Sep 21

It is not the way to fight spams on blogs, but for professional look for websites, duplicate comments should not be allowed. This feature is common among most popular blogs and forums, so i bring this simple extension to add this feature to BlogEngine.

To enable this extension just upload it to your extension directory under App_Code.

The extension is attached with this post.

ValidateComments.cs (1,014.00 bytes)

Sep 04

BlogEngine.NET SendMailMessage issue

Posted By Ahmed El-Kilani On 04 Sep 2009 3 Comments »
BlogEngine.NET is one of the best .NET blogs over there. I have changed to blogengine for its simplicity and themes support and customizability.
Sending mail from BlogEngine sometimes does not work. Why?
BlogEngine uses different email addresses as "Sender email" i.e "From", for example: the email of the comment poster is used as the sender notification email.
Most of the SMTP severs like godaddy only replay emails sent from only addresses hosted at the same domain as the blog is hosted, for security and spam-fighting reasons.

To fix this issue add the following to BlogSettings class under BlogEngine.Core:
/// 
/// Gets or sets the e-mail address notifications are sent from.
/// 
public string SenderEmail { get; set; }
Then we need to add the following node to settings.xml under BlogEngine.Web/App_Data
sendername@example.com
And finally a little modification in SendMailMessage method in Util class under BlogEngine.Core
/// 
/// Sends a MailMessage object using the SMTP settings.
/// 
public static void SendMailMessage(MailMessage message)
{
	if (message == null)
		throw new ArgumentNullException("message");

	try
	{
        //Override sender email which was set from contact or comment forms:
        MailAddress senderEmail = new MailAddress(BlogSettings.Instance.SenderEmail, message.From.DisplayName);
        message.From = message.ReplyTo = message.Sender = senderEmail;
		message.IsBodyHtml = true;
		message.BodyEncoding = Encoding.UTF8;
		SmtpClient smtp = new SmtpClient(BlogSettings.Instance.SmtpServer);
        // don't send credentials if a server doesn't require it,
        // linux smtp servers don't like that 
        if (!string.IsNullOrEmpty(BlogSettings.Instance.SmtpUserName)) {
		    smtp.Credentials = new System.Net.NetworkCredential(BlogSettings.Instance.SmtpUserName, BlogSettings.Instance.SmtpPassword);
        }
		smtp.Port = BlogSettings.Instance.SmtpServerPort;
		smtp.EnableSsl = BlogSettings.Instance.EnableSsl;
		smtp.Send(message);
		OnEmailSent(message);
	}
	catch (SmtpException)
	{
		OnEmailFailed(message);
	}
	finally
	{
		// Remove the pointer to the message object so the GC can close the thread.
		message.Dispose();
		message = null;
	}
}
Aug 26
An interesting way to declare a variable in the same name as a reserved keyword in C# by prefixing @ before the variable name: Example:
int @int = 0;
This creates a variable name int holding the value 0.
May 20

Modal Ajax UpdateProgress Control

Posted By Ahmed El-Kilani On 20 May 2008 No Comments »

UpdateProgress control which is included with AjaxExtentions works with UpdatePanel control to keep users informed about the progress of the partial postback.
UpdateProgress is important for users to know the current process which is processed by UpdatePanel , so that users is going to wait until the process has completed, clicking a button more than one time or refreshing the page is a bad action usually taken by users in the same situations.

So, I have developed this UpdateProgress to prevent users from preforming any action until UpdatePanel progress is complete. This class is a web control that overrides the UpdateProgress template and inject a modal template which is like AjaxModalPopupExtender, disables page controls until the process is complete.

namespace AjaxedControls
{
    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.ComponentModel;

    /// 
    /// Summary description for AjaxUpdateProgress
    ///    
    public class AjaxUpdateProgress : Control
    {
        UpdateProgress ajaxUpdateProgress;
        
        protected override void  OnLoad(EventArgs e)
        {
            ajaxUpdateProgress = new UpdateProgress();
            ajaxUpdateProgress.ID = "ajaxUpdateProgress";
            ajaxUpdateProgress.DisplayAfter = 0;
            ajaxUpdateProgress.ProgressTemplate = new CustomProgressTemplate(_loadingHTMLText);
            this.Controls.Add(ajaxUpdateProgress);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            //For flexible use (only one .cs file) i added the css style script here.
            //If you are to compile this control into a separate assembly, it is better to move this script to an external .css file.
            writer.Write(@"
                ");

            base.Render(writer);
        }

        #region Properties

        string _loadingHTMLText = "Loading...";

        [Description("HTML text displayed in the loading area.")]
        [DefaultValue("Loading...")]
        public string LoadingHTMLText
        {
            set
            {
                _loadingHTMLText = value;
            }
            get
            {
                return _loadingHTMLText;
            }
        }

        Boolean _renderCss = true;

        [Description("Gets or sets whether to render css styles for the loading text, else you can add your custom styles to the page.")]
        [DefaultValue(true)]
        public Boolean RenderCss
        {
            get { return _renderCss; }
            set { _renderCss = value; }
        }

        #endregion
    }



    /// 
    /// Progress template for AjaxUpdateProgress control.
    /// 
    internal class CustomProgressTemplate : ITemplate
    {

        internal CustomProgressTemplate() { }

        internal CustomProgressTemplate(string loadingHTMLText)
        {
            _loadingHTMLText = loadingHTMLText;
        }

        #region ITemplate Members

        public void InstantiateIn(Control container)
        {
            //Override UpdateProgress progress template.
            container.Controls.Add(new LiteralControl(@"
            
            
            
{0}
".Replace("{0}", _loadingHTMLText) )); } string _loadingHTMLText; public string LoadingHTMLText { set { _loadingHTMLText = value; } } #endregion } }
Apr 29

Powerful Codesmith data layers templates

Posted By Ahmed El-Kilani On 29 Apr 2008 No Comments »

Codesmith tools is one of the powerful template-based code generation tool. For more info go to www.codesmithtools.com

Codesmith has various predefined templates for genrating domain model, N-tires, CSLA and NHibernate classes or mapping files.
In fact none of predefined templates are suitable for easy and quick use. NetTiers is the best but it needs a lot of customization and also generates a lot of code which is not necessary in most cases.
Today I come with a Generator template to generate domain model classes and data access layer and also CRUD stored procedures.

The final output of the template (generated for Northwind Category table) is figured below:

SqlDB class is the class containing Execute, ExecuteScalar, ExecuteReader, FillTable methods, which are responsible for creating database connection and execute queries and stored procedure on the database.

AbstractDataProvider is the base class for each Entity DataProvider class, it abstracts the definitions for the common base methods such as select, insert, update and delete.

AbstractEntity Class is the base class for each Entity class. IComparable interface is implemented to allow dynamic sorting for domain objects into lists; for more info about default comparer see :
http://blogs.a-h-m-e-d.com/Blogs/post/Another-dynamic-comparer-for-sorting-lists-(-very-simple-).aspx

Features:
- DeleteByFlag:

This feature allows you to specify a boolean column in a given table to be a flag for deleted rows instead of deleting them permenantly from database.
Select stored procedures select only rows of a table which has the DeleteFlagColumn set to 0 (False). Delete stored procedure just updates the colum to 1 (True) instead of the delete action.

-UseCollection:
Returned rows can be returned as generic lists if UseCollections option is set to True else a DataTable is returned.

-Generator template:
This template will generate all classes and stored procedures needed for interaction with database for given table(s).

Generator.rar (13.38 KB)

Jan 26
If you want to sort a list of objects, then your objects needs to implement IComparer or IComparable interfaces. Strings, Integers and even DateTime objects implement IComparable; but if you need to sort your custom objects then these objects need to implement IComparable. Implementing IComparable is easy but quite boring, since your business objects may have plenty of properties that you need to compare. Click here to know more about IComparable interface.

To get out of this boring task I have written an abstract class that works as a base class for any business object. This class uses reflection to dynamically compare any property, without having to implement CompareTo() method in the derived class.

The Code:
abstract class DefaultComparer : IComparable
{
    public string SortExpression;
    public bool IsAscending = true;

    public int CompareTo(object obj)
    {
        PropertyInfo pInfo = this.GetType().GetProperty(SortExpression);
        if (null == pInfo) return 0;
        int rel = IsAscending ? 1 : -1;
        return ((IComparable)pInfo.GetValue(this, null)).CompareTo(pInfo.GetValue(obj, null)) * rel;

    }

}

The object:
class Custom : DefaultComparer
{
    private int _id;

    public int ID
    {
        get { return _id; }
        set { _id = value; }
    }
    private string _name;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

}

Usage:
List list = new List();
Custom c1 = new Custom();
c1.ID = 3;
c1.Name = "Ahmed";            
Custom c2 = new Custom();
c2.ID = 2;
c2.Name = "Mohammed";            
list.Add(c1);
list.Add(c2);

list[0].SortExpression = "Name";
list[0].IsAscending = false;
list.Sort();

foreach (Custom c in list)
{
    Console.WriteLine(c.ID + " : " + c.Name);
    Console.WriteLine();
}

Nothing else is needed ;)
Jan 10

Visual studio Code Snippets feature

Posted By Ahmed El-Kilani On 10 Jan 2008 No Comments »

Code snippets is one of the coolest features and enhancements that Visual Studio 8 provides. Code snippets is XML-based templates for reusable code, it can help you write your code faster so that increases developer productivity.
I am going to demonstrate a custom code snippet template which can help you write your data access queries faster; The snippet will generate the following code: 

SqlConnection con = new SqlConnection("Connection String"); 
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text; 
cmd.CommandText = "Command Text"; 
try { 
    con.Open();
    cmd.ExecuteNonQuery(); 
} 
catch (SqlException ex) 
{ 
    //throw new Exception(ex.Message);
} 
finally 
{ 
    cmd.Dispose(); 
    con.Close(); 
}
   

To start out go to:
C:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C# 
*Change "c:/program files" to where you've installed visual studio
You will find a lot of *.snippet files which are shipped with MS Visual studio. To define our own snippet create a file named "SqlConnection.snippet" then write the following and save the file inside the current location:

<?xml encoding="utf-8" version="1.0" ?>
<CODESNIPPETS xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CODESNIPPET Format="1.0.0">
<HEADER>
<SHORTCUT>sqlcon</SHORTCUT>
<DESCRIPTION>Code snippet for Sql Connection with command execution</DESCRIPTION>
<AUTHOR>aHmeD eL-kiLaNi</AUTHOR>
<SNIPPETTYPES>
<SNIPPETTYPE>Expansion</SNIPPETTYPE>
<SNIPPETTYPE>SurroundsWith</SNIPPETTYPE>
</SNIPPETTYPES>
</HEADER>
<SNIPPET>
<DECLARATIONS>
<LITERAL>
<ID>con</ID>
<TOOLTIP>SqlConnection object.</TOOLTIP>
<DEFAULT>con</DEFAULT>
</LITERAL>
<LITERAL>
<ID>cmd</ID>
<TOOLTIP>SqlCommand object.</TOOLTIP>
<DEFAULT>cmd</DEFAULT>
</LITERAL>
</DECLARATIONS>
<CODE language=csharp>

</CODE>
</SNIPPET>
</CODESNIPPET>
</CODESNIPPETS>

Variable declaration:
The following lines defines variables that would be used in our snippet:
<Literal>
     
<ID>con</ID>
     
<ToolTip>SqlConnection object.</ToolTip>
       
<Default>con</Default>
 
</Literal>

Code snippet:
Inside  <Code> element write your custom code; use the literals (variables) - defined before - inside codesnippet putting $ right before and after variable names.

After finishing save the template. Now with your visual studio IDE go to where you want to generate this code and (press ctl+k+x); a snippet drop-down menu would be popped up, click SqlConnection and you're done!!

Note: if you've saved the .snippet file in another place you can import it using VS IDE: (press ctl+k+b) and import the *.snippet file under your desired language.

Jan 08

Database backup and restore are the most important actions we need for our published web applications. Some shared hosts like Godaddy do not allow backup/restore for your databases, although godaddy has introduced backup/restore actions but is only for backup files (*.bak) have been created by their system, however *.bak files that made from local machines or any other system cannot be restored.
Here is how to backup/restore databases programatically without the need to execute backup or restore commands.

Backup:
You can backup all or choosen tables into an xml file. The following command gets all table: 

SELECT TABLE_NAME
FROM   INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE 'BASE TABLE' AND
TABLE_NAME <> 'dtproperties'

By selecting all from the retrieved tables into one dataset and then calling DataSet.WriteXml() , would write all tables data into one xml file.

foreach (string table in tables)
{
    cmd.CommandText 
= string.Format("SELECT * FROM [{0}]",table);
    
DataTable dt = new DataTable(table);
    
da.Fill(dt);
    
ds.Tables.Add(dt);              
}


Restore:
1-
First step is to disable all constraints and delete all data in each table before insert statement can execute:

string beforeInsertComm = string.Empty;
beforeInsertComm "sp_msforeachtable \"ALTER TABLE ? NOCHECK CONSTRAINT all\" ";
beforeInsertComm +"DELETE [{0}]";
beforeInsertComm = string.Format(beforeInsertComm, table);
cmdBeforeInsert.CommandText beforeInsertComm;
cmdBeforeInsert.Connection.Open();
cmdBeforeInsert.ExecuteNonQuery();
cmdBeforeInsert.Connection.Close();
sb.Append(beforeInsertComm);

ALTER TABLE statement will disable constraint for all database tables, and will automatically be restored to its default value when closing the connection; therefore ALTER statement must be followed by DELETE statement in the same command execution so that DELETE execution will not be violated with foreign key constraints.

2- Restoring data read from xml by DataSet.ReadXml() to the database:
a- We must set indentity_insert to on to allow insert into identity columns:

string beforeInsertComm "IF(EXISTS(SELECT Name FROM SYSCOLUMNS WHERE COLUMNPROPERTY(OBJECT_ID('{0}'),Name,'ISIDENTITY') = 1))BEGIN ";
beforeInsertComm +"SET IDENTITY_INSERT [{0}] ON END ";
beforeInsertComm = string.Format(beforeInsertComm, dt.TableName);

b- Now comes the generating insert command for the given table:

sb.Append("INSERT INTO [" + dt.TableName + "](");
for 
(int 0x < dt.Columns.Countx++)
{
    
string column dt.Columns[x].ColumnName;
    
sb.Append("[" + column + "]");
    if 
(x < dt.Columns.Count - 1)
        sb.Append(
",");
}
sb.Append(
") VALUES (");
for 
(int 0y < dt.Columns.County++)
{
    
string column dt.Columns[y].ColumnName;
    
sb.Append("@" + column);
    if 
(y < dt.Columns.Count - 1)
        sb.Append(
",");

    
SqlParameter p = new SqlParameter();
    
p.ParameterName "@" + column;
    
p.SourceColumn column;
    
cmdInsert.Parameters.Add(p);
}
sb.Append(
")");


3- Reenable constraints:

sp_msforeachtable "ALTER TABLE ? CHECK CONSTRAINT all" 


Note:
For better performance ,Bulk insert command is one of the fastest solutions but can only run under sysadmin or bulkadmin roles.

Source code is available within attachments.
Hope that helps,
Enjoy

BackupRestore.rar (182.7 KB)
Dec 30

Hidden vs Overridden methods in C#

Posted By Ahmed El-Kilani On 30 Dec 2007 No Comments »

The difference between hiding and overriding methods is that override keyword will completely override the method over its parent's, but new keyword will only hide the method from its class reference.
The following code snipset illustrates some trials for hiding and overring methods :

class Parent
{
    
public void HiddenMethod()
    {
        Console.WriteLine(
"Parent Hidden Method");
    
}
    
public virtual void VirtualMethod()
    {
        Console.WriteLine(
"Parent Virtual Method");
    
}
    
public virtual void VirtualHiddenMethod()
    {
        Console.WriteLine(
"Parent Virtual Hidden Method");
    
}

}
class Child : Parent
{
    
public new void HiddenMethod()
    {
        Console.WriteLine(
"Child Hidden Method");
    
}

    
//Compilation error, since HiddenMethod in the base class is not virtual
    //public override void HiddenMethod()
    //{
    //    Console.WriteLine("Child Hidden Method");
    //}


    
public override void VirtualMethod()
    {
        Console.WriteLine(
"Child Virtual Method");
    
}
    
public new void VirtualHiddenMethod()
    {
        Console.WriteLine(
"Child Virtual Hidden Method");
    
}

}

Non-virtual methods can only be hidden while virtual methods can be hidden or overridden; but the difference between virtual and new comes into the picture when playing with object references:

static void Main(string[] args)
{
    Child c 
= new Child();
    
c.HiddenMethod();
    
c.VirtualMethod();
    
c.VirtualHiddenMethod();

    
Console.WriteLine("----");

    
Parent pc = new Child();
    
pc.HiddenMethod();
    
pc.VirtualMethod();
    
pc.VirtualHiddenMethod();
}

Output :

Child Hidden Method
Child Virtual Method
Child Virtual Hidden Method 
----
Parent Hidden Method
Child Virtual Method
Parent Virtual Hidden Method 

pc is a Child object with a Parent reference. pc calls Parent hidden methods and Child overriden methods.

Dec 26

Qyering Many-To-Many data with HQL

Posted By Ahmed El-Kilani On 26 Dec 2007 1 Comments »

Yesterday while I was coding in my company media gallery project I faced a case in which multiple joins between  many-to-many tables have to be constructed. With a simple HQL query I could easily have it done.
Again, NHibernate rocks.

Channels have many media TV shows to be shown which media may be shown in a channel or more.

With this one line we could get all media under a certain channel.

Select m From Media m,Channel c WHERE m in elements(c.ChannelMedia) AND c.Id=:Id

Channel Entity has ChannelMedia collection which has a list of media and Media Entity has ChannelMedia collection which has a list of channels. Because they are related together many to many, so I only have to check that Media is an element in the ChannelMedia collection of the given Channel.