Labels

Sunday, May 27, 2007

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.