Partial Methods

You may have heard about Partial Class in C#. But you may not be knowing about partial methods in C#. So, here I am writing a blog about Partial Methods in C# 3.0 (Here, I have assumed that you are aware of basic concepts of LINQ to SQL.).

Application:

Partial Method are used extensively in LINQ. Here, I am showing the application of this feature in action. You may be knowing that LINQ to SQL is an O/R mapper. You can perform database operations like inset/update/delete on the database tables using LINQ to SQL. There may be situations where you may need to perform validation rules on the entity before the entiry is added/updated to the database. In LINQ to SQL, You can do this by using On<ProperyName>Changing methods of the properties.

Here, in my database I have table called Profile. This table has a field named email. We want to validate the email of user before the Profile is added or updated. This can be achieved by adding method OnemailChanging in the Profile class. (LINQ to SQL generates the Partial class for the tables added in the Designer. Here, I have added Profile table in the designer. So LINQ to SQL will generate the Partial class named Profile.) The implementation of this method is as follows:

public partial class Profile
{
     partial void OnemailChanging(string value)
     {
          Regex reg = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");

          if(!reg.IsMatch(value))
          {
               throw new Exception("Not a Valid Email!");
          }
     }
}

So, this method validates the email of the record being added/updated. Our motive is achieved. The email is validated before the entity is added/updated. But how? Yes! Using Partial Methods.

Partial Methods:

If you will look closely at the above code. The method OnemailChanging is marked as partial method. Partial Methods enable us to perform light-weight event handling. Here in the above snippet of code, we have defined the OnemailChanging method of Profile class. This partial method is declared in the Class generated by LINQ to SQL.

Here, I have listed some of the rules of Partial Methods:

• Partial methods must be declared within partial classes
• Partial methods are indicated by the partial modifier
• Partial methods do not always have a body (well look at this more below)
• Partial methods must return void
• Partial methods can be static
• Partial methods can have arguments (including this, ref, and params modifiers)
• Partial methods must be private

Sending email in ASP.NET 2.0

System.Net.Mail namespace provides classes to send email. To send email, we need to create object of MailMessage class and set its properties. Then create instance of SmtpClient class and send email by calling SmtpClient class send method which accepts MailMessage object as its argument.

The SMTP server information used by the SmtpClient class can be specified programmatically, through the SmtpClient class’s properties, or can be specified in Web.config file. To use the Web.config approach, we need to add <system.net> element within the <configuration> element. Then, add a <mailSettings> element that contains an <smtp> element whose settings are specified within its <network> child element, as below.

<configuration>
<!-- Add the email settings to the <system.net> element -->
<system.net>
<mailSettings>
<smtp>
<network
host="localhost"
port="25"
userName="username"
password="password" />
</smtp>
</mailSettings>
</system.net>

</configuration>
Dim ToAddress As String = "you@youremail.com"
Dim FromAddress As String = "info@localhost.com"
Dim mm As New MailMessage(FromAddress, ToAddress)
mm.Subject = "Mail Subject"
mm.Body = "Mail Body"
mm.IsBodyHtml = True
Dim smtp As New SmtpClient
smtp.Send(mm)

Sql Bulk Copy in .Net

Sometimes, we need to insert a large amount of data in sql table. .Net Framework 2.0 and later version contain a “SqlBulkCopy” class in “System.Data.SqlClient” namespace.

SqlBulkCopy provides simplest and fastest way to copy large amounts of data to SqlServer, Instead of inserting all data row by row.

Here, is the example of SqlBulkCopy class

private void BulkCopy(DataTable dtSource, string strDestinationTableName)
{
   SqlConnection sqlCon = new SqlConnection("Your Connection String");
   SqlBulkCopy sqlBC = new SqlBulkCopy(sqlCon);
   sqlBC.DestinationTableName = strDestinationTableName;

   /*
   Here is the column mapping to the source and destination table.
   You can also use column name instead of column index for mapping.   
   */

   //sqlBC.ColumnMappings.Add(SourceTableColumnIndex, DestinationTableColumn Index

   sqlBC.ColumnMappings.Add(0, 0);     
   sqlBC.ColumnMappings.Add(1, 1);
   sqlBC.ColumnMappings.Add(2, 2);
   sqlBC.ColumnMappings.Add(3, 3);
   sqlBC.ColumnMappings.Add(4, 4);

   try
   {
    sqlCon.Open();
    sqlBC.BatchSize = 500; //BatchSize Indicates the total number of rows sent to the server at a time.
    sqlBC.WriteToServer(dtSource);
    sqlCon.Close();
   }
   catch (Exception ex)
   {
    if (sqlCon.State == ConnectionState.Open)
        sqlCon.Close();
    throw ex;
   }
}

Variable declaration

Hello all,

Today, I am writing some common naming convention for declaring variables.

Camel Notation : The first letter is lowercase and each appended word begins with an uppercase letter. For e.g.: var myTestVar = 0

Pascal Notation : The first letter is uppercase and each appended word begins with an uppercase letter. For e.g.: var MyTestVar = 0

Hungarian Type Notation : Pretends a lowercase letter to the beginning of a Pascal Notation variable name to indicate the type of the variable. For e..g.: var iMyTestVar = 0 where i for integer.

Convert string into title case in c#

The System.String class contains methods ‘ToUpper’ and ‘ToLower’ which convert the string to Uppercase and Lowercase. But String class does not have the Title Case conversion.

‘TextInfo’ class provide this method. It is in System.Globalization.

using System.Globalization;
TextInfo myText = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo;
string sample = "this IS a blog for net";
string titleCase = myTextInfo.ToTitleCase(sample);
Response.Write(titleCase);

Output : This Is A Blog For Net

Password Strength Meter

To show password strength following function is useful.

function passwordChanged() 
{
var strength = document.getElementById('strength');

var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$", "g");

var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");

var enoughRegex = new RegExp("(?=.{6,}).*", "g");

var pwd = document.getElementById("password");

var strColor;
var strText;
var strWidth;

if (pwd.value.length == 0) 
{
strText = 'Type Password'; strColor = 'White'; strColor = "#cccccc";strWidth = 150;
} 
else if (false == enoughRegex.test(pwd.value)) 
{
strText = 'Very Weak!'; strColor = 'White'; strColor = "red"; strWidth = 50;
} 
else if (strongRegex.test(pwd.value)) 
{
strText = '<span style="color: green;">Strong!</span>';
strColor = "green"; strWidth = 150;
} 
else if (mediumRegex.test(pwd.value)) 
{
strText = '<span style="color: orange;">Medium!</span>';
strColor = "orange"; strWidth = 100;
} 
else 
{
strText = '<span style="color: red;">Weak!</span>';
strColor = "#E41B17"; strWidth = 75;
}

strengthBar.style.backgroundColor = strColor;
strengthBar.style.width = strWidth;
strength.innerHTML = strText;

}

Add two div tag in page.

<input id="password" onkeyup="return passwordChanged();" type="password" maxlength="20" name="password" size="15" />
<div id="strength">Type Password</div>
<div id="strengthBar" style="height: 2px; width: 150px; border: 1px solid black; background-color: #cccccc;"></div>