Most Viewed

Most Viewed

Sunday 22 July 2012

Authentication & Authorization in ASP.Net

Authentication & Authorization in ASP.Net


This is a new security concept provided with asp.net.When client request comes to the web server, then web server will attach one user account for the anonymous user, based on which resources will be accessible. This is called as impersonation.
By default IUSR_MACHINENAME is the account attached to the anonymous user.
When you want to implement current security for the web application, then we require authentication and authorization.

Authentication, is nothing but the process of getting identity or credential of the user (means username and password)
Authorization is the process of giving access or denying access to a particular resource based on identity of the user.



Asp.net supports three types of authentication.
1.                       Windows based authentication
2.                       Form based authentication
3.                       Passport based authentication

Windows based authentication
This can be used only to the private website related to the organization i.e. intranet implementation.
This will perform authentication based on windows operating system.
(That is network label login or role)

Form based authentication
This will perform authentication based on users information maintained within database server. This is required for the commercial websites.
When client provides proper authentication information, asp.net runtime will respond with redirecting to requested page along with writing a cookie to the client machine.
This cookie will contain security token, so that subsequent request will be processed without authentication.

Redirectfromloginpage () will provide the user with the requested web page, based on the second parameter, cookie will be created with security token in the form of Inmemory cookie or persistent cookie. If it is Inmemory cookie the authentication is not required only for one browser window. If it is persistent cookie all the browser window from the system does not require authentication. The name of the cookie by default is aspxauth.
Providing name attribute within forms tag the cookie name can be changed.
The lifetime with the cookies by default is 30 minutes.

Passport authentication
When you want to perform common authentication for collection of website, then we require passport authentication. In this client will be authenticated only once and access is given to different websites. This is called as single sign on service 
The main disadvantage is that, the company’s client details will be mainted by Microsoft database.

Read more ...

Saturday 21 July 2012

Caching in ASP.Net



   Caching in ASP.Net

When you store most frequently used data on to the temporary storage and providing to different clients request, then it is called as caching.
The main advantage of caching is to improve the performance of the web server by reducing the processing time.
When you are expecting more no. of requests to a web page within a particular time interval, also the web page is having database interaction and the data within the database is not changing frequently then apply the caching.

ASP 3.0 supports, entire page caching only at client side.
ASP.Net supports 3 types of caching,
a. Output Caching (Entire page Caching) 
b. Fragment Caching (Portion of web Page as Caching)
c. Data Caching (memory Variable Caching)

Output caching is also termed as entire page caching.
When you want to maintain multiple buffers content towards a single web page then we require varybyparam option.
To achieve this output caching go to html view,
<%@ outputcache duration=”seconds” varybyparam=”none”%>

User defined control.
Web user control will provide reusability of graphical interfaces and coding.
It will compile dynamically along with web page.
The extension of the file is .ascx
This is local to the application, so it will not appear in the toolbox.
Caching can be applied to web user control.
When you want to make use of web user control within a web page then .ascx file has to be registered with the web page.
i.e. under html view,
<%@ Register TagPrefix="uc1" TagName="WebUserControl1" Src="WebUserControl1.ascx"%>

      A web user control is similar to webform but can’t be called independently.
It has to be contained by web form.

When you apply caching on a portion of web page then it is called as fragment caching. This can be achieved under web user control.

Data caching
When you apply caching on the memory variables, then it is called as data caching. This can be classified into three types.
1.           Ordinary caching
2.           File based dependency data caching
3.           Time based dependency data caching

In asp.net the alternative for application memory is provided with data caching.
This will overcome all the drawbacks of application memory variable like,
1. Data caching is a thread safe as compared to application memory.
So the lock method will be applied implicitly to the variable, which is used for modification.
Application. Lock ()
Application. Unlock ()
(Not required in case of caching)

2. Data caching supports expiry policy for the data, which is not supported by application memory variable.

System.web.caching (namespace)
                                   
Cache class
CacheDependency Class

Ordinary data caching
Cache. Insert (“A”, 100)
Or
Cache (“A”) = 100
File based dependency data caching
When you want to provide expiry policy of data, based on time stamp of the file, then it is called as file based dependency data caching.


Time based dependency data caching
When you want to provide expiry policy of data, based on time, then it is called as time based dependency data caching.
Time can be based on two types.
1.           Absolute time will be considered from storage time.
2.           Sliding time will be considered from the last access.

When it comes to data caching, the content will be erased, when application demands for the memory.


Read more ...

Tuesday 17 July 2012

ASP.Net Page Execution


ASP.Net Page Execution


·     Asp.net webpage is a class inherited from page class….
·     It will be compiled into dll file.
·     An object of -----.aspx class will be created, this will produce output to client browser.
·     The object will be destroying after providing output to client browser. The dll file will be maintained by server.
·     When the subsequent client request comes to webpage the object will be created from the dll and output will be provided to client.

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files

 

 ·     Asp.net worker process can be called as asp.net runtime. This will maintain http app factory and page handler factory. http app factory will contain app names running under worker process. Page handler factory will contain compiled webpage names. The requested app will be verified with http app factory. If it is not available it will create a block of memory and files related to app will be loaded into memory. This memory is called app domain.
·     The requested webpage will be verified with page handler factory. If it is not available the request will be given to http pipeline.
·     http pipeline is a collection of .net framework classes which will produce dll file for the webpage.
·     The request will be forwarded to http runtime this will encapsulate .net runtime (clr) it will create an object of webpage class and makes a call to process request method.
Read more ...

Sunday 15 July 2012

.Net Fundamentals & Architecture

                                      .NET fundamentals



.NET is a platform to create distributed applications

The Core Purpose of .NET is to connect different devices,systems,information and people.


.Net takes the best of XML to leverage the speed of Internet applications
.NET creates XML web services through which we can expose the needy methods to the users thru internet.
The clients on the other end can consume the web services.

This is one of the powerful features of .NET that makes reusability very easy.

The Advantages of .NET platform:

1.Side-by-side execution:

  .NET allows two different versions of the same component to be installed on the same system.
  i.e. we can run .NET framework 1.1 and 2.0 on the same PC

2.Ease of Deployment:
    .NET  allows different scenarious  for the deploying of the application  ex. XCopy deployment,windows installer,clickOnce etc
   these make the developers job much  more easier without any fuss of registering and coding.

3.Language independent:
  .NET is totally language independent as it supports huge number of languages alomost   40+
ex. c#,vb.net,j# cobol.net,php.net,fortran.net etc

4.partially platform independent :

 The .NET framework works on Windows and a project called 'mono-project' is being conducted to make it available for unix and linux as well
     

4.Highly Scalable:
.NET apps are highly scalable and can accomodate wide number of users.
 for example we can increase the performance of our website depending on the number of visitors.
Many of the performance tuning techniques of .NET help us to achieve this scalability

5.Secure

.NET provides high level of security to the applications by sophisticated and standard security mechanisms

6.Ease of development:

.NET increases the developer productivity as it allows the programmer to focus on the business logic alone.
all the mundane tasks of development were handled by .NET itself


    The Architecture of .NET


The languages supported by .net are called as .NET aware languages.

CLS: common language specification

 we can use a VB.NET class in a C# class.any of the .net aware languages  can utilize the other .net aware languages classes. This mechanism is called inter-operability
      this interoperability is achieved thru the CLS
     CLS contains a set of rules to be followed by all the .net aware languages

CTS:common type system

   CTS is the subset of CLS.
CTS promotes interoperability between the datatypes.

ex. vb.NET represents integer datatype with keyword 'Integer'
The C# with 'int'
if i need to use a c# class with vb.net the CTS type known as 'Int32' acts a representation of integer.
thus interoperability between datatypes is achieved thru CTS types.    

ASP.NET: ActiveServerPages.NET

  This is a technology to create Internet applications and mobile web Apps.
  It is mostly used to create websites
 we can use vb.net ,c# or j# to develop these sites.


WindowsForms: These are classic vb apps which represent desktop applications.
Mostly used for Gaming and graphical desinging.

ADO.NET: ActiveX Data Objects.NET

Any app deals with data. Inorder to retrieve data or dislay data or manipulate the information we can take the help of ADO.NET objects
ADO.NET is a collection of objects which enhance the power of dealing with the data
ADO.NET works in conjuction with XML to achieve data exchange

BCL: Base Class Library

this is the repository of huge number of classes all prepackaged to ease the development of .NET application
BCL contains 13000 classes which are organized as namespaces.
A namespace is a category which represent a certain classes belonging to specific functionality.

CLR:Common language runtime or runtime
   This is the foundation on which the total .net architecture lies upon  It performs all the major tasks of the framework

CLR functionalities:-

1. Compilation and CodeExecution
2. Automatic Memory Management
3. Exception Handling
4. Threading
5. Security
6. Type Safety


1.Compilation and Execution
Any .NET code is first compiled into MSIL -microsoftintermediate language. later this IL code is converted to native code by JIT(just-in-time)Compiler or jitter


Visualstudio.net: this is IDE -integrated development environment to create .NET apps.
 This is a design tool integrated with all .nET technologies to create .NEt software
the latest version is visualstudio2005








 
  
Read more ...

Conditional and Obsolete keyword in C#.Net

Conditional and Obsolete keyword in C#.Net

The attribute Obsolete is used to mark types and members of types that should no longer be used.

The Conditional attribute is an alias for ConditionalAttribute, and can be applied to a method or an attribute class



Demonstrate Conditional and Obsolete keyword in C#.Net
#define DEBUG
using System;
using System.Diagnostics;
class Class1
{            [Conditional ("DEBUG") ]
public static void disp1()       {
       Console.WriteLine(" Trying out Conditional Attributes") ;
              }
[Obsolete("this function is outdated!",false)] //changing false to true will cause error
public static void disp2(){    
Console.WriteLine(" Trying out an Obsolete Attributes") ;
              }
              static void Main(string[] args)
              {     disp1();disp2();Console.Read();
              }
}
Read more ...

Example on Delegate, Multicast delegate, Events in C#.Net


Demonstrates delegate in C#.Net
using System;
class Class1
{     public delegate int Calc(int a,int b);
              static int  Multi(int val1,int val2)
              {return val1*val2;}
              static void Main(string[] args)
              {     Calc  delObj = new  Calc(Multi);
Console.Write("Enter val1:");int v1 = Int32.Parse(Console.ReadLine());
Console.Write("Enter val2:");int v2= Int32.Parse(Console.ReadLine());
              int val=delObj(v1,v2);
              Console.WriteLine ("Mutiplication :"+val);
              Console.Read();
              }

}

Demonstrate Multicast delegate in C#.Net
using System;
class Client1
{public void mesg(string s)
       { Console.WriteLine("Mesg to client1:"+s);}
}
class Client2
{public void mesg(string s)
       { Console.WriteLine("Mesg to client2:"+s);}
}
class Client3
{public void mesg(string s)
       {Console.WriteLine("Mesg to client3:"+s);}
}
public class Class1
{     delegate void DelClient (string s);
       public static void Main()
       {
       DelClient del=new DelClient(new Client1().mesg);
         del+=new DelClient(new Client2().mesg);
         del+=new DelClient(new Client3().mesg);
       del("Meeting at 11 am");
       Console.Read();
       }
}

Demonstrating event handling technique in C#.Net
using System;
class EventSource
{     public delegate void EventDelegate();
       public event EventDelegate myEvent;
       public void eventRaiser(){myEvent();}
}
       class EventListener
       {     static void Main(string[] args)
              {
                     EventSource es=new EventSource();
       es.myEvent+=new EventSource.EventDelegate(myEventHandler);
                     es.eventRaiser();
                     Console.Read();
              }
              private static void myEventHandler()
              {
              Console.WriteLine("Event Handler is called!");
               }
       }
Read more ...

C#.Net Remoting application


Steps for C#.Net Remoting application :

  1. Create service first
  2. Create server  object by ref. service
  3. create client  code.

  1. Create Service first – new project à class library à

Create a folder  : c:\remotingdemo and store class library , client and server in this folder.

New Project à Class Library à SimpleRemotingLibrary
Location : c:\>remotingDemo

using System;
using System.Collections.Generic;
using System.Text;

namespace SimpleRemotingLibrary
{
    public class RemoteObject:MarshalByRefObject
    {

        public RemoteObject()
        {
            Console .WriteLine (" constructor called for RemoteObject");
        }
        public void DisplayMessage(string msg)
        {
            Console.WriteLine("Message : " + msg);
        }
        public string ReturnMessage()
        {
            return ("Hello from server");
        }
    }
}

Build Solution

Step 2 :

New Project à Console Application  à SimpleRemoteObjectServer
Location : c:\>remotingDemo

// Server application – Console application
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Remoting.Channels;
namespace SimpleRemoteObjectServer
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                HttpChannel c = new HttpChannel(32469);
                ChannelServices.RegisterChannel(c,false);
                RemotingConfiguration.RegisterWellKnownServiceType(typeof(SimpleRemotingLibrary.RemoteObject), "RemotingObject.soap", WellKnownObjectMode.Singleton);
                Console.WriteLine("Server is ready... Tap any key to stop service");
                Console.ReadKey();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

        }
    }
}

Build  Solution:

New Project à Console Application  à SimpleClient
Location : c:\>remotingDemo

step 3 :

// client application – Console application
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Proxies;

namespace SimpleClient
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpChannel c = new HttpChannel();
            ChannelServices.RegisterChannel(c,false );
            object remobj = Activator.GetObject(typeof(SimpleRemotingLibrary.RemoteObject), "http://localhost:32469/RemotingObject.soap");
            SimpleRemotingLibrary .RemoteObject  simple= (SimpleRemotingLibrary .RemoteObject ) remobj ;
            simple.DisplayMessage ("Hello From Client - Murthy" );
            Console.WriteLine ("Server says : "+simple.ReturnMessage ());
            Console.ReadKey ();
        }
    }
}


Add existing Project à SimpleServerObject.exe code from bin/debug directory to client application .

Then goto solution à right click à properties à select Multiple Projects à first star server application then start client application à start  (Order it properly).


Run the application  and see the output.


Read more ...

Event Bubbling in .Net

Event Bubbling in C#.Net

the repeater can do more than just displaying data. it can contain some other controls in the itemtemplate. all these controls are called child controls to the parent control the repeater (or anyother container) when the child raises an event the parent can handle that event which is called eventbubbling.

datalist,datagrid also support event bubbling.

this is a better approach because its difficult to for each individual child control to have its own eventhandlers

now everthing is taken care of the parent or the container control.

but how do the parent know which particular child had raised the event. we have commandsource property for a container which helps us to figure it out . 
Read more ...

Delegates in C#.Net

Delegates in C#.Net

A delegate is a typesafe function pointer

It points to the methods(or functions )  which match to its signature

A delegate is typesafe becoz it will accept the functions with same datatypes as of its own arguments

if the parametres does not match it throws an error

Advantages:

1. It can point any method that matches..so we can have muticast delegates
2.which method is invoked is postponed until runtime
3 Delegates are the basis for events

Addressof: this represents the address of the method being called by the delegate
ex: delegateobject=Addressof MyMethodOne

Invoke: This method invokes the  method matching the delegates signature

delegateobject.Invoke("MyStringArgument")



The Delegate statement defines the parameter types and return type of a delegate class. Any procedure with matching parameters types and return type may be used to create an instance of this delegate class. The procedure can then later be invoked by means of the delegate instance, by calling the delegate's Invoke method.

Delegates can be declared at the namespace, module, class, or structure level, but not within a procedure.

Each delegate class defines a constructor that is passed the specification of an object method. An argument to a delegate constructor must be an expression of the form:

AddressOf [expression.]methodname

The compile-time type of the expression must be the name of a class or an interface that contains a method of the specified name whose signature matches the signature of the delegate class. The methodname can be either a shared method or an instance method. The methodname is not optional, even if you create a delegate for the default method of the class.

The AddressOf operator creates a function delegate that points to the function specified by procedurename. When the specified procedure is an instance method then the function delegate refers to both the instance and the method. Then, when the function delegate is invoked the specified method of the specified instance is called.

The AddressOf operator can be used as the operand of a delegate constructor or it can be used in a context in which the type of the delegate can be determined by the compiler






Example 1:
The following is a simple example of declaring and using a delegate. Notice that both the delegate, Del, and the associated method, MultiplyNumbers, have the same signature


// Declare a delegate
delegate void Del(int i, double j);

class MathClass
{
    static void Main()
    {
        MathClass m = new MathClass();

        // Delegate instantiation using "MultiplyNumbers"
        Del d = m.MultiplyNumbers;

        // Invoke the delegate object.
        System.Console.WriteLine("Invoking the delegate using 'MultiplyNumbers':");
        for (int i = 1; i <= 5; i++)
        {
            d(i, 2);
        }
    }

    // Declare the associated method.
    void MultiplyNumbers(int m, double n)
    {
        System.Console.Write(m * n + " ");
    }
}


Output
Invoking the delegate using 'MultiplyNumbers':

2 4 6 8 10
----------------------------------------------------------

Example 2:

In the following example, one delegate is mapped to both static and instance methods and returns specific information from each.


// Declare a delegate
delegate void Del();

class SampleClass
{
    public void InstanceMethod()
    {
        System.Console.WriteLine("A message from the instance method.");
    }

    static public void StaticMethod()
    {
        System.Console.WriteLine("A message from the static method.");
    }
}

class TestSampleClass
{
    static void Main()
    {
        SampleClass sc = new SampleClass();

        // Map the delegate to the instance method:
        Del d = sc.InstanceMethod;
        d();

        // Map to the static method:
        d = SampleClass.StaticMethod;
        d();
    }
}



Output
A message from the instance method.

A message from the static method.

 

Anonymous Methods

In versions of C# previous to 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduces anonymous methods.

Creating anonymous methods is essentially a way to pass a code block as a delegate parameter.

For example:


// Create a handler for a click event
button1.Click += delegate(System.Object o, System.EventArgs e)
                   { System.Windows.Forms.MessageBox.Show("Click!"); };


or


// Create a delegate instance
delegate void Del(int x);

// Instantiate the delegate using an anonymous method
Del d = delegate(int k)
 {
  Console.WriteLine("Iam an Anonymous Method")


 };

 By using anonymous methods, you reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method.
For example, specifying a code block in the place of a delegate can be useful in a situation when having to create a method might seem an unnecessary overhead

Example 3

The following example demonstrates the two ways of instantiating a delegate:

Associating the delegate with an anonymous method.

Associating the delegate with a named method (DoWork).

In each case, a message is displayed when the delegate is invoked.


// Declare a delegate
delegate void Printer(string s);

class TestClass
{
    static void Main()
    {
        // Instatiate the delegate type using an anonymous method:
        Printer p = delegate(string j)
        {
            System.Console.WriteLine(j);
        };

        // Results from the anonymous delegate call:
        p("The delegate using the anonymous method is called.");

        // The delegate instantiation using a named method "DoWork":
        p = new Printer(TestClass.DoWork);

        // Results from the old style delegate call:
        p("The delegate using the named method is called.");
    }

    // The method associated with the named delegate:
    static void DoWork(string k)
    {
        System.Console.WriteLine(k);
    }
}



Output
The delegate using the anonymous method is called.

The delegate using the named method is called.



 






Read more ...