Monthly Archives: June 2010

Static Classes

Static classes are loaded automatically by the .NET when the program or namespace containing the class is loaded.
The main features of a static class are:
# They only contain static members.
# They cannot be instantiated.
# They are sealed.
# They cannot contain Instance Constructors

If you include instance member in static class then you will get compile time error.

static class CompanyInfo
{
public static string GetCompanyName() { return “CompanyName”; }
public static string GetCompanyAddress() { return “CompanyAddress”; }
}

Leave a comment

Filed under C#

ASP.Net Page Life Cycle

Leave a comment

Filed under .Net

ASP.NET Application Life Cycle for IIS

Application Life Cycle


Step 1:- The user sends a request to IIS. IIS first checks which ISAPI extension can serve this request. Depending on file extension the request is processed. For instance if the page is an ‘.ASPX page’ then it will be passed to ‘aspnet_isapi.dll’ for processing.

Step 2:- If this the first request to the website then a class called as ‘ApplicationManager’ creates an application domain where the website can run. As we all know application domain creates isolation between two web applications hosted on the same IIS. So in case there is issue in one app domain it does not affect the other app domain.

Step 3:- The newly created application domain creates hosting environment i.e. the ‘HttpRuntime’ object. Once the hosting environment is created necessary core ASP.NET objects like ‘HttpContext’ , ‘HttpRequest’ and ‘HttpResponse’ objects are created.

Step 4:- Once all the core ASP.NET objects are created ‘HttpApplication’ object is created to serve the request. In case you have a ‘global.asax’ file in your system then object of the ‘global.asax’ file will be created. Please note ‘global.asax’ file inherits from ‘HttpApplication’ class.
Note: The first time an ASP.NET page is attached to an application, a new instance of ‘HttpApplication’ is created. Said and done to maximize performance, ‘HttpApplication’ instances might be reused for multiple requests.

Step 5:- The ‘HttpApplication’ object is then assigned to the core ASP.NET objects to process the page.

Step 6:-Now following events are executed by HttpAlication like:
–ValidateRequest() for validating information sent by the browser to determine whether it contain malicious markup or for Cross-site scricpting attacks.
–URL mapping if it is configured in UrlMapping section in web.config.
–BeginRequest() event
–AuthenticateRequest() event
–AuthorizeRequest() event
….
….
….
–EndRequest() event

REFERENCES

http://www.codeproject.com/Articles/121096/Web-Server-and-ASP-NET-Application-Life-Cycle-in-D

http://www.codeproject.com/Articles/73728/ASP-NET-Application-and-Page-Life-Cycle

Leave a comment

Filed under .Net

ref vs out

ref
it is necessary to initialize them before passing to the function(compile time error, if not done).

 protected void Page_Load(object sender, EventArgs e)
{           
            int a = 20;
            Response.Write(a + “<BR>”);
            DoSome(ref a);      //we need to pass value with ref keyword
            Response.Write(a + “<BR>”);           
}

private void DoSome(ref int aa)
{
            aa = 30;
}

out
no assignment is required, but you must assign a value in which function this is passed.
If the other side doesn’t need any information about this object except where to store the object, you probably should just use ‘Out’.

protected void Page_Load(object sender, EventArgs e)
 {           
            int a = 20;           
            DoSome(out a);      //we need to pass value with out keyword
            Response.Write(a + “<BR>”);           
}

private void DoSome(out int aa)
{
            aa = 30;
}

2 Comments

Filed under .Net, C#

What is GAC? Where GAC located on machine?

GAC is known as Global Assembly Cache where the shared assembiles are being kept. GAC can be found on a system at \\Assembly ie. C:\Windows\Assembly.
GAC is a Folder that contains DLL that have strong name. As DLL differ by strong names+public key and since strong name can not be same hence we can put two DLL with same name into GAC. For example SameNameApp.dll and SameNameApp.dll can co-exist in GAC if the first one have version 1.0.0.0 and the second have 1.1.0.0.

DLL =Assembly_name + Version + Culture_Info + public_key

Leave a comment

Filed under .Net

Exception Handling in WCF

**********************************

Server Side Exception Handling

**********************************

Exception Handling in WCF

We basically handle two types of exception in WCF service and covert them to the FaultExcetion<SomeErrorDto> to make client familiar with the exceptions. Let me explain the complete scenario with a sample application XYZ:

Catch (XYZException ex)

{

       //Convert Application specific (XYZException) exceptions to FaultException<XYZErrorDto>.

       throw ExceptionHelper.HandleXYZToFaultException(ex);

}

Catch(Exception ex)

{

      //Convert Generic Exception to FaultException<XYZErrorDto>.

       throw ExceptionHelper.HandleGenericToFaultException(ex);

}

 

Our XYZException Class

public class XYZException : System.Exception

{

    private int _errorCode;

     public int ErrorCode

    {

        get { return _errorCode; }

        set { _errorCode = value; }

    }

 

    public XYZException(string message, Exception ex)  : base(message, ex)

    {

    }

    public XYZException(string message, int code, Exception ex)  : base(message, ex)

    {

        _errorCode = code;

    }  

}

Our ExceptionHelper class:

using System;

using System.Data.SqlClient;

using System.ServiceModel;

 

public class ExceptionHelper

{

    //Used in the BL(Business Logic) layer

    public static XYZException HandleGenericToXYZException(Exception genExcep)

    {

        //Logging the Generic Execption here before converting it to Application specific

       // (XYZException) exception.

        if ((genExcep != null))

        {

            return new XYZException(genExcep . Message, genExcep);

        }

        else

        {

            return null;

        }

    }

   

    //Convert Application specific Exception to FaultException<XYZErrorDto>

    public static FaultException<XYZErrorDTO> HandleXYZToFaultException(XYZException xyzExcep)

    {

        return HandleGenericToFaultException(xyzExcep);

    } 

    //Used in WCF service.

    public static FaultException<XYZErrorDTO> HandleGenericToFaultException(Exception genExcep)

    {

        XYZErrorDTO objXYZErrDTO = new XYZErrorDTO();

        if ((genExcep != null))

        {

            objXYZErrDTO = new XYZErrorDTO(genExcep.Message);

        }

        else

        {

            objXYZErrDTO = new XYZErrorDTO(“An unexpected error has occurred in the system”);

        } 

        //Logging the Generic Execption here before converting it to FaultException.

        return new FaultException<XYZErrorDTO>(objXYZErrDTO);

    }

}

*********************

UI Exception Handling

**********************

Now it is clear the UI will only receive Exceptions of type FaultException only from server, moreover we need to handle the Generic exception raised at the UI also. So if the UI code logic involve server resource usage the we have to catch both the exceptions else there will be only catching of general exception as shown below:

 Try

{

     //Logic involve usage of server resources 

}

Catch (FaultException ex)

{

      UIExceptionHelper.HandleFaultException(ex);        

}

Catch (Exception ex)

{

      UIExceptionHelper.HandleGenericException(ex);    

}

Our UIExceptionHelper class:

using System.ServiceModel;

using System.Diagnostics.EventLog;

 public class UIExceptionHelper

{

     public static void HandleFaultException(FaultException<XYZErrorDTO> faultExcep)

    {

        try

        {

            //Logging FaultException before displaying on Screen.          

            LogManager.LogError(faultExcep, errorCode, ConfigurationManager.AppSettings(“LogCategory”));

            WebMsgBox.Show(Decl.WEB_MSG, faultExcep.Detail.Message);

        }

        catch (Exception ex)

        {

        }

    }

     public static void HandleGenericException(Exception excep)

    {

        try

        {

            //Logging the Generic message before redirecting to custom error page.

            string strMsg = excep.Message.Replace(Constants.vbCrLf, ” “);

            string strTrace = excep.StackTrace.Replace(Constants.vbCrLf, ” “);

            LogManager.LogError(excep, errorCode, ConfigurationManager.AppSettings(“LogCategory”));

            //Redirecting to Custom Error Page for Generic Exceptions.

            Response.Redirect(Decl.ERROR_PAGE + “?Error=” + strMsg + “&Trace=” + strTrace);

        }

        catch (Exception ex)

        {

        }

    }

}

Refrences

http://msdn.microsoft.com/en-US/library/seyhszts(v=VS.80).aspx

http://dhananjaykumar.net/2010/05/23/fault-contract-in-wcf-with-learning-video/

Leave a comment

Filed under C#, WCF

Asynchronous Programming

Asynchronous Programming

When you create delegate, the compiler generates three methods Invoke, BeginInvoke, EndInvoke. Invoke is used to execute delegate synchronously, and rest two methods allow you to have asynchronous programming.

BeginInvoke takes the same parameters as delegate itself, plus another two parameters- an AsyncCallback which is called after the BeginInvoke execution, and an object parameter which is made available through the AsyncState property of the IAsyncResult parameter which is passed to the AsyncCallback.

The call to BeginInvoke returns an IAsyncResult which can be used to call EndInvoke, and you don’t have to pass a callback delegate to be executed if you don’t want to – just pass null as the last but one parameter to BeginInvoke.

private delegate int DoubleMeDelegate(int x);

protected void Page_Load(object sender, EventArgs e)

{

   for (int i = 1; i < 5; i++)

  {

     DoubleMeDelegate d = new DoubleMeDelegate(DoubleMe);

     d.BeginInvoke(i, new System.AsyncCallback(InvokeMessage), d);

   }

Thread.Sleep(1900);

}

private void InvokeMessage(IAsyncResult ar)

{

   DoubleMeDelegate dEnd = (DoubleMeDelegate)ar.AsyncState;

   int result = dEnd.EndInvoke(ar);

   Response.Write(result + “<br/>”);

}

private int DoubleMe(int single)

{

   Thread.Sleep(100);

   return (2 * single);

}

Leave a comment

Filed under C#

ThreadPool

ThreadPool

ThreadPool basically maintain “pool” of threads which are waiting for work items. As thread creation is not a cheap process. By default, the thread pool has 25 threads per processor.

We can Queue up method to the ThreadPool using it’s QueueUserWorkItem method. It takes two parameters – a WaitCallback delegate to the method you want to call and the optional object to pass as parameter to the callback method.

     protected void Page_Load(object sender, EventArgs e)  

        {  

            WaitCallback callBack;   

            callBack = new WaitCallback(DoubleMe);  

            ThreadPool.QueueUserWorkItem(callBack, 1);  

            ThreadPool.QueueUserWorkItem(callBack, 2);  

            ThreadPool.QueueUserWorkItem(callBack, 3);  

        }   

        public void DoubleMe(int i)  

        {   

            // Simulation of processing time   

            Thread.Sleep(1000);  

            String result = (2*i).ToString();

            Response.Write(result + “<BR>”);  

        } 

Leave a comment

Filed under C#

State Management

VIEW STATE

  • The ViewState property provides a dictionary object for retaining values between multiple requests for the same page only.
  • ViewState is lost if the user visits a different Web page, so it is useful only for temporarily storing values. They are saved in hidden fields.
  • The viewstate for all of the controls on the page will be stored in a single hidden control called __VIEWSTATE.

<input type=”hidden” name=”__VIEWSTATE” id=”__VIEWSTATE” value=”/wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHn/rt75XF/pMGnqjqHlH66cdw==” />

We can encrypt viewstate to make it more difficult for attackers. To configure view state encryption:

At Application Level:

<Configuration>

<system.web>

<pages viewStateEncryptionMode=”Always”/>

</system.web>

</configuration>

At Page level:

<%@ Page AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” ViewStateEncryptionMode=”Always”%>

View State is enabled by default, but we can disable it by setting the EnableViewState property for each web control to false.

Data Types You Can Store in View State

Strings

Integers

Boolean values

Array objects

ArrayList objects

Hash tables

Custom ViewState

ArrayList PageArrayList;

//Get value from ViewState

if (ViewState[“PageArrayList”] != null)

{

PageArrayList = (ArrayList)ViewState[“arrayListInViewState”];

}

//To saves into ViewState

ViewState.Add(“arrayListInViewState”, PageArrayList);

QUERYSTRING

A query string is information sent to the server appended to the end of a page URL.

Benefits: –

• No server resources are required. The query string containing in the HTTP requests for a specific URL.

• All browsers support query strings.

Limitations: –

• Query string data is directly visible to user thus leading to security problems.

• Most browsers and client devices impose a 255-character limit on URL length.

If you have more than one query string then using “&” sign.

eg:

http://www.gurunguns.com/login.aspx?type=testing&uid=qstring

We can use the above queryString in C# as:

string loginType = Request.QueryString[“type”]

string userid = Request.QueryString[“uid”]

To access QueryString using javascript:

http://triaslama.wordpress.com/2008/04/12/retrieving-query-string-values-in-aspnet-and-javascript/

COOKIES

PERSISTENT COOKIE NON-PERSISTENT COOKIE
1. Persistent cookies are stored in text file at the client side. Non-Persistent cookies are stored in the RAM at client.
2. They are permanent cookies. They are destroyed when the browser is closed.
3. Session Id is not stored in them. Session Id is stored in non-persistent cookies.

Leave a comment

Filed under .Net

Http Modules

Http Module

An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules let you examine incoming and outgoing requests and take action based on the request.

eg: BeginRequest, AuthenticationRequest event, EndRequest event etc. You may intercept , participate and modify each request.

Uses for HTTP modules include

1) Security   Because you can examine incoming requests, an HTTP module can perform custom authentication or other security checks before the requested page, XML Web service, or handler is called.

2) Statistics and logging   Because HTTP modules are called on every request, you can gather request statistics and log information in a centralized module, instead of in individual pages.

3) Custom headers or footers   Because you can modify the outgoing response, you can insert content such as custom header information into every page or XML Web service response.

 An HTTP module is supposed to implement the following methods of the IHttpModule interface:

Method Name Description
Init This method allows an HTTP module to register its event handlers to the events in the HttpApplication object.
Dispose This method gives HTTP module an opportunity to perform any clean up before the object gets garbage collected

 An HTTP module can register for the following events exposed by the System.Web.HttpApplication object.

  • Event Name
Description
AuthenticateRequest This event is raised when ASP.NET runtime is ready to authenticate the identity of the user.
AuthorizeRequest This event is raised when ASP.NET runtime is ready to authorize the user for the resources user is trying to access.
BeginRequest This event is raised when ASP.NET runtime receives a new HTTP request.
EndRequest This event is raised just before sending the response content to the client.
Global.asax Events
Application_OnStart This event is raised when the very first request arrives to the Web application.
Application_OnEnd This event is raised just before the application is going to terminate.
Session_OnStart This event is raised for the very first request of the user’s session.
Session_OnEnd This event is raised when the session is abandoned or expired.

 Registering HTTP Modules in Configuration Files

To add an HTTP module:

 <httpModules>

            <add  name=”modulename” type=”classname, assemblyname” />

<httpModules>

Eg:

<httpModules>

 <add name=”OutputCahe”  type=”System.Web.Caching.OutputCacheModule”/>

 <add  name=”Session”  type=”System.Web.SessionState.SessionStateModule”/>

</httpModules>

 To remove an HTTP module

 <httpModules>

            <remove  name=”modulename” />

<httpModules>

 Implementing an HTTP Module for Providing Security Services

HTTP module that provides security services for our Web application. Our HTTP module will basically provide a custom authentication service. It will receive authentication credentials in HTTP request and will determine whether those credentials are valid.

 using System;

using System.Web;

using System.Security.Principal; 

namespace SecurityModules

{

 /// <summary>

 /// Summary description for Class1.

 /// </summary> 

 public class CustomAuthenticationModule : IHttpModule

 {

  public CustomAuthenticationModule()

  {

  }

  public void Init(HttpApplication r_objApplication)

  {

   // Register our event handler with Application object.

   r_objApplication.AuthenticateRequest +=

               new EventHandler(this.AuthenticateRequest) ;

  }

   public void Dispose()

  {

   // Left blank because we dont have to do anything.

  }

   private void AuthenticateRequest(object r_objSender,

                                   EventArgs r_objEventArgs)

  {

   // Authenticate user credentials, and find out user roles.

   1. HttpApplication objApp = (HttpApplication) r_objSender ;

   2. HttpContext objContext = (HttpContext) objApp.Context ;

   3. if ( (objApp.Request[“userid”] == null) ||

   4.                     (objApp.Request[“password”] == null) )

   5. {

   6.  objContext.Response.Write(“<H1>Credentials not provided</H1>”) ;

   7.  objContext.Response.End() ;

   8. }

    9. string userid = “” ;

   10. userid = objApp.Request[“userid”].ToString() ;

   11. string password = “” ;

   12. password = objApp.Request[“password”].ToString() ;                                   

   13. string[] strRoles ;

   14. strRoles = AuthenticateAndGetRoles(userid, password) ;

   15. if ((strRoles == null) || (strRoles.GetLength(0) == 0))

   16. {

   17. objContext.Response.Write(“<H1>We are sorry but we could not

       find this user id and password in our database</H1>”) ;

   18. objApp.CompleteRequest() ;

   19. }

    20. GenericIdentity objIdentity = new GenericIdentity(userid,

                                             “CustomAuthentication”) ;

   21. objContext.User = new GenericPrincipal(objIdentity, strRoles) ;

  }

   private string[] AuthenticateAndGetRoles(string r_strUserID,

                                                 string r_strPassword)

  {

   string[] strRoles = null ;

   if ((r_strUserID.Equals(“Steve”)) &&

                                  (r_strPassword.Equals(“15seconds”)))

   {

    strRoles = new String[1] ;

    strRoles[0] = “Administrator” ;

   }

   else if ((r_strUserID.Equals(“Mansoor”)) &&

                                        (r_strPassword.Equals(“mas”)))

   {

     strRoles = new string[1] ;

     strRoles[0] = “User” ;                                             

    }

    return strRoles ;

   }

  }

}

 We start with the Init function. This function plugs in our handler for the AuthenticateRequest event into the Application object’s event handlers list. This will cause the Application object to call this method whenever the AuthenticationRequest event is raised.

 Once our HTTP module is initialized, its AuthenticateRequest method will be called for authenticating client requests. AuthenticateRequest method is the heart of the security/authentication mechanism. In that function:

 Line 1 and Line 2 extract the HttpApplication and HttpContext objects. Line 3 through Line 7 checks whether any of the userid or password is not provided to us. If this is the case, error is displayed and the request processing is terminated.

 Line 9 through Line 12 extract the user id and password from the HttpRequest object.

 Line 14 calls a helper function, named AuthenticateAndGetRoles. This function basically performs the authentication and determines the user role. This has been hard-coded and only two users are allowed, but we can generalize this method and add code for interacting with some user database to retrieve user roles.

 Line 16 through Line 19 checks whether the user has any role assigned to it. If this is not the case that means the credentials passed to us could not be verified; therefore, these credentials are not valid. So, an error message is sent to the client and the request is completed.

 Line 20 and Line 21 are very important because these lines actually inform the ASP.NET HTTP runtime about the identity of the logged-in user. Once these lines are successfully executed, our aspx pages will be able to access this information by using the User object.

 Now we have to perform some changes in our web.config file. First of all, since we are using our own custom authentication, we don’t need any other authentication mechanism.

 <authentication mode=”None”/>

 Similarly, don’t allow anonymous users to our Web site. Add the following to web.config file:

 <authorization>

  <deny users=”?”/>

</authorization> 

Users should at least have anonymous access to the file that they will use for providing credentials. Use the following configuration setting in the web.config file for specifying index.aspx as the only anonymously accessible file:

 <location path=”index.aspx”>

 <system.web>

  <authorization>

   <allow users=”*”/>

  </authorization>

 </system.web>

</location> 

Reference:

http://www.15seconds.com/issue/020417.htm

Leave a comment

Filed under .Net

Logging with HttpModule

In order to build an Http module we only need to implement 
the IHttpModule interface. The following is a simple 
LoggingHttpModule which log details when a web request start 
and when web request end: 
using System;
using System.Web;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging; 
namespace HttpModules
{
  public class LoggingHttpModule : IHttpModule
  {
    #region Members 
    private LogWriter _writer; 
    #endregion 
    #region IHttpModule Members 
    public void Dispose()
    {
      if (_writer != null)
      {
        _writer.Dispose();
      }
    } 
    public void Init(HttpApplication context)
    {
      CreateLogWriter();
      context.BeginRequest += new EventHandler(context_BeginRequest);
      context.EndRequest += new EventHandler(context_EndRequest);
    } 
    private void CreateLogWriter()
    {
      ConfigureEnterpriseLibraryContainer();
      _writer = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
    } 
    private void ConfigureEnterpriseLibraryContainer()
    {
      var builder = new ConfigurationSourceBuilder(); 
      builder.ConfigureInstrumentation().EnableLogging();
      builder.ConfigureLogging().WithOptions
             .LogToCategoryNamed("General")
               .WithOptions
               .SetAsDefaultCategory()
               .SendTo
               .FlatFile("Log File")
               .FormatWith(new FormatterBuilder()
               .TextFormatterNamed("Textformatter"))
                   .ToFile("file.log"); 
      var configSource = new DictionaryConfigurationSource();
      builder.UpdateConfigurationWithReplace(configSource);
      EnterpriseLibraryContainer.Current =
        EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
    } 
    void context_BeginRequest(object sender, EventArgs e)
    {
      _writer.Write(new LogEntry
      {
        Message = "BeginRequest"
      });
    } 
    void context_EndRequest(object sender, EventArgs e)
    {
      _writer.Write(new LogEntry
      {
        Message = "EndRequest"
      });
    } 
    #endregion
  }
}

 

In order to use the module all we need to do is to add a reference
to the class library that holds the LoggingHttpModule. Then we need
to register the module in the web.config file in the httpModules 
element like:

<httpModules>
    <add name="LoggingHttpModlue" type="HttpModules.LoggingHttpModule, HttpModules"/>
</httpModules> 

That is it. Now the module will be executed whenever a request
start or end.

Leave a comment

Filed under .Net

Cookieless Session

SessionId is stored at client side in cookies. Therefore we won’t be able to retrieve session’s data in the case when cookies are not enable.
ASP.NET support cookieless execution of the application when the client doens’t have cookies support. The Session id is embedded to the request url.

To set Cookieless session in an ASP.NET application set following value in web.config file
<sessionstate cookieless=”true” />

When you have cookieless session then the url may look like this
http://www.gurunguns.com/Posts/(_entv9gVODTzHuenph6KAlK07..)/test.aspx

Leave a comment

Filed under .Net

Nth Highest salary & Nth Lowest salary of employee

There are two approaches for the same, I will show the example with N=2
1 using CTE

Highest
With cteH
{
   Select Emp_Name, Emp_Salary, Row_Number() over (Order By Emp_Salary Desc) as Rn
   From Emp
}

Select Emp_Name, Emp_Salary
From cteH
Where Rn=2

Lowest
With cteL
{
   Select Emp_Name, Emp_Salary, Row_Number() over (Order By Emp_Salary Asec) as Rn
   From Emp
}
Select Emp_Name, Emp_Salary
From cteL
Where Rn=2

2 using Distinct

Highest
Select e1.Emp_Name, e1.Emp_Salary
From Emp e1
Where 2=(Select Count(DISTINCT(e2.Emp_Salary)) From Emp e2
  Where e2.Emp_Salary>=e1.Emp_Salary)

Lowest
Select e1.Emp_Name, e1.Emp_Salary
From Emp e1
Where 2=(Select Count(DISTINCT(e2.Emp_Salary)) From Emp e2
  Where e2.Emp_Salary<=e1.Emp_Salary)

Leave a comment

Filed under SQL

How SSL Works

How SSL Works

Secure Sockets Layer (SSL) is the public -key encryption approach. SSL is an Internet security protocol used by Internet browsers and Web servers to transmit sensitive information.

SSL doesn’t authenticate a user.

Look for the “s” after “http” in the address whenever you are about to enter sensitive information & a small padlock in the status bar at the bottom of the browser window. 

How SSL handshake works:

Like XYZ Inc., intends to secure their customer transactions

Step 1: Client makes a connection to xyz.com on an SSL port, typically 443. This connection is denoted with https instead of http.

Step 2: xyz.com sends back its public key to the client. Once client receives it, his/her browser decides if it is alright to proceed on the basis of below points:

  • the certificate comes from a trusted party (like VeriSign);
  • the certificate is currently valid; and
  • the certificate has a relationship with the site from which it’s coming.

Step 3: If the client decides to trust the certificate, then the client will be sent to xyz.com his/her public key.

Step 4: xyz.com will next create a unique hash and encrypt it using both the customer’s public key and xyz.com’s private key, and send this back to the client.

Step 5: Customer’s browser will decrypt the hash. This process shows that the xyz.com sent the hash and only the customer is able to read it.

Step 6: Customer and website can now securely exchange information.

Certificates and Public Key Infrastructure
During the handshake, the service also sends its SSL certificate to the client. The certificate contains information, such as its expiration date, issuing authority, and the site’s Uniform Resource Identifier (URI). The client compares the URI to the URI it had originally contacted to ensure a match, and also checks the date and issuing authority.

Every certificate has two keys, a private key and a public key, and the two are known as an exchange key pair. In brief, the private key is known only to the owner of the certificate while the public key is readable from the certificate. Either key can be used to encrypt or decrypt a digest, hash, or other key, but only as contrary operations. For example, if the client encrypts with the public key, only the site can decrypt the message using the private key. Similarly, if the site encrypts with the private key, the client can decrypt with the public key. This provides assurance to the client that the messages are being exchanged only with the possessor of the private key because only messages encrypted with the private key can be decrypted with the public key. The site is assured that it is exchanging messages with a client that has encrypted using the public key. This exchange is secure only for an initial handshake, however, which is why much more is done to create the actual symmetric key. Nevertheless, all communications depend on the service having a valid SSL certificate.
(Refer to here)

1 Comment

Filed under .Net

Nullable Type

Nullable types are instances of the System.Nullable struct.

Variables are of two types.

Value type eg. int, char, date. A data type is a value type if it holds the data within its own memory allocation.
Reference type eg. string, object. A reference type contains a pointer to another memory location that holds the data.
 For more details on Value types and Reference type of variable, please read http://msdn.microsoft.com/en-us/library/t63sy5hs(VS.80).aspx

Reference types variable can be assigned null but value types of variables like integer can’t because they can’t contain reference, even the reference of nothing.

int i = 0;
The above statement shall throw error because we are trying to store null in the integer variable.

To avoid this we can use nullable modifier like this.

int? ii = null;
In the above code, ii is the nullable type of variable that can store either null or any integer type of variable. When a variable is declared as nullable, its extends two properties called HasValue and Value. Both property are public and read-only.

Leave a comment

Filed under C#

New vs Override

New vs Override 

Override

  • Override method actually override the virtual method.
  • When a method of a base class is overridden in a derived class (subclass), the version defined in the derived class is used.
  • This indicates for the compiler to use the last defined implementation of a method i.e. override the last implented method.
  • if you want to prevent anymore overridden from inherited class then use sealed keyword along with override.

New

  • It actually hides the base class method.
  • The new modifier instructs the compiler to use your implementation instead of the base class implementation. Any code that is not referencing your class but the base class will use the base class implementation.
  • new keyword doesn’t allow the method to be more overridden.

Example:

class BaseClass
{
public virtual void WhichClass()
{
System.Console.WriteLine(“BASE CLASS”);
}
}

class NewClass : BaseClass
{
public new void WhichClass()
{
//base.WhichClass();
System.Console.WriteLine(“NEW CLASS”);
}
}

class OverrideClass : BaseClass
{
public override void WhichClass()
{
//base.WhichClass();
System.Console.WriteLine(“OVERRIDE CLASS”);
}
}
class Program
{
static void Main(string[] args)
{
BaseClass bObj = new BaseClass();
bObj.WhichClass();
System.Console.WriteLine(“———-“);

NewClass nObj = new NewClass();
nObj.WhichClass();
System.Console.WriteLine(“———-“);

BaseClass bnObj = new NewClass();
bnObj.WhichClass();
System.Console.WriteLine(“———-“);

OverrideClass oObj = new OverrideClass();
oObj.WhichClass();
System.Console.WriteLine(“———-“);

BaseClass boObj = new OverrideClass();
boObj.WhichClass();
System.Console.WriteLine(“———-“);

Console.ReadLine();
}
}

1 Comment

Filed under .Net, C#

Static ClientID ASP.Net 4.0

Static ClientID
When writing JavaScript code to get any control in a page, We don’t know the control client

ID. Now in ASP.Net 4.0 you can make the client id of the control fixed

By making your control implement the following interface:

INamingContainer “ and set the ClientIDMode property to Static.

For example, here is the codebehind for a simple web user control (ASCX) with a label in it.

public partial class WebUserControl1 : System.Web.UI.UserControl, INamingContainer
{
   protected void Page_Load(object sender, EventArgs e)
   {
     this.ClientIDMode = ClientIDMode.Static;
   }
}
That’s all you need to do, and the control gets rendered to the page with an ID of Label1.

Leave a comment

Filed under .Net

C# 4.0 new features

In every new release of C# there is a major new feature like in C# 2.0 (Generics), C# 3.0 (Linq), and here C# 4.0 (dynamic programming support) 

1. Named and optional parameters: Now declare optional parameters simply by providing a default value for it. And call params by name: like so,      

        // Definition of the method

        public void Method(int x, int y = 1, int z = 2)

        {        } 

        // Using the optional params

        Method(1);          // same as Method(1, 1, 2);

        Method(1, 2);       // same as Method(1, 2, 2);

        Method(1, 2, 3);   

       // Named params called, note arbitrary order and missing y

        Method(z: 1, x: 2);

 2. dynamic object:

A new type has been introduced called dynamic. The idea is that you can call any operation on the dynamic type you want, the compiler won’t check it at compile-time, but figure it out at runtime. A dynamic object is assumed to support any operation at compile-time; only at runtime will you get an error. The result of any dynamic operation is of type dynamic.

        // Instantiation
        dynamic d = 7; // implicit conversion
        dynamic d = GetStudentData(); //GetStudentData() returns object of type Student class
        // Operations on dynamic       

        d.f = d.P;           // getting and settings types fields and properties
        d[“one”] = d[“two”]; // getting and setting thorugh indexers
        int i = d + 3;       // calling operators

 
// in the previous examples if f,p are not properties on the Student class and also there is no indxer it will be   compiled successfully ,it will be detected at runtime.

Leave a comment

Filed under C#

C# 3.0 new features

1. Implicitly typed local variables and arrays:  A new keyword is introduced called var. This allows you to declare a variable and let the compiler figure out the type  

ex:

        // Declare a variable of type int

            var i = 5;

            // Declare an int array

            var a = new[] { 1, 10, 100, 1000 };

            // Usage:

            for (var i = 0; i < 5; i++) { }

            foreach (var item in MyList) { }

            using (var file = new StreamReader(“Filename.txt”)) { } 

2. Auto-implement properties: Use this when no additional logic is required in the property accessors. 

ex:

        // Previously we had to do this,

        private string _name;

        public string Name

        {

            get { return _name; }

            set { _name = value; }

        }

        // Now we can shorthand it, there’s no need to declare the _name variable

        public string Name { get; set; } // The compiler creates a private anonymous backing field

Behind the scene, compiler automatically creates private, anonymous fields that can be accessed from the above auto-implemented properties.

 3. Object and collection initializers: Set properties inline during object creation.    

 ex:

    public class A {

    public string Name { get; set; }

    public string Address { get; set; }

}

// Previously we would have to do,

A a = new A();

a.Name = “…”;

a.Address = “…”;

// Now we can do this,

A a = new A { Name = “…”, Address = “…” };

// Similarly, we can initialize collections,

List<int> MyList = new List<int> { 0, 1, 2, 3, 4 };

 4. Extension methods: Now you can add methods to existing types without creating a new derived type, recompiling or modifying the original type’s code. This is incredibly useful in writing cleaner code,

ex:

public static void ExportToExcel(this DataSet ds)
{
    //do something…
}

Extension methods are declared by specifying the “this” keyword as the modifier in the first parameter. The ExportToExcel method is declared as an extension method for the DataSet class.
Extension methods are invoked as soon the namespace of the containing static class is included.
In the below code snippet, the extension method is declared inside
namespace Orcas.Samples
{
   public static class Extensions
   {
       public static void ExportToExcel(this DataSet ds)
      {
             //do something…
      }
   }
}

Above method is invoked in the client program as,
using Orcas.Samples;
DataSet ds = new DataSet();
ds.ExportToExcel()
;

5. Anonymous types: If you need a small class with read only properties, you can now use a simple syntax,     

ex:

// a is an anonymous type, the compiler creates the class with

// private string fields _name and _address

// and public string properties Name and Address,

var a = new { Name = “Dev”, Address = “Delhi” };

// a.Name and a.Address are read-only,

string s = a.Name;

 6. Query keywords (LINQ): We are now able to use TSQL like syntax inside C# to query data sources (could be objects, collections, XML, or SQL databases). Introduces a host of new keywords like from, where, select, group, orderby, join, etc.      

ex:

// The data source,

     int[] numbers = { 0, 1, 2, 3, 4, };

     // Create the query,

     var lessthan3 =

         from num in numbers

         where num < 3

         select num;

     // Output: 0 1 2

     foreach (var m in lessthan3) {

         Console.Write(m.ToString() + ” “);

     }

7. Partial method definitions: A partical class (introduced in C# 2.0) can now have partial methods. This simply means the method signature is in one partial class and the implementation in another. There are some constraints, like the method is implicitly private (and therefore cannot be virtual) and must return void.      

 ex:

public partial class A

{

    // Method definition

    partial void Method();

}

public partial class A

{

    // Method implementation

    partial void Method() { /* Do Work */ }

} 

Leave a comment

Filed under C#

Explanation of WCF web.config

Explanation of WCF web.config class 

<configuration xmlns=”http://schemas.microsoft.com/.NetConfiguration/v2.0″&gt;

  <system.serviceModel>

    <services>

      <service behaviorConfiguration=”returnFaults”>

        <endpoint contract=”IMyService” binding=”wsHttpBinding”/>

      </service>

    </services>

    <behaviors>

      <serviceBehaviors>

        <behavior >

          <serviceDebug includeExceptionDetailInFaults=”true” />

<serviceMetadata httpGetEnabled=”true” />

        </behavior>

      </serviceBehaviors>

    </behaviors>

  </system.serviceModel>

  <system.web>

    <compilation debug=”true”/>

  </system.web>

</configuration> 

Within the <system.serviceModel> we will host Serivces tag, which will has all services we will have in our project or what we want to expose. 

Within   <Services> we will host service by service

Each service tag has a name attribute “the name of the service class” and “behaviorConfiguration” that specify name of behaviour tag within serviceBehaviors tag

Each service has endpoint (“ABC”) tag with three attributes

Address(“Where”): will be “” empty if the service on the localhost.

Binding(“How”): binding=”wsHttpBinding” we will use http or https for transportation and communication

Contract(What”):the Name of the interface

Within <ServiceBehaviours> there are behaviour tag

<serviceDebug includeExceptionDetailInFaults=”true />

Each behaviour has name attribute so service can find it as mentioned before

serviceDebug includeExceptionDetailInFaults=”true” specify that occurrence of exceptions include details of the exception in the message. 

<serviceMetadata httpGetEnabled=”true” />

To enable service client to get metadata of the service project assembly to view and call service contained types

Refrences

http://blog.flair-systems.com/search/label/WCF

Leave a comment

Filed under WCF

Returning Data

Returning Data from Strored Procedure
There are three common ways to return data from stored procedures: returning result sets (SELECT statements), using output variables and using the RETURN statement.

Result Sets
Like the procedure to return a list of all the people with a given last name

Create Procedure dbo.GetPeopleByLastName(@LastName varcgar(200))
As
Select FirstName, LastName
From Person
Where
LastName=@LastName

Using OUTPUT variables
To return a single value (or a couple of values) you can use output variables.

Create Procedure dbo.GetCountByLastName(@LastName varchar(200), @LNameCount int OUTPUT)
As
Select @LNameCount=  Count(*)
From Person
Where
LastName=@LastName
And how to execute it :
DECLARE @TheCount INT

EXEC dbo.GetCountByLastName 
    @LastName = ‘Alexander’,
    @LastNameCount = @TheCount OUTPUT

Using Return

It only returns a single numeric value. This is most commonly used to return a status result or error code from a procedure.

Create Procedure TestReturn(@IntValue int)
As
RETURN @IntValue
Go

Note that executing a RETURN statement causes a stored procedure to stop executing and return control back to the calling program. This is often used to test for error conditions and stop processing if one is found.

Leave a comment

Filed under SQL

SSRS – Reporting Services Database

Some report developers don’t realize that there are two databases that you can use to lookup or analyze reporting services information. It’s often useful to write your own reports, based on information stored in these databases.

The first database is ReportServer, which is used by the Report Services to store all the information about reports that have been uploaded to the report manager. Information such as the report catalog, settings, and security are all stored within the ReportServer database.  The database ReportServerTempDB stores temporary information such as report snapshots, user sessions, and report execution information.

I have three examples of useful reports created from the ReportServer database. The first report is what I call the Report Index. It provides a list of all the items in the reporting services catalog, with links to render each report in the catalog, as shown in Figure 35. This can prove to be useful as it allows your report users to run just one report and get a list of all reports, without having to navigate through the report manager.

Figure : The Report Index report

I provide an example Report Index.rdl report as part of the code download with this article. You’ll have to point the report to your ReportServer database.

The second report, Report Usage, is basically a metrics-type report, providing details of reports that are being executed and how many times per month. The ReportServer database contains a table called ExecutionLog that, by default, stores every report execution for 60 days. You can update the setting ExecutionLogDaysKept in table ConfigurationInfo to allow for more than 60 days of execution tracking. Again, you can obtain the Report Usage.rdl file from the download file, and an example of the report is shown in Figure .

Figure : The Report Usage report

The third report, Report Users, is similar to the Report Usage report. Report Users report is basically a metrics-type report, providing details of which users are executing the reports.  Again, you can obtain the Report Users.rdl file from the download file, and an example of the report is shown in Figure.

You will need to point all the report mentioned in this section to your ReportServer database.

Leave a comment

Filed under SSRS

Playing with REST !

REST Services

àREST stands for Representational State Transfer, means that each unique URL is a representation of some object.

-to get the contents of that object use an HTTP GET,

-to delete you then might use a POST, PUT, or DELETE to modify the object.

àUnlike SOAP, REST is not a standard; it is just an architectural style.

àREST uses HTTP for all four CRUD (Create/Read/Update/Delete) operations.

àMuch like Web Services, a REST service is:

* Platform-independent (you don’t care if the server is Unix, the client is a Mac, or anything else),

* Language-independent (C# can talk to Java, etc.)

eg:

-The famous Twitter API is all REST.

Yahoo! offer most of their services using REST including Search API, Maps, Photos.

Flickr,

-Amazon.com offer several REST services, e.g., for their S3 storage solution

Atom is a RESTful alternative to RSS.

Like the following URL sends a REST request to Yahoo!’s web-search service:

http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=rest.

Click it, and observe the XML results, ready to be used directly.

This REST request includes two parameters:

appid“, used by Yahoo! to specify your application, and

query“, which is the actual search query.

REST vs SOAP

Yahoo’s web services are using REST and google using SOAP for their web services.

REST is Lightweight than SOAP because it does not requires lot of xml markup.

WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding.

The below code shows how to expose a RESTful service

[ServiceContract]

interface IStock

{

[OperationContract]

[WebGet(UriTemplate:=”/Stock/{StockId}”)]

int GetStock(string StockId);

}

By adding the WebGetAttribute, we can define a service as REST based service that can be accessible using HTTP GET operation, like GetStock from Stock.

We can use REST style to get order as shown in the below URL with Stock

http://localhost/stock.svc/Stock/100234

How to consume REST services

There are different ways to consume the REST services as per requirements, below I am mentioning some:

1) Here I am actually reading the Xml from REST service and writing to the file.  WebClient() is defined in System.Net
WebClient() objWebClient = new WebCleint();
objWebClient.Credentials = new NetworkCredential(uid, pwd, domain);
XmlTextReader objXmlTextReader = new XmlTextReader(objWebClient.OpenRead(path));
string objXml = string.Empty;

while(objXmlTextReader.Read())
{
   objXml = objXmlTextReader.ReadOuterXml;
}

string filePath = serverPath + “\” + Date.UtcNow.Year.Tostring();

if(File.Exists(filePath))
{  
   StreamWriter wr;
   File.Delete(filePath);
   wr = File.CreateText(filePath)
   wr.WriteLine(objXml)
   wr.Close();        
}
else
{
   StreamWriter wr;
   wr = File.CreateText(filePath)
   wr.WriteLine(objXml)
   wr.Close();
}

2) To query a REST service, like the one I mentioned above, we can use LINQ’s XML functionality.  The XElement class (declared in System.Linq.XML) provides a Load method that can retrieve an XML data from a url with GET  method:

XElement rootXml = XElement.Load(“http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=rest”);

var SearchResult = from R in rootXml.Elements()

select new { Topic = (string)R.Element(“Title”),

Detail = (string)R.Element(“Summary”),

Link = (string)R.Element(“Url”) };

foreach (var x in SearchResult)

Console.WriteLine(“{0}  {1}”, x.Topic, x.Detail, x.Link);

Console.ReadKey();

Using POST method is a bit more complex. First we have to obtain a channel by which we may POST the information. Then we have to create an instance of data entity in XML format. Finally we have to POST data through the channel.

To get access to REST service we use a HttpWebRequest since it lets use the POST method and let us specify the type of information we are posting.

HttpWebRequest channel = (HttpWebRequest)WebRequest.Create(“http://ws.geonames.org/countryInfo”);

channel.Method = “POST”;

channel.ContentType = “text/xml”;

HttpWebRequest class provides a stream to which we can write information :

StreamWriter sw = new StreamWriter(channel.GetRequestStream());

Then we can create a concerete entity to post:

XElement country = new XElement(“country” ,

new XElement(“countryCode”, “AUS”),

new XElement(“countryName” , “Australia”),

….

);

Finally we just need to save this XElement object to the stream we obtained from HttpWebRequest:

country.Save(sw);

References:

http://aspguy.wordpress.com/2008/10/10/dealing-with-rest-web-services/

http://developer.yahoo.com/dotnet/howto-rest_cs.html

2 Comments

Filed under .Net, C#

SET vs SELECT

SET and SELECT both key words are used to Assign Variables in SQL Server.

SET and SELECT both specifies the columns to be changed and the new values for the columns.
The values in the specified columns are updated with the values specified in the SET and SELECT in all rows that match the WHERE clause search condition.
If no WHERE clause is specified, all rows are updated.

There are some difference based on the Performance, Process like Follows :

1. SET is the ANSI standard for variable assignment, SELECT is not. 

2. SELECT can be used to assign values to more than one variable at a time, Whereas SET allows to assign data to only one variable at a time.

Example :

/* Declaring variables */
DECLARE @Var1 AS int, @Var2 AS int

/* The same can be done using SET, but two SET statements are needed */
SET @Var1 = 1
SET @Var2 = 2  

/* Initializing two variables at once */
SELECT @Var1 = 1, @Var2 = 2

But use SET instead SELECT, for variable initialization, It will throw the following error

SET @Var1 = 1, @Var2 = 2  

Msg 102, Level 15, State 1, Line 10
Incorrect syntax near ‘,’.

3. When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all .so the variable will not be changed from it’s previous value.  

Example :

Run it in master Database in SQL Server.

/* Returns NULL */
DECLARE @Title varchar(80)
–SET @Title = ‘Not Found’

SET @Title =
(
SELECT error
FROM SysMessages
WHERE Description = ‘Invalid Description’
)

SELECT @Title
GO

/* Returns the string literal ‘Not Found’ */
DECLARE @Title varchar(80)
SET @Title = ‘Not Found’

SELECT @Title = error
FROM SysMessages
WHERE Description = ‘Invalid Description’

SELECT @Title
GO  

4. Let using a query needs to populate a variable and the Query returns more than one value.
SET will fail with an error in this scenario.
But SELECT will assign one of the returned rows and mask the fact that the query returned more than one row.

As a result, bugs in your the could go unnoticed with SELECT, and this type of bugs is hard to track down too.

Example :

/* Consider the following table with two rows */
SET NOCOUNT ON
CREATE TABLE #Table (i int, j varchar(10))
INSERT INTO #Table (i, j) VALUES (1, ‘Sunday’)
INSERT INTO #Table (i, j) VALUES (1, ‘Monday’)
GO

/* Following SELECT will return two rows, but the variable gets its value from one of those rows, without an error.
you will never know that two rows existed for the condition, WHERE i = 1 */
DECLARE @j varchar(10)
SELECT @j = j FROM #Table WHERE i = 1
SELECT @j
GO

/* If you rewrite the same query, but use SET instead, for variable initialization, you will see the following error */
DECLARE @j varchar(10)
SET @j = (SELECT j FROM #Table WHERE i = 1)
SELECT @j

Msg 512, Level 16, State 1, Line 4
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Based on the above results, when using a query to populate variables, we should always use SET.
If you want to be sure that only one row is returned then only use SELECT, as shown below:

DECLARE @j varchar(10)
SELECT @j = (SELECT j FROM #Table WHERE i = 1)
SELECT @j

5. This very feature of SELECT makes it a winner over SET, when assigning values to multiple variables. A single SELECT statement assigning values to 3 different variables, is much faster than 3 different SET statements assigning values to 3 different variables.
In this scenario, using a SELECT is at least twice as fast, compared to SET.

Leave a comment

Filed under SQL

Report Data in Page Header/Footer

Reporting Services does not provide out of-the-box support for use of information from your queries in Page Headers and Footers. There are two ways around this.

The first way is to create controls in the body of your report, holding the values you need to display in the header and/or footer. You can set these controls to “hidden”, and place them in some out-of-the-way place, towards the bottom of the report. Then, you can set expressions on controls in your header and footer sections to the value of the control in the body of your report.

In the following example, shown in Figure 27, I placed a textbox control in the body of the report named “textbox1”, with a value of “Hello World”. In the header section, I placed a textbox with a value of “=ReportItems!textbox1.Value”. I then copied the control in the header section and pasted it into the footer section.

Figure : Display report data in headers and footers, using a hidden control in the body

If you preview this report, the value of “textbox1” will be displayed in the header and footer.

Figure: Three times Hello World

A slightly cleaner option, in my opinion, is to create a public function that can be called to set the value of a variable, which can then be used in any or all sections of the report body, header, and footer. Figure shows the embedded code that creates this SetReportTitle function, containing the _Title variable.

Figure: The SetReportTitle function.

In this example, you can then simply set the value of the hidden textbox in the body of your report to “=Code.SetReportTitle(“Report Title”)“. This calls our function and sets the value of the _Title variable to Report Title.

Now, you can set the value of any control in the header or footer to “=Code._Title”. The variable can be used in any or all sections of the report body, header, and footer.

Leave a comment

Filed under SSRS