Archive for March, 2007

Extension Method : A New Orcas Feature

Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type.  Extension Methods help blend the flexibility of “duck typing” support popular within dynamic languages today with the performance and compile-time validation of strongly-typed languages.

Using the new “extension method” language feature in C# and VB, I can instead add a useful ”IsValidEmailAddress()” method onto the string class itself, which returns whether the string instance is a valid string or not.  I can then re-write my code to be cleaner and more descriptive like so:

string email Request.QueryString["email"];
if 
( email.IsValidEmailAddress() ) {   }

How did we add this new IsValidEmailAddress() method to the existing string type?  We did it by defining a static class with a static method containing our “IsValidEmailAddress” extension method like below:

public static class infovishExtensions
{
    
public static bool IsValidEmailAddress(this string s)
    {
        Regex regex 
= new Regex(@”^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$”);
        return 
regex.IsMatch(s);
    
}
}

Note how the static method above has a “this” keyword before the first parameter argument of type string.  This tells the compiler that this particular Extension Method should be added to objects of type “string”.  Within the IsValidEmailAddress() method implementation I can then access all of the public properties/methods/events of the actual string instance that the method is being called on, and return true/false depending on whether it is a valid email or not.

To add this specific Extension Method implementation to string instances within my code, I simply use a standard “using” statement to import the namespace containing the extension method implementation:

using infovish;

The compiler will then correctly resolve the IsValidEmailAddress() method on any string. Just write in like :

if ( email.IsValidEmailAddress(“infovish@infovish.com”) ) { } ………
Read from : http://msdn.microsoft.com/dotnetrocks/

Leave a Comment

Problem with ClientScript.RegisterClientScriptBlock when using Ajax

There’s a breaking change in the beta. to insert scripts during a partial postback youmust use the registerXXX static methods of the scriptmanager class. 

e.g.
Microsoft.Web.UI.ScriptManager.RegisterClientScriptBlock(DropDownList1, typeof(DropDownList),“TestKey”,” alert(‘TEst Key’); “,true);

Comments (6)

Missing Intellisense within ASP.NET AJAX Controls

Sometimes Markup intellisense no longer works for controls or for any controls nested within ajax controls. We discovered a bug with the VS markup intellisense engine when doing the ASP.NET AJAX Beta1 release – which is that you lose intellisense when you map multiple assemblies against the <asp:> tag prefix and use the controls within a <asp:content> control in a .aspx page based on a master page. 

Preferred Solutions :

1) . Either Install VS SP1.
2). Let Master Page open. It turns out the intellisense engine only runs into issues if the .master file is closed.  As long as it is open within the same IDE, it resolves the assemblies just fine and will give you full intellisense.
3). Change Tag Prefix <asp> to any other tag, lets say <ajx> in web.config.

Comments (1)

Saving Application settings in a Windows Application

Many a times in the windows application when you create some settings, we ned to save the settings so that it can be retrieved and used when the user starts the application again. In Dot net this can be done very easily.

You need to save these settings in the Application settings. The scope of these setting should be user and not application. Remember the Settings with the scope of Application are readonly and hence these cannot be changed in the code.

Now to retrieve the settings use the following code

Properties.Settings.Default["SettingName"].ToString();

To change the settings for the user you need to

Properties.Settings.Default ["SettingName"] = “Value”;
Properties.Settings.Default.Save();

The setting is changed by setting the property value. But if you do not save the setting the changed setting will not be available next the application restart.

Leave a Comment

How to send mail in Asp.Net 2.0 with read receipt

Many a time we want to add read receipt header to the Email we sent. A read receipt is a notification method where by an Email is sent to the given Email address when the mail is first read. To add a read receipt Notification to the Email in Asp.net we need top add the header Disposition-Notification-To in the Email. This can be done very easily by one line of code.

mail.Headers.Add("Disposition-Notification-To", "<EmailAddress@mydomain.com>");

If we add this header to the element the read receipt Email will be sent to the EmailAddress@mydomain.com.

Although this header is recognized by most of the mail clients, this might not work with all the mails. There can be many reason for this. The mail client may not recognize the header and hence not send any notification.

Comments (2)

Anonymous Methods in C#

You must be aware of delegates if you have worked in C# before. Even then let me describe delegates my way. Delegates are objects that encapsulate the reference to functions. Implementation of Event Handler code is one of the best examples of delegates.

When we double click on a button on the form to add the handler for that button’s click event, the windows form generate two separate codes. The actual event Handler and a hidden code (found in the designer code) to wire-up the button clicks event.

The code outputted is like this.

private void button1_Click(
  object sender, System.EventArgs e)
{ }
and

this.button1.Click +=   new System.EventHandler(
  this.button1_Click);

[Note: The Signature for the button click event handler is defined in the System.EventHandler delegate]

We can simplify this a bit by using anonymous method. We can create the whole handler method inline without defining a method name. We will still require the patameters.

this.button1.Click += 
  delegate(object sender, EventArgs e)
  {    };

Here you can see there is no method name and we are not delegating the event to another method instead writing the method inline.

Comments (1)

Difference between the truncate and the delete command

In SQL server 2000 there are 2 main keywords for deleting data – Truncate and delete. Although the end result might be same but both work very differently. We should take into consideration the advantages, limitation and the consequences when using one of them.

When we use the delete statement, SQL server deletes one row at a time. Each row is logged in the transaction LOG. This also means theta the server will also maintain the Log Sequence number. This will consume more database more resource in the database and the process will be slow. But this also gives an advantage. The transaction can be rolled back as there are transaction log.

Also you can use the where clause with the delete command but not with the truncate command. With truncate command it’s all records or nothing. Also one more advantage of the truncate command is that it also resets the identity seed of the table. Also the fact that deallocated pages is returned to the system for use in other areas.

Truncate statements cannot be used on the tables involved in log shipping or replication. This is because they both depend on the transaction log to keep the database consistent. Truncate table cannot be used with tables having foreign key references. As the truncate command do not fire any triggers. If you want to use the truncate command with a foreign key, you need to first drop the index and then add it again after using the truncate table command.

Comments (2)

Suspend the execution of a connection for a given time interval in SQL

SQL server 2000 also has a WAITFOR keyword to suspend the execution of a connection for a given time interval or a specified day of time has reached. The WAITFOR command can be specified with either of the two clauses.

The delay keyword with the amount of time to be passed before the WAITFOR statement is completed. This time can be up to 24 hours. Or we can use the time keyword followed by a time to specify the completion of the WAITFOR statement.

Here are two example of using the statement.

WAITFOR DELAY ‘00:00:02′

SELECT * FROM CATEGORIES

This example delays the execution of the select statement by 2 seconds.

BEGIN

   WAITFOR TIME ‘23:00′

   DBCC CHECKALLOC

END

The above example waits until 11 PM to perform a check on the given database and make sure that all the pages in the database are allocated and used.

Remember that the connection from the application remains suspended until the WAITFOR completes. WAITFOR is best used when an application or stored procedure must suspend processing for some relatively limited amount of time.

Leave a Comment

Static Class – A When to use class

We use static class when we have to separate data and behavior that will be independent of any object identity. The data and functions do not change regardless of what happens to the object.  

A static class can only contain static members. We cannot create an instance of a static class. Static class is always sealed and they cannot contain instance constructor. Hence we can also say that creating a static class is nearly same as creating a class with only static members and a private constructor (private constructor prevents the class from being instantiated).

The advantage of using the static class is that compiler can check that no instance of the class is accidentally added. The complier will not allow any instance class of a static class. We also cannot inherit a static class since it is sealed. Static class do not have constructor, but can still declare static constructor to set up the initial values.

Static class also makes the implementation simpler and faster since we do not have make and instance of the class to call its method.  An example of good use of static class would be a class like math, which does all the mathematic function, or a currency converter class to convert currency class for converting the currency.

Comments (1)

SQL Page number and Page Size Query : Best One

 It will return records 61-80.

DECLARE @PageSize int
DECLARE
@PageNumber int
DECLARE
@intBeginRecord int
DECLARE
@intEndRecord int
SET
@PageNumber = 4
SET @PageSize = 20

SET @intBeginRecord= ((@PageNumber - 1) * @PageSize) + 1;
SET @intEndRecord = @PageNumber * @PageSize;
WITH TestTable  as
(
SELECT ROW_NUMBER() OVER( ORDER BY StateAbbr ASC ) AS ROWNUMBER, UserMaster.UserID, UserMaster.StateAbbr FROM UserMaster
)
SELECT * FROM TestTable  WHERE RowNumber between CONVERT(varchar,@intBeginRecord) and CONVERT(varchar, @intEndRecord)

Leave a Comment

Older Posts »