April 18, 2015

Nullable Types (C# Programming Guide)

Source- MSDN.Miscrosoft.com


Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable<bool> can be assigned the values true or false, or null. The ability to assign null to numeric and Boolean types is particularly useful when dealing with databases and other data types containing elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.
class NullableExample
{
    static void Main()
    {
        int? num = null;
        if (num.HasValue == true)
        {
            System.Console.WriteLine("num = " + num.Value);
        }
        else
        {
            System.Console.WriteLine("num = Null");
        }

        //y is set to zero
        int y = num.GetValueOrDefault();

        // num.Value throws an InvalidOperationException if num.HasValue is false
        try
        {
            y = num.Value;
        }
        catch (System.InvalidOperationException e)
        {
            System.Console.WriteLine(e.Message);
        }
    }
}

The above will display the output:
num = Null
Nullable object must have a value.

Nullable Types Overview

Nullable types have the following characteristics:
  • Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)
  • The syntax T? is shorthand for System.Nullable<T>, where T is a value type. The two forms are interchangeable.
  • Assign a value to a nullable type in the same way as for an ordinary value type, for example int? x = 10; or double? d = 4.108;
  • Use the System.Nullable.GetValueOrDefault property to return either the assigned value, or the default value for the underlying type if the value is null, for example int j = x.GetValueOrDefault();
  • Use the HasValue and Value read-only properties to test for null and retrieve the value, for example if(x.HasValue) j = x.Value;
    • The HasValue property returns true if the variable contains a value, or false if it is null.
    • The Value property returns a value if one is assigned, otherwise a System.InvalidOperationException is thrown.
    • The default value for a nullable type variable sets HasValue to false. The Value is undefined.
  • Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type, for example int? x = null; int y = x ?? -1;
  • Nested nullable types are not allowed. The following line will not compile: Nullable<Nullable<int>> n;

August 13, 2014

SEQUENCE Vs IDENTITY in SQL Server 2012

A sequence is a user-defined schema bound object that generates a sequence of numeric values according to the specification with which the sequence was created. The sequence of numeric values is generated in an ascending or descending order at a defined interval and can be configured to restart (cycle) when exhausted. Sequences, unlike identity columns, are not associated with specific tables. Applications refer to a sequence object to retrieve its next value. The relationship between sequences and tables is controlled by the application. User applications can reference a sequence object and coordinate the values across multiple rows and tables.
CREATE SEQUENCE [schema_name . ] sequence_name
    [ AS [ built_in_integer_type | user-defined_integer_type ] ]
    [ START WITH <constant> ]
    [ INCREMENT BY <constant> ]
    [ { MINVALUE [ <constant> ] } | { NO MINVALUE } ]
    [ { MAXVALUE [ <constant> ] } | { NO MAXVALUE } ]
    [ CYCLE | { NO CYCLE } ]
    [ { CACHE [ <constant> ] } | { NO CACHE } ]
    [ ; ]

1)Independent from table.
Example : 

Example : CREATE SEQUENCE [dbo].[Sequence_ID]
 AS [int]
 START WITH 1
 INCREMENT BY 1 
 MINVALUE 1
 MAXVALUE 1000
 NO CYCLE
 NO CACHE 

http://raresql.com/tag/sequence-vs-identity-in-sql-server-2012/
http://www.c-sharpcorner.com/UploadFile/ff2f08/identity-vs-sequence-object-in-sql-server/
http://msdn.microsoft.com/en-IN/library/ff878091.aspx

July 25, 2012

How To Create an ASP.NET HTTP Handler by Using Visual C# .NET

Implement the Handler

  1. Open Microsoft Visual Studio .NET. In Visual C# .NET, create a new Class Library project named MyHandler.
  2. Set a reference to the System.Web.dll assembly.
  3. Add the following directive to the class:
    using System.Web;
         
  4. Rename the class SyncHandler.cs, and then change the class definition to reflect this.
  5. Implement the IHttpHandler interface. Your class definition should appear as follows:
    public class SyncHandler : IHttpHandler
         
  6. Implement the IsReusable property and the ProcessRequest method of the IHttpHandler interface. Because this is a synchronous handler, return False for the IsReusable property so that the handler is not pooled.
    public bool IsReusable
    {
       get {return false;}
    }
    
    public void ProcessRequest(HttpContext context)
    {
       context.Response.Write("Hello from custom handler.");
    }
         
  7. Compile the project.

Deploy the Handler

  1. Create a new directory named Handler under the C:\Inetpub\Wwwroot directory.
  2. Create a subdirectory named Bin in the newly created Handler directory. The resultant path is C:\Inetpub\Wwwroot\Handler\Bin.
  3. Copy MyHandler.dll from your project's Bin\Debug directory to the C:\Inetpub\Wwwroot\Handler\Bin directory.
  4. Follow these steps to mark the new Handler directory as a Web application:
    1. Open Internet Services Manager.
    2. Right-click the Handler directory, and then click Properties.
    3. On the Directory tab, click Create.
  5. Follow these steps to create an application mapping for the handler. For this handler, create a mapping to the Aspnet_isapi.dll file for the *.sync extension. Whenever a .sync file is requested, the request is routed to ASP.NET, and ASP.NET executes the code in the handler.
    1. Right-click on the Handler Web application, and then click Properties.
    2. On the Directory tab, click Configuration.
    3. Click Add to add a new mapping.
    4. In the Executable text box, type the following path: Microsoft Windows 2000:
      C:\WINNT\Microsoft.NET\Framework\<version#>\Aspnet_isapi.dll
      Microsoft Windows XP:
      C:\WINDOWS\Microsoft.NET\Framework\<version#>\Aspnet_isapi.dll
    5. In the Extension text box, type .sync.
    6. Make sure that the Check that file exists check box is cleared, and then click OK to close the Add/Edit Application Extension Mapping dialog box.
    7. Click OK to close the Application Configuration and the Handler Properties dialog boxes.
  6. Close Internet Services Manager.

Configure the System

  1. In the C:\Inetpub\Wwwroot\Handler directory, create a new file named Web.config.
  2. Add the following code to Web.config:
    <configuration>
       <system.web>
          <httpHandlers>
             <add verb="*" path="*.sync" type="MyHandler.SyncHandler, MyHandler" />
          </httpHandlers>
       </system.web>
    </configuration>
          
    In the verb="*" attribute, we instruct the handler to process a request that uses any verb (for example, POST, HEAD, GET, and so on). If you want this handler to process only the POST request, change this to verb="POST".

    In the path="*.sync" attribute, we instruct the handler to process any incoming requests for files with the .sync extension.

    In the type="MyHandler.SyncHandler, MyHandler" attribute, we instruct the handler that processes the request to implement in the MyHandler.SyncHandler namespace, and this class resides in the MyHandler assembly.

Test the Module

To test a handler, a page does not need to exist in the file system. For example, request the Default.sync file in the Handler Web application (http://<ComputerName>/Handler/Default.sync). You should receive the following results:
Hello from custom handler.
    

How To Create an ASP.NET HTTP Module Using Visual C# .NET

An HTTP module is an assembly that is called on every request made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life cycle events throughout the request. HTTP modules therefore give you the opportunity to examine incoming requests and take action based on the request. They also give you the opportunity to examine the outbound response and modify it.
ASP.NET HTTP modules are similar to ISAPI filters in that they run for all requests. However, they are written in managed code and are fully integrated with the life cycle of an ASP.NET application.
Typical uses for HTTP modules include:
  • Security. Because you can examine incoming requests, your HTTP module can perform custom authentication or other security checks before the requested page, XML Web service, or handler is called.
  • Statistics and logging. Because HTTP modules are called on every request, you can gather request statistics and logging information in a centralized module, rather than in individual pages.
  • Custom headers or footers. Because you can modify the outbound response, you can inject content such as custom header information into every page or XML Web service response.
ASP.NET uses modules to implement various application features, including forms authentication, caching, session state, and client script services. In each case, when those services are enabled, the module is called as part of a request and performs tasks that are outside the scope of any single page request. Modules can consume application events and can raise events that can be handled in the Global.asax file. For more information about application events, see ASP.NET Application Life Cycle Overview.
NoteNote
HTTP modules differ from HTTP handlers. HTTP modules are called for all requests and responses, whereas HTTP handlers run only in response to specific requests. For more information, see Introduction to HTTP Handlers.

  Implement the Module

  1. Create a new Visual Studio .NET C# Class Library project named MyModule.
  2. Set a reference to the System.Web.dll assembly.
  3. Add the following directive to the class:

    using System.Web;     
  4. Rename the class SyncModule.cs, and then change the class definition to reflect this.
  5. Implement the IHttpModule interface. Your class definition should appear as follows:

    public class SyncModule : IHttpModule     
  6. Decide to which events you will subscribe. The following list outlines the available events from the HttpApplication object to which you can subscribe:
    • AcquireRequestState: Call this event to allow the module to acquire or create the state (for example, session) for the request.
    • AuthenticateRequest: Call this event when a security module needs to authenticate the user before it processes the request.
    • AuthorizeRequest: Call this event by a security module when the request needs to be authorized. Called after authentication.
    • BeginRequest: Call this event to notify a module that new request is beginning.
    • Disposed: Call this event to notify the module that the application is ending for some reason. Allows the module to perform internal cleanup.
    • EndRequest: Call this event to notify the module that the request is ending.
    • Error: Call this event to notify the module of an error that occurs during request processing.
    • PostRequestHandlerExecute: Call this event to notify the module that the handler has finished processing the request.
    • PreRequestHandlerExecute: Call this event to notify the module that the handler for the request is about to be called.
    • PreSendRequestContent: Call this event to notify the module that content is about to be sent to the client.
    • PreSendRequestHeaders: Call this event to notify the module that the HTTP headers are about to be sent to the client.
    • ReleaseRequestState: Call this event to allow the module to release state because the handler has finished processing the request.
    • ResolveRequestCache: Call this event after authentication. Caching modules use this event to determine if the request should be processed by its cache or if a handler should process the request.
    • UpdateRequestCache: Call this event after a response from the handler. Caching modules should update their cache with the response.
    This sample uses the BeginRequest event.
  7. Implement the Init and Dispose methods of the IHttpModule interface as follows:

    public void Init(HttpApplication app)
    {
       app.BeginRequest += new EventHandler(OnBeginRequest);
    }
    
    public void Dispose(){ }     
  8. Create a delegate for an event as follows:

    public delegate void MyEventHandler(Object s, EventArgs e);     
  9. Define a private local variable of the type MyEventHandler to hold a reference to the event:

    private MyEventHandler _eventHandler = null;     
  10. Create an event that hooks up the delegate to the method in the Global.asax file or class that inherits from the HttpApplication object:

    public event MyEventHandler MyEvent
    {
       add { _eventHandler += value; }
       remove { _eventHandler -= value; }
    }     
  11. Create the OnBeginRequest method, which hooks up to the BeginRequest event of HttpApplication:

    public void OnBeginRequest(Object s, EventArgs e)
    {
       HttpApplication app = s as HttpApplication;
       app.Context.Response.Write("Hello from OnBeginRequest in custom module.<br>");
       if(_eventHandler!=null)
          _eventHandler(this, null);
    }     
  12. Compile the project.

Deploy the Module

  1. Create a new directory under C:\Inetpub\Wwwroot named Module.
  2. Create a subdirectory named Bin in the newly created Module directory. The resultant path is C:\Inetpub\Wwwroot\Module\Bin.
  3. Copy MyModule.dll from your project's Bin\Debug directory to the C:\Inetpub\Wwwroot\Module\Bin directory.
  4. Follow these steps to mark the new Module directory as a Web application:
    1. Open Internet Services Manager.
    2. Right-click the Module directory, and then click Properties.
    3. On the Directory tab, click Create.
    4. Click OK to close the Module Properties dialog box.

Configure the System

  1. In the C:\Inetpub\Wwwroot\Module\ directory, create a new file named Web.config.
  2. Paste the following text in Web.config:

    <configuration>
       <system.web>
          <httpModules>
             <add name="MyModule" type="MyModule.SyncModule, MyModule" />
          </httpModules>
       </system.web>
    </configuration>     

Test the Module

  1. In the C:\Inetpub\Wwwroot\Module directory, create a new .aspx file named Test.aspx.
  2. Paste the following text into Test.aspx:

    <%@Page Language="C#"%>
    <% Response.Write("Hello from Test.aspx.<br>"); %>     
  3. In the C:\Inetpub\Wwwroot\Module directory, create a Global.asax file.
  4. Paste the following code into Global.asax:

    <%@ Import Namespace="MyModule" %>
    
    <script language="C#" runat=server >
    protected void MyModule_OnMyEvent(Object src, EventArgs e)
    { 
      Context.Response.Write("Hello from MyModule_OnMyEvent called in Global.asax.<br>");
    }
    </script>     
  5. Request the Test.aspx page. You should see the following lines of text:

    Hello from OnBeginRequest in custom module.
    Hello from MyModule_OnMyEvent called in Global.asax.
    Hello from Test.aspx.     

July 14, 2012

November 13, 2011

September 12, 2011

Windows XP Group Policy : Restrict the specific window application

1)Go to START -> Run
2)Type gpedit.msc and Enter
3)User Configuration ->Administrative Templates ->System
4)Right click on 'Don't run the specified Windows application ' and go to Properties
5)Select Enable radio button and click on Show button and add specified program exe file.