Labels

Thursday, May 31, 2007

Checking for null values is tricky

Checking for null values is tricky. Testing a variable only against null could give quite misleading results.

 

There is difference between a method not returning any value and a method returning a value where the content of the value is null. Consider following code snippet.

 

using (SqlConnection conn = new SqlConnection(connString))
{
                SqlCommand cmd = new SqlCommand("SELECT Color FROM Production.Product WHERE ProductID = 1", conn);
                conn.Open();
                object result = cmd.ExecuteScalar().ToString();

 

                if (result == null)
                    MessageBox.Show("Product not found");
                else if (result == System.DBNull.Value)
                    MessageBox.Show("Product found but Color is null");
                else MessageBox.Show(result.ToString());

}

In first case, the ExecuteScalar method doesn't return any result which means that the product is not found. In second case, the product is found but the value of color is stored as null. And in third case, the product is found and the value of it's color is non-null.

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Monday, May 28, 2007

Framesets

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Frames.aspx.vb" Inherits="Frames" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Untitled Page</title>

 

</head>

   

   

    <frameset framespacing="0" border="false" frameborder="0" rows="120,*,15,0">

                                <frame name="header" src="Default.aspx" frameborder="1" marginwidth="0"  marginheight="0" framespacing="0" scrolling="no">

        <frameset id="frmBody"  framespacing="1" border="false" frameborder="0" cols="200,*">

            <frame name="menu" src="Default2.aspx"  style="top: 20px"  frameborder="1" marginwidth="0" marginheight="0" framespacing="0" scrolling="auto" noresize>           

            <frame name="master" src="Default3.aspx" style="top: 20px" frameborder="1" marginwidth="0" marginheight="0" framespacing="0" scrolling="auto" noresize>                                                 

        </frameset>

                </frameset>

               

 

</html>

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Sunday, May 27, 2007

ASP.NET 2.0 - Tips & Tricks V1.0

ASP.NET 2.0 offers some great new features that you can implement with a minimal amount of code.  I wanted to start a list of some of the most simple (yet cool) things you could do with it that required little or no C#/VB.NET code. 

 1.  Maintain the position of the scrollbar on postbacks:  In ASP.NET 2.0 you can simply add the MaintainScrollPostionOnPostBack attribute to the Page directive:

<%@ Page Language="C#" MaintainScrollPositionOnPostback="true" AutoEventWireup="true" CodeFile="..." Inherits="..." %>

2.  Set the default focus to a control when the page loads:  Using the DefaultFocus property of the HtmlForm control you can easily do this.

<form id="frm" DefaultFocus="txtUserName" runat="server">
  ...
</form>

3. Set the default button that is triggered when the user hits the enter key:  You can now use the HtmlForm control's DefaultButton property to set which button should be clicked when the user hits enter.  This property is also available on the Panel control in cases where different buttons should be triggered as a user moves into different Panels on a page.

<form id="frm" DefaultButton="btnSubmit" runat="server">
  ...
</form>

4. Locate nested controls easily: Finding controls within a Page's control hierarchy can be painful but if you know how the controls are nested you can use the lesser known "$" shortcut to find controls without having to write recursive code.  If you're looking for a great way to recursively find a control. The following example shows how to use the DefaultFocus property to set the focus on a textbox that is nested inside of a FormView control.  Notice that the "$" is used to delimit the nesting:

<form id="form1" runat="server" DefaultFocus="formVw$txtName">
    <
div>
        <
asp:FormView ID="formVw" runat="server">
            <
ItemTemplate>
               
Name: 
                
<asp:TextBox ID="txtName" runat="server" 
                   
Text='<%# Eval("FirstName") + " " + Eval("LastName") %>' />
            </
ItemTemplate>
        </

This little trick can also be used on the server-side when calling FindControl(). Here's an example:

TextBox tb = this.FindControl("form1$formVw$txtName"as TextBox;
if 
(tb != null)
{
    
//Access TextBox contro! l
}

5. Strongly-typed access to cross-page postback controls:  If you have a page called Default.aspx that exposes a public property that returns a Textbox that is defined in the page, the page that data is posted to (say SearchResults.aspx) can access that property in a strongly-typed manner by adding the PreviousPageType directive into the top of the page:

<%@ PreviousPageType VirtualPath="Default.aspx" %>

By adding this directive, the code in SearchResults.aspx can access the TextBox defined in Default.aspx in a strongly-typed manner.  The following example assumes the property defined in Default.aspx is named SearchTextBox.

TextBox tb PreviousPage.SearchTextBox;

6. Strongly-typed access to Master Pages controls: If you have public properties defined in a Master Page that you'd like to access in a strongly-typed manner you can add the MasterType directive into a page as shown next:

<%@ MasterType VirtualPath="MasterPage.master" %>

You can then access properties in the target master page from a content page by writing code like the following:

this.Master.HeaderText "text updated using MasterType directive with VirtualPath attribute.";

7. Validation groups: You may have a page that has multiple controls and multiple buttons.  When one of the buttons is clicked you want specific validator controls to be evaluated rather than all of the validators defined on the page. Here's an example:

<form id="form1" runat="server">
    Search Text: <asp:TextBox ID="txtSearch" runat="server" /> 
    <
asp:RequiredFieldValidator ID="valSearch" runat="Server" 
      ControlToValidate
="txtSearch" ValidationGroup="SearchGroup" /> 
  

8. Finding control/variable names while typing code:  This tip is a bit more related to VS.NET than to ASP.NET directly. After typing the first few characters of a control/variable name, hit CTRL + SPACEBAR and VS.NET will bring up a short list of matching items. For those who are interested, Microsoft made all of the VS.NET keyboard shortcuts available in a nice downloadable and printable guide-

http://www.microsoft.com/downloads/details.aspx?FamilyID=c15d210d-a926-46a8-a586-31f8a2e576fe&DisplayLang=en

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Thread Safe Version of SingleTon

Most common way of creating Singleton class :

private static SingletonClass Instance = null;

public static SingletonClass GetInstance()

{

if (Instance == null)

Instance = new SingletonClass();

return Instance;

}

But this method is not thread safe! Imagine two threads simultaneously checking if the instance of the class is null, when it is actually null! Both of these threads will create instance of our singleton class which is not what we want.

The Thread Safe way of creating a singleton class:

private static SingletonClass Instance = null;

private static readonly object lockingObject = new object();

public static SingletonClass GetInstance()

{

//Lock the shared object and then check for creating the class instance

lock (lockingObject)

{

if (Instance == null)

Instance = new SingletonClass();

return Instance;

}

}

Now this way of creating the singleton class is completely thread safe but what about the performance issues? Unfortunately, every time we want an instance of this class, we have to acquire the lock which affects the performance badly if our application is a heavily threaded application.

Improved: The thread safe, but a not so lazy implementation of singleton class:

private static SingletonClass Instance = new SingletonClass(); // Note: Here the non-static constructor will take precedence over static constructor.

// Either use Static or Private constructor.

// Private - Advantage- Does not forces to make any member variable[ required to be referred] in constructor to be static

//static SingletonClass()

//{

//}

private SingletonClass()

{

}

public static SingletonClass GetInstance()

{

return Instance;

}

How does this work?

In C# when a constructor is marked as static, they are specified to execute only when an instance of the class is created or a static member is referenced. Also, they are supposed to execute only once per AppDomain. This allows us to remove our locks because the checks required have already taken care of because of the property of the static constructor.

Now imagine if you have another static variable in the singleton class that you wish to access before you want to access the variable “Instance”? So, our “Instance” object creation wouldn’t be lazy anymore. (By lazy we mean, instantiated only when referenced)

But, in most of our implementations, we can do with this kind of an static instantiation of the singleton class because generally they do not have other static objects which we would wish to refer separately J

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Tuesday, May 22, 2007

Tip/Trick: List Running ASP.NET Worker Processes and Kill/Restart them from the command-line

Problem

You want a quick way to kill a process on your system, or kill and restart an ASP.NET or IIS worker process. 

Solution

Windows has two built-in command-line utilities that you can use to help with this: Tasklist and Taskkill

Within a command-line window you can type "Tasklist" to obtain a listing of all of running Windows processes on your system:

C:\Documents and Settings\Arun>tasklist

Image Name                   PID Session Name     Session#    Mem Usage
========================= ====== ================ ======== ============
System Idle Process            0 Console                 0         16 K
System                         4 Console                 0        212 K
smss.exe                     824 Console                 0        372 K
csrss.exe                    876 Console                 0      5,116 K
winlogon.exe                 900 Console                 0      3,848 K
services.exe                 944 Console                 0      4,112 K
lsass.exe                    956 Console                 0      1,772 K
svchost.exe                 1372 Console                 0     22,240 K
svchost.exe                 1524 Console                 0      3,428 K
svchost.exe                 1572 Console                 0      4,916 K
spoolsv.exe                 1788 Console                 0      5,660 K
inetinfo.exe                 352 Console                 0      9,860 K
sqlservr.exe                 612 Console                 0      7,348 K
sqlservr.exe                 752 Console                 0     15,552 K
explorer.exe                2960 Console                 0     25,224 K
CTHELPER.EXE                3660 Console                 0      4,964 K
LVComS.exe                   872 Console                 0      3,092 K
msmsgs.exe                  3596 Console                 0      6,532 K
sqlmangr.exe                3096 Console                 0      4,264 K
OUTLOOK.EXE                 1740 Console                 0     75,992 K
iexplore.exe                 472 Console                 0     37,372 K
cmd.exe                      732 Console                 0      2,436 K
tasklist.exe                3104 Console                 0      4,156 K
wmiprvse.exe                3776 Console                 0      5,416 K

TaskKill can then be used to terminate any process instance in the above list.  Simply provide it with the PID (Process ID) value of the process instance to kill and it will terminate it:

C:\Documents and Settings\Scott>taskkill /pid 1980
SUCCESS: The process with PID 1980 has been terminated.

ASP.NET on Windows 2000 and XP runs code within the "aspnet_wp.exe" worker process (when using IIS).  On Windows 2003 it runs within the IIS6 "w3wp.exe" worker process.  Both of these processes are launched from Windows system services, which means you must provide the "/F" switch to taskkill to force-terminate them:

C:\Documents and Settings\Scott>tasklist

Image Name                   PID Session Name     Session#    Mem Usage
========================= ====== ================ ======== ============
aspnet_wp.exe               3820 Console                 0     13,512 K

C:\Documents and Settings\Scott>taskkill /pid 3820 /F
SUCCESS: The process with PID 3820 has been terminated.

As a short-cut, you can also just provide the process image name to "Taskkill" if you want to avoid having to lookup the PID value for a specific process instance.  For example, the below command will kill all ASP.NET worker processes on the system:

C:\Documents and Settings\Scott>taskkill /IM aspnet_wp.exe /F
SUCCESS: The process "aspnet_wp.exe" with PID 2152 has been terminated.

ASP.NET and IIS will automatically launch a new worker process the next time a request is received by the system.  So when you run the above command it will shutdown all active ASP.NET Worker processes.  When you then hit the site again a new one will be automaticlaly launched for it (and it will have a new PID as a result).

Note that both TaskList and TaskKill support a "/S" switch that allows you to specify a remote system to run the commands against.  If you have remote admin rights on one of your co-workers machines this can be a lot of fun.

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Custom Validatorss

 

By simply using the four ASP.NET validation Web controls (the RequiredFieldValidator, the CompareValidator, the RangeValidator, and the

RegularExpressionValidator), we are able to solve the vast majority of our form validation needs. However, there may be times when we need

 to perform more complex , more conditional validation logic.In such cases CUSTOM VALIDATOR comes into picture.

 

Building a simple CustomValidator Control

 

The below code shows a simple Web form with a text box, a checkbox and a button. if the checkbox is checked , the textbox should not be

 empty and if it is unchecked the textbox can be empty. We are providing client side validation for this .

 

 

 <script type="text/javascript">

 

//function for checking the validation

 function CheckEmpty(sender, args)

   {

    var check=document.getElementById("CheckBox1");

 

         if(check.checked==true)

          {

              if(args.Value=="")

               {

                 args.IsValid =false;

               

               }

              else

                args.IsValid = true;

          }

    } 

    </script>

</head>

 

<body> 

    <form id="form1" runat="server">     

     

           <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

           <asp:CheckBox ID="CheckBox1" runat="server" />

           

          <%--  custom validator--%>

         <asp:CustomValidator runat="server" id="custPrimeCheck"  ControlToValidate="TextBox1"   ValidateEmptyText="true" 

                                 ClientValidationFunction="CheckEmpty"  ErrorMessage="Please enter some data" />

 

        <asp:button ID="Button1" runat="server" text="Button" />

      </form>

 

</body>

</html>

 

 

 

 

The args parameter passed in the CheckEmpty() function contains two properties that are vitally important:

 

Value - indicates the value of the form field the CustomValidator control is validating.

IsValid - a Boolean property , Set IsValid to true if the Value is valid, false otherwise.

 

We can also perform server side validation using Custom validators.

 

 

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Monday, May 21, 2007

Overiding Function in JS

Hi,

 

Below is the way to implement overriding in JS. The major use of this comes while working with Master & User Controls.

 

<script type="text/javascript">

    function Base()

    {

        this.OverrideMe = function()

        {

        alert("Base::Override()");

        }

 

        this.BaseFunction = function()

        {

        alert("Base::BaseFunction()");

        }

    }

 

    function Derive()

    {

        this.OverrideMe = function()

        {

            alert("Derive::Override()");

        }

    }

 

    function CallOveride()

    {

        Derive.prototype = new Base(); // Required only when u want to call some base class fucntions as well. This must be the first statement.

        d = new Derive();

        d.OverrideMe();      

       

        d.BaseFunction();

       

        d = new Base();

        d.OverrideMe();

    }

</script>

 

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Thursday, May 17, 2007

LDAP Authentication

<!-- "LDAP://yourCompanyName.com/DC=yourCompanyName,DC=com"; -->

    <add key="LDAP_Path" value="LDAP://rspl.com/DC=rspl,DC=com" />

    <add key="Domain" value="RSPL" />

 

Public Function IsAuthenticated(ByVal domain As String, ByVal username As String, ByVal pwd As String) As Boolean

            Dim domainAndUsername As String = domain & "\" + username

            Dim entry As New DirectoryEntry(_path, domainAndUsername, pwd)

 

            Try

 

                ' Bind to the native AdsObject to force authentication.

                Dim obj As Object = entry.NativeObject

                Dim search As New DirectorySearcher(entry)

                search.Filter = "(SAMAccountName=" + username + ")"

                search.PropertiesToLoad.Add("cn")

 

                Dim result As SearchResult = search.FindOne()

                If (Nothing Is result) Then

 

                    Return False

                End If

                ' Update the new path to the user in the directory

                _path = result.Path

                _filterAttribute = CStr(result.Properties("cn")(0))

 

            Catch ex As Exception

 

                Throw New Exception("Error authenticating user. " + ex.Message)

            End Try

            Return True

End Function

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

InProc Mode issues with WebGarden & WebFarm

[http://msdn2.microsoft.com/en-us/library/ms178586.aspx]

 

If you enable Web-garden mode by setting the webGarden attribute to true in the processModel element of the application's Web.config file, do not use InProc session state mode.

If you do, data loss can occur if different requests for the same session are served by different worker processes.

 

Reason Behind:

If a user already has a Session key, but is returned to a different machine than the one on which his session was created, a new Session is created on that new machine using the session ID supplied by the  user. Of course, that new Session is empty and unexpected results may occur.

 You cannot use InProc mode in a Web garden environment because multiple instances of Aspnet_wp.exe are running on the same computer.

 

Work Around: [Mentioned in Wrox]

However if regenerateExpiredSessionId is set to True in the web.config file, a new Session ID is created and assigned to the user.

 

 

Note: [http://msdn2.microsoft.com/en-us/library/ms178586.aspx]

InProc is the only mode that supports the Session_End event. The Session_End event fires when a user's session times out or ends. You can write code in this event to clean up server resources.

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Wednesday, May 16, 2007

DecryptionKey & ValidationKey

By default, you cannot share the same Authentication Ticket cookie across multiple servers [Web farm] or multiple application on the same Web Server.

 

·         By default, the Forms authentication cookie is encrypted and signed.

·         By default, each application generates a unique decryption and validation key.

·         Therefore, by default, you can't share the same authentication cookie across applications neither in the same Web Server nor different Web Servers.

Here are the default settings for this element:

<machineKey

  decryption="Auto"

  validation="SHA1"

  decryptionKey="AutoGenerate, IsolateApps"

  validationKey="AutoGenerate, IsolateApps" />

 

 

To share the same authentication cookie across every application hosted on the same web server, do as below.

·   Remove the IsolateApps attribute, as it cause to generate a different keys for every application.

 

<machineKey

  decryption="Auto"

  validation="SHA1"

  decryptionKey="AutoGenerate"

  validationKey="AutoGenerate" />

 

 To share the same authentication cookie across separate web servers.

·    Then you need to specify the decryptionKey and validationKey manually.

 

 

<machineKey

  decryption="AES"

  validation="SHA1"

  decryptionKey="306C1FA852AB3B0115150DD8BA30821CDFD125538A0C606DACA53DBB3C3E0AD2"

  validationKey="61A8E04A146AFFAB81B6AD19654F99EA7370807F18F5002725DAB98B8EFD19C711337E269

48E26D1D174B159973EA0BE8CC9CAA6AAF513BF84E44B2247792265" />

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.