Category Archives: .Net

How does HTTPS works?

How does HTTPS works?

  1. Client request for secure Https  page.
  2. Web server respond by sending certificate with public key.
  3. Client checks the validity of the certificate and create a symmetric session key using the public key and sends it back to Web serer.
  4. Web server decrypt the symmetric session key using it’s private key and sends page encrypted using the symmetric session key.
  5. Secure session has now been established between Client browser & Web server.

ssl-in-a-nutshell

HTTPS pages typically use one of two secure protocols to encrypt communications – SSL (Secure Sockets Layer) or TLS (Transport Layer Security). Both the TLS and SSL protocols use what is known as an ‘asymmetric’ Public Key Infrastructure (PKI) system. An asymmetric system uses two ‘keys’ to encrypt communications, a ‘public’ key and a ‘private’ key. Anything encrypted with the public key can only be decrypted by the private key and vice-versa.

The ‘private’ key should be kept strictly protected and should only be accessible the owner of the private key. In the case of a website, the private key remains securely ensconced on the web server. Conversely, the public key is intended to be distributed to anybody and everybody that needs to be able to decrypt information that was encrypted with the private key.

HTTPS-workflow

 

Leave a comment

Filed under .Net, ASP.Net, C#, WCF

What does cherry-picking a commit with git means?

Cherry picking in git means to choose a commit from one branch and apply it onto another.

This is in contrast with other ways such as merge and rebase which normally applies many commits onto a another branch.

Make sure you are on the branch you want apply the commit to.

git checkout master

Execute the following:

git cherry-pick

Refrences:-
What does cherry-picking a commit with git means?

Leave a comment

Filed under .Net

Imp Terms
IIS is the most popular ASP.Net web server provided by Micrsoft.

Worker Process: All asp.net application runs under the scope of Worker Process (w3wp.exe), which act as application boundary. When a request comes to the server from a client worker process is responsible to generate the request and response.

Application pool:
Application Pool is the container of worker process. An app pool can have multiple worker process that share same configuration, by default there is only one worker process per app pool. A server can have multiple App pool for different application.
eg: an enterprise organization might place its human resources Web site and its finance Web site on the same server, but in different application pools.

Application Pool with multiple Worker process is “Web Garden“.

Now the request handling by IIS is divided into two stages:
Kernal Mode
User Mode

1) In Kernal level, the request received by IIS is handled by HTTP.SYS, which identify the App pool to process the request.

2) In User Level, we have Web Admin Services (WAS) which takes the request from HTTP.SYS and pass it to App pool.

3) When App pool rceive the request it simply passes the request to the worker process (w3wp.exe) which looks up the URL of request to load the correct ISAPI extension.
ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll) and adds the mapping into IIS.

4) When wp loads the aspnet_iisapi.dll, it starts the HttpRuntime, which is the entry point of your application.

5) HttpRuntime calls the ProcessRequest method to start processing
HttpRuntime.ProcessRequest(HttpWorkerRequest wr)
It creates the instance of HttpContext which provide access to all it’s properties like Request, Response, Session using HttpContext.Current properties.

6) Then HttpRuntime loads HttpApplication object

References:
http://abhijitjana.net/2010/03/14/beginner%E2%80%99s-guide-how-iis-process-asp-net-request/
http://www.codeproject.com/Articles/42724/Beginner-s-Guide-Exploring-IIS-6-0-With-ASP-NET
http://www.iis.net/learn/get-started/introduction-to-iis/introduction-to-iis-architecture

http://www.codeproject.com/Articles/28693/Deploying-ASP-NET-Websites-on-IIS-7-0

Leave a comment

Filed under .Net

Encoding vs Encryption

First Similarities:
1) They both transform data into different format.
2) They both are reversible (unlike Hashing).

Differences:

Encoding
1) to transform data it uses a scheme that is publicly available
2) don’t require any key to transform, just algorithm & the same is used to decode it.
eg: ASCII, Unicode, Base64

Encryption
1) to transform data it uses the way that only specific user can reverse it.
2) it uses key with plaintext & algorithm to encrypt and the ciphertext, algorithm & key is used to decrypt it.
eg: AES, RSA

References:
http://danielmiessler.com/study/encoding_encryption_hashing/

Leave a comment

Filed under .Net

Difference between “==” and Equals() methods?

Value Type:- “==” & Equal() method usually compare object by value.

Reference Type:- “==” compares whether both the reference point to same object.
Equal() returns true if value at reference point to the object are equivalent.

there is an exception here for string that “==” compares value rather then object identity.

In the below example:- for value type is obvious, but for reference types s1 & s2 are different objects so it will return false where as both of objects are equivalent so it will return true.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Refrences

http://dotnetguts.blogspot.in/2007/07/difference-between-and-equals-method.html

1 Comment

Filed under .Net, C#

Why do we need Constructor for abstract class?

Yes we can have constructor in Abstract class (though we can’t still create object of abstract class).
Because :- this way you can instantiate the data in abstract class.
And inherited classes can call the base constructor.

public abstract class A{
private string data;
protected A(string myString){
data = myString;
}
}

public class B : A {

B(string myString) : base(mystring){}
}

NOTE:- As you can’t override constructor, so we can’t have abstract constructor.

Leave a comment

Filed under .Net, C#

Abstract method vs Virtual method

Abstract method Virtual method
1) Abstract method doesn’t have any body defined. 1) Virtual method have their body defined otherwise it will give compile-time error message “<VirtualMethod()> must declare body because it is not defined abstract, extern, or partial.
2) Mandatory to implement them. 2) Not mandatory to override them.
3) They can be defined in abstract classes only. 3) They can be defined in any instance class.

Leave a comment

Filed under .Net, C#

Generics

Generics has the below features:

— makes logic independent of DataTypes.

— strongly types as Array.

— flexible of DataTypes like arraylist without boxing & unboxing.

Below is the project which show use of two Generic classes CoreDemo & CoreDemoDual:

Generic Classes


2 Comments

Filed under .Net, C#

Compile Code into Assemblies

To service user request thru application code, it need to be compiled to one or more assemblies.

Assembly files have extension .dll. We can write ASP.net code in many languages like C#, VB.net, J# & others but when compiled, but when compiled, it will be translated into language-independent or CPU-independent language i.e. MS Intermediate Language(MSIL). At run-time in the context of .Net framework, the MSIL gets translated into CPU-specific instructions.

 Benefits of compiling the application code to Assemblies:

Performance:- Compiled code is much faster then scripting language because it’s representation is closer to machine code & doesn’t require additional parsing.

Security:- Compiled code is difficult to the reverse engineer as it lacks the readability & high level of abstraction.

Stability:- Code is checked at compile time for syntax error, type safety, & other problems. By caching these errors at build-time we can eliminate many errors in our code.

Inter-operability:- As MSIL code support all .Net languages so if you are writing an ASP.Net web page in C# then you can use reference of assemblies written in VB.net too.

Leave a comment

Filed under .Net

Abstract Class FACTS

Abstract Class FACTS

1) We can inherit abstract class from another abstract class also.

Eg:

public abstract class AbstractClass1

{
public abstract string TestMe();       

}

 It is inherited by AbstractClass2 

public abstract class AbstractClass2 : AbstractClass1

{
public abstract string DoSome();

public override string TestMe()

{

return “This is test”;

}

}

2) Abstract class can inherit Interface also.

Leave a comment

Filed under .Net, C#

User Control Bubble Event

A better idea is to publish an event in the user control to allow any interested parties to handle the event.

This technique is commonly referred to as “event bubbling”.

Here is an exmple:

<%@ Control Language=”C#” AutoEventWireup=”true” CodeBehind=”UserControlDemo.ascx.cs” Inherits=”WellnGood.UserControlDemo” %>
<asp:Button ID=”btn1″ runat=”server” Text=”Bubble to Page”
onclick=”btn1_Click” />

public partial class WebUserControl : System.Web.UI.UserControl

{

public event EventHandler buttonClick;

protected void Button1_Click(object sender, EventArgs e)
{
buttonClick(sender, e);
}

}

Then you can subscribe the event buttonClick at webpage to display the different information .

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”BubbleEvent.aspx.cs” Inherits=”WellnGood.BubbleEvent” %>

<%@ Register Src=”~/UserControlDemo.ascx” TagName=”UserControlDemo” TagPrefix=”ucDemo” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<ucDemo:UserControlDemo ID=”ucDemo1″ runat=”server” />
</div>
</form>
</body>
</html>

public partial class BubbleEvent: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

ucDemo1.buttonClick+=new EventHandler(ucDemo1_buttonClick);

}

protected void ucDemo1_buttonClick(object sender, EventArgs e)
{
Response.Write(“I am User control bubble event on Page”);
}

}

Leave a comment

Filed under .Net

Factory Pattern

Factory Pattern is a creational patter. It provide encapsulation by hiding the complex components and their dependencies from the client.
Why do we need?
1. A class can’t anticipate the class of object it must create.
2. Client don’t need to use lot of new keywords.
3. Classes delegate responsibility to one of several helper subclasses.
4. If you want to develop a data layer that supports many types of database products, it should not be tightly coupled with a particular database product or ADO.NET data provider.

Ex: we will be creating an Employee objects. As with good OO design we will start with an interface.

public interface IEmployee
{
string GetDepartment();
string GetEducation();
}

Now Concrete Classes: we define two class inheriting from IEmployee interface i.e CTechnology & CHumanResource

public Class CTechnology : IEmployee
{
public string GetDepartment()
{
return “IT Department”;
}

public string GetEducation()
{
return “Engineering”;
}
}

public class CHumanResource : IEmployee
{
public string GetDepartment()
{
return “HR Department”;
}

public string GetEducation()
{
return “MBA”;
}
}

Now factory class, it is static and contain one method to return the correct object.
public class EmployeeFactory
{
public enum EmployeeType
{
IT, HR;
}

public static IEmployee CreateEmployee(EmployeeType empType)
{
switch(empType)
{
case EmployeeType.IT:
return new CTechnology;
break;

case EmployeeType.HR:
return new CHumanResource;
break;

default:
throw new ArgumentException(“Invalid Type of Employee”);
}
}
}

Now Client section: there are two buttons “IT EMployee” & “HR Employee” and two labels lblDept & lblEdu.

protected void Page_Load(object sender, EventArgs e)
{

}

protected void btnITEmployee_Click(object sender, EventArgs e)
{
IEmployee emp = EmployeeFactory.CreateEmployee(EmployeeFactory.EmployeeType.IT);
lblDept.Text = emp.GetDepartment();
lblEdu.Text = emp.GetEducation();
}

protected void btnHREmployee_Click(object sender, EventArgs e)
{
IEmployee emp =               EmployeeFactory.CreateEmployee(EmployeeFactory.EmployeeType.HR);
lblDept.Text = emp.GetDepartment();
lblEdu.Text = emp.GetEducation();
}

public interface IEmployee
{
string GetDepartment();
string GetEducation();
}Now we define two class inheriting from IEmployee interface i.e CTechnology & CHumanResource
public Class CTechnology : IEmployee
{
public CTechnology()
{

}
public string GetDepartment()
{
return “IT Department”;
}

public string GetEducation()
{
return “Engineering”;
}
}
public class CHumanResource : IEmployee
{
public CHumanResource()
{

}
public string GetDepartment()
{
return “HR Department”;
}

public string GetEducation()
{
return “MBA”;
}
}

Now our factory class, it is static and contain one method to return the correct object.
public class EmployeeFactory
{
public enum EmployeeType
{
IT, HR;
}

public static IEmployee CreateEmployee(EmployeeType empType)
{
switch(empType)
{
case EmployeeType.IT:
return new CTechnology;
break;

case EmployeeType.HR:
return new CHumanResource;
break;

default:
throw new ArgumentException(“Invalid Type of Employee”);
}
}
}

Leave a comment

Filed under .Net

How GC Works

How GC works

The GC maintains lists of managed objects arranged in “generations.” A generation is a measure of the relative lifetime of the objects in memory. The generation number indicates to which generation an object belongs. Recently created objects are stored in lower generations compared to those created earlier in the application’s life cycle. Longer-lived objects get promoted to higher generations.

Because applications tend to create many short-lived objects compared to relatively few long-lived objects, the GC runs much more frequently to clean up objects in the lower generations than in the higher ones.

Finalization is the process, by which the GC allows objects to clean up any unmanaged resources that they’re holding,

Note that you cannot call or override the Finalize method. It is generated implicitly if you have a destructor for the class.

~Test

{

//Necessary cleanup code

}

Dispose method must call GC.SuppressFinalize(this) to prevent the finalizer from running.

public void Dispose()

{

Dispose(true);

GC.SuppressFinalize(this);

}

Finalize Dispose
The execution order of finalize is non-deterministic. It’s execution is deterministic by using call to Dispose() method.
It doesn’t use any interface. It uses IDisposable interface and then override it’s Dispose() method.
you cannot  override the Finalize method, as it is generated implicitly destructor. Dispose is not depended on destructor.
You can suppress Finalize() by using GC.SuppressFinalize(this) You can’t suppress Dispose() as it is not called implicitly.

Leave a comment

Filed under .Net

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

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

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

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

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#

HttpHandlers

Using http handlers we can add new functionalities to Web Server. Files with new extensions like .text for a text file can be handled by Web Server by using http handlers. The future of customization can lead to hosting .jsp pages in IIS by finding adequate ISAPI extensions.

To create customized http handler we need to Create a C# class library as “Examplehandler” and implement IHttpHandler interface.

eg: maps all HTTP requests for files with file name extension .New to the class MyHandler.New

<configuration>
   <system.web>
      <httpHandlers>
         <add verb=”*” path=”*.New” type=”MyHandler.New,MyHandler”/>
      </httpHandlers>
   <system.web>
</configuration>

eg: To configure Web services to enable calls from Ajax enabled client script, we need to register the ScriptHandlerFactory HTTP handler in web.config.

<httpHandlers>

   <remove verb=”*” path=”*.asmx”/>

      <add verb=”*” path=”*.asmx” validate=”false”     type=”System.Web.Script.Services.ScriptHandlerFactory,     System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″/>

</httpHandlers>

Firstly you need to remove the default httphandler assigned to *.asmx

Leave a comment

Filed under .Net

LINQ

LINQ
Using Linq ( Language Integrated Query) we can manipulate any object which is implemented by the IEnumerable<T> interface, XML, Dataset or relational database.

The core Linq assemblies are
System.Core.dll :- The core LINQ API.
System.Data.Linq.dll :- LINQ with relational databases (LINQ to SQL).
System.Data.DataSetExtensions.dll :- ADO.NET types into the LINQ programming paradigm (LINQ to DataSet).
System.Xml.Linq.dll :- LINQ with XML document data (LINQ to XML).

Linq Query Operators
from, in :- Used to start the LINQ expression.
where :- Used to filter the data.
select :- Used to select the data.
join, on, equals, into :- Performs joins based on specified key.
orderby, ascending, descending :- Allows the data to be ordered in ascending or descending order.
group, by :- Data grouped by a specified value.

Advantage of LINQ over stored procedures.
1. Debugging – It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you can use visual studio’s debugger to debug the queries.
2. Deployment – With stored procedures, we need to provide an additional script for stored procedures but with LINQ everything gets complied into single DLL hence deployment becomes easy.
3. Type Safety – LINQ is type safe, so queries errors are type checked at compile time. It is really good to encounter an error when compiling rather than runtime exception!

Query Expression
string[] Weekdays = {“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday” };
IEnumerable<string> WeekdaysWithLength = from W in Weekdays
where W.Length> int.Parse(textBox1.Text)
orderby W
select W;

var WeekdaysWithLength = from W in Weekdays
where W.Length > int.Parse(textBox1.Text)
orderby W
select W;
IEnumerable<string> is the explicit object, & var is implicit object, which will convert to assign type by compiler.

Extension Methods
Linq provides a set of generic extension methods e.g. Aggregate<T>(), Max<T>(), Distinct<T>() etc.
eg:
string[] WeekdaysWithLength = (from W in Weekdays where W.Length > int.Parse(textBox1.Text)
orderby W descending select W).Distinct<string>();

Leave a comment

Filed under .Net, C#

XAML – Extensible Application Markup Language

Extensible Application Markup Language (XAML) is a .NET technology. It’s a markup language that can be used to help create desktop applications, web pages, and printable documents.
XAML is a declarative XML-based language that defines objects and their properties in XML.
It provides abbreviated markup syntax for specific types of elements that take advantage of the underlying Common Language Runtime (CLR) class constructors. Each XAML element has a name and one or more attributes. Attributes correspond directly to object properties, and the name of the XAML element exactly matches the name of a CLR class definition.
XAML is pure markup, which means that while the names of event handlers are specified as attributes, you must implement the actual logic of the event handler in code like C# or VB.net.
Every event in XAML can be assigned to a codebehind handler,which is implemented in a supported .NET language. eg: Button click event
<Button
OnClick=”ButtonClickedHandler”
Name=”MyButton”
Width=”50″
Content=”Click Me!” />

a corresponding codebehind handler is declared
void ButtonClickedHandler(object sender, RoutedEventArgs eventArgs)
{
MyButton.Width = 100;
MyButton.Content = “Thank you!”;
}

All XAML attributes can be manipulated within code because they are simply XML representations of actual CLR class attributes.
It is also acceptable to inline code in the XAML file by specifying the <x:Code> element.
All inline code must be enclosed in the <CDATA[…]]> tag to ensure that the parser does not try to interpret the code. eg:
<x:Code>
<![CDATA
void ButtonClickedHandler(object sender, RoutedEventArgs eventArgs)
{
MyButton.Width = 100;
MyButton.Content = “Thank you!”;
}
]]>
</x:Code>

for application logic developers to access specific XAML elements, the elements must be named using either the Name or ID attribute which will be used to manipulate the element in the code.
Three basic rules to follow when declaring XAML elements:
1) XAML is case-sensitive. Element and attribute names must be properly cased.
2) All attribute values, regardless of data type, must be enclosed in double quotes.
3) The resulting XML must be well-formed. like end tag etc.

Elements can be declared all on one line, or attribute declarations can be split across lines; formatting is completely up to you. Because XAML is compiled into Binary Application Markup (BAML) file (This is a binary representation of XAML auto-genned by Visual Studio) before deployment, the amount of space taken up by elements in a XAML file is irrelevant. There are no advantages to using less space by declaring elements on a single line and no disadvantages to the formatting.

All XAML elements are an XML representation of CLR classes, but not all CLR classes are represented in XAML.
XAML element represents a .NET CLR class. but not all CLR classes are represented in XAML. Most of those represented are user-interface elements and are ultimately derived from System.Windows.UIElement, System.Windows.FrameworkContentElement.

XAML elements can be organized into five basic categories
1) Root elements
A page is required to have one root element. Windows and Page elements are the most common root elements.
2) Panel elements
These elements help you to lay out your user interface.  eg: StackPanel, DockPanel, Grid and Canvas.
3) Control elements
Controls are interactive and allow the user to enter data, make choices, and perform other interactive tasks.
eg: Button, CheckBox, RadioButtonList, ComboBox, MenuItem
<MenuItem Header=”First Menu Item”>
<MenuItem Header=”First Child Item” />
<MenuItem Header=”Second Child Item” />
</MenuItem>
4) Geometric elements
This kind of elements helps you to draw shapes and geometric graphics on your UI. eg: LineGeometry, EllipseGeometry, PathGeometry.
5) Document elements
use to deal with presentation of a document. eg: Bold, LineBreak and Italic, Paragraph, List, Block, Figure and Table.
Example:
<Window x:Class=”IntroductionToXAML.Window1″
xmlns=”
http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=”
http://schemas.microsoft.com/winfx/2006/xaml
Title=”Introduction To XAML” Height=”200″ Width=”300″
>
<StackPanel>
<TextBox Name=”MyTextBox”
Width=”200″
Height=”30″
Margin=”40″ />
<Button Click=”ButtonClickHandler”
Width=”60″
Height=”20″>
Content=”Click Me!”
</Button>
</StackPanel>
<x:Code>
<![CDATA[
void ButtonClickHandler(object sender, RoutedEventArgs e)
{
MessageBox.Show(string.Format
(“You typed ‘{0}’ in TextBox!”, MyTextBox.Text), “XAML”);
}
]]>
</x:Code>
</Window>
Benefit of XAML
1) The Run Time :- The ASPX uses the ASP.Net Run Time which is loaded in the IIS, rather Silver Light Runtime is a portion of CLR. Which we can download dowload in to the Client Machine and perform operations.
2) The XAML supports Rich User Interface, which means no need of JS and others. We can use the Straight away .NET WPF Animation Functions.
3) It also supports the Out Of Browser Support. (We can use the Server Web Application as a Client Application). Its included in Silverlight 4.0
4) In XAML you do not need to put a name as identifier for your controls unless you want to refer to them from other parts of your code.

Q: Can XAML be used to develop both Web and client-server applications?
Ans: XAML is used as part of Windows Presentation Foundation to write smart client applications that take advantage of the power of the PC and benefit from all of the power of the CLR. For Windows Presentation Foundation applications, the logic runs on the client, unlike ASP.NET, which processes on the server. ASP.NET continues to be the answer to producing powerful Web applications that take advantage of the benefits of the CLR on the server.

Leave a comment

Filed under .Net, C#

Serialization

Serialization is a process of converting an object into a stream of data so that it can be is easily transmittable over the network or even stored in a database or file system. This storage location can be a physical file, database or ASP.NET Cache.
In .NET it is provided by the System.Runtime.Serialization namespace.  This namespace contains an interface called IFormatter which in turn contains the methods Serialize and De-serialize that can be used to save and load data to and from a stream.

Types
Serialization can be of the following types:

·         Binary Serialization

·         SOAP Serialization

·         XML Serialization

·         Custom Serialization
Binary Serialization
Binary serialization is a mechanism which writes the data to the output stream. All members including private & public, no matter if they are read-only. It is used commonly in .NET’s Remoting technology.
The easiest way to make a class serializable is to mark it with the Serializable attribute.
[Serializable]
public class MyObject {
public int n1 = 0;
public int n2 = 0;
public String str = null;
}

//Serialize the object
Create an instance of stream and BinaryFormatter and then call Serialize method on formatter.
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = “Some String”;
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(“MyFile.bin”, FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();

//De-serialize the object
Create an instance of stream and BinaryFormatter and then call de-Serialize method on formatter.
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(“MyFile.bin”, FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject) formatter.Deserialize(stream);
stream.Close();

// Here’s the proof.
Console.WriteLine(“n1: {0}”, obj.n1);
Console.WriteLine(“n2: {0}”, obj.n2);
Console.WriteLine(“str: {0}”, obj.str);

XML Seriallization
XML serialization converts (serializes) the public fields and properties of an object, into an XML stream to a XML Schema definition language (XSD) document.
Because XML is an open standard, the XML stream can be processed by any application. It use is the XmlSerializer for both serialization and de-serialization. XML Serialization is however, much slower compared to Binary serialization.

Public class Employee
{
[XmlAttribute(“empName”)]
public string EmpName
{
get
{
return empName;
}
set
{
empName = value;
}
}
}

//Serialize the object
Create an instance of stream and XmlSerializer and then call Serialize method on formatter.

DataContractSerializer

The System.Runtime.Serialization.DataContractSerializer is new in .Net 3.0. used by Wcf, but can be used for general serialization as well.

the only real key difference is that you use a WriteObject() method to serialize instead of a Serialize() method and a ReadObject() method to deserialize instead of a Deserialize() method. It works with the same types of streams, so you can write to memory, files, etc. eg:

DataContractSerializer dataContractSerializer =

new DataContractSerializer(typeof(MyType));

// Serialize from an object to a stream

dataContractSerializer.WriteObject(stream, myInstanceOfMyType);

// Deserialize from a stream to an object

myInstanceOfMyType = (MyType)dataContractSerializer.ReadObject(stream);

XmlSrializer DataContractSerialize
1 Opt-out rather than opt-in properties to serialize. This mean you don’t have to specify each and every property to serialize. Opt-in rather than opt-out properties to serialize. This mean you specify what you want serialize.
2 Can only serialize Public Properties. It can serialize properties, fields & that can be private, protected or public.
3 Slower then DataContractSerialize 10% faster then XmlSrializer
4 Cannot understand the DataContractAttribute and will not serialize it unless there is a SerializableAttribute too Can understand the SerializableAttribute also and know that it needs to be serialized
5 Use only different attributes to serialize like XmlIgnoreAttribute, XmlRootAttribute, XmlAttributeAttribute, XmlElementAttribute Use only 2 attributes to serialize i.e  DataContactAttribute & DataMemberAttribute
6 use a Serialize() & Deserialize() method. use a WriteObject() & ReadObject() method.

Leave a comment

Filed under .Net, C#

Access Modifier

Access Modifier Meaning
public Access is not restricted.
protected Access is limited to the containing class or types derived from the containing class.
internal Access is limited to the current assembly.
protectedinternal Access is limited to the current assembly or types derived from the containing class.
private Access is limited to the containing type.

Only one access modifier is allowed for a member or type, except when using the protectedinternal combination.

Access modifiers are not allowed on namespaces. Namespaces have no access restrictions.

Members of Default accessibility Allowed declared accessibility of the member
enum public None
class private public

protected

internal

private

protected internal

interface public None
struct private public

internal

private

NB A class can not be declared as Protected.

Leave a comment

Filed under .Net, C#