Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Saturday, April 30, 2011

How To Perform Scheduled Backups For SQL Server 2005 Express

SQL Server 2005 Express edition is a free, lightweight and embeddable version of SQL Server 2005 which includes SQL Server Management Studio Express for users to easily manage that databases. Although SQL Server 2005 Express edition supports backup and restore database but it does not supports scheduling backups.


 Below are the simple steps to perform in order to enable scheduling backups for SQL Server 2005 Express:

   1. Create a store procedure that allows generate the dynamic backup file name, with types of backup to run such as full, differential or transaction log backups and location of the Backup files.

      USE [master]

      CREATE PROCEDURE [dbo].[sp_BackupDatabase]
      @databaseName sysname, @backupType CHAR(1)
      AS
      BEGIN
      SET NOCOUNT ON;

      DECLARE @sqlCommand NVARCHAR(1000)
      DECLARE @dateTime NVARCHAR(20)

      SELECT @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),111),'/','') +
      REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','')

      IF @backupType = 'F'
      SET @sqlCommand = 'BACKUP DATABASE ' + @databaseName +
      ' TO DISK = ''C:\Backup\' + @databaseName + '_Full_' + @dateTime + '.BAK'''

      IF @backupType = 'D'
      SET @sqlCommand = 'BACKUP DATABASE ' + @databaseName +
      ' TO DISK = ''C:\Backup\' + @databaseName + '_Diff_' + @dateTime + '.BAK'' WITH DIFFERENTIAL'

      IF @backupType = 'L'
      SET @sqlCommand = 'BACKUP LOG ' + @databaseName +
      ' TO DISK = ''C:\Backup\' + @databaseName + '_Log_' + @dateTime + '.TRN'''

      EXECUTE sp_executesql @sqlCommand
      END

   2. Create a SQL script to run the backup. In this example, we will backup database master and saved the below SQL script as dbbackup.sql and save in “c:\Backup” folder.

      sp_BackupDatabase 'master', 'F'
      GO
      QUIT
   3. Create a scheduled task in Windows which can be found in Control Panel or Accessories -> System Tools -> Scheduled Tasks or Task Scheduler.





 Click on Add Scheduled Task or Create Task. Scheduling wizard will be displayed. Click Next, then click the Browse button to find SQLCMD.EXE from “C:\Program Files\Microsoft SQL Server\90\Tools\Binn”.






In Task Scheduler, define the above in Action tab.
Specify when to perform the task as well as the user name and password to run the operation. Once finished, give the scheduled task a name and save the task.
Click on the “Open advanced properties” to edit the command.







 Type the following command in Run:

 sqlcmd  -S prog3 -E -Q "EXECUTE sp_BackupDatabase 'master', 'F'"



      The meaning of the command:
          * sqlcmd
          * -S (this specifies the server\instance name for SQL Server)
          * serverName (this is the server\instance name for SQL Server)
          * -E (this allows you to make a trusted connection)
          * -i (this specifies the input command file)

If you want to test the task which has been created then you can go back to the Scheduled Tasks or Task Scheduler, right click on the task and select “Run”.
















Monday, April 25, 2011

Monday, April 18, 2011

What is Delay signing ?


During development process you will need strong name keys to be exposed to developer which is not a good practice from security aspect point of view.In such situations you can assign the key later on and during development you an use delay signing
Following is process to delay sign an assembly:
√ First obtain your string name keys using SN.EXE.
√ Annotate the source code for the assembly with two custom attributes from System.Reflection: ssemblyKeyFileAttribute, which passes the name of the file containing the public key as a parameter to its constructor. AssemblyDelaySignAttribute, which indicates that delay signing, is being used by passing true as a parameter to its constructor.
 For example as shown below:
[Visual Basic]
<Assembly:AssemblyKeyFileAttribute("myKey.snk")>
<Assembly:AssemblyDelaySignAttribute(true)>
[C#]
[assembly:AssemblyKeyFileAttribute("myKey.snk")]
[assembly:AssemblyDelaySignAttribute(true)]
The compiler inserts the public key into the assembly manifest and reserves space in the PE file for the full  strong name signature. The real public key must be stored while the assembly is built so that other assemblies that reference this assembly can obtain the key to store in their own assembly reference.
√ Because the assembly does not have a valid strong name signature, the verification of that signature must be turned off. You can do this by using the –Vr option with the Strong Name tool.The following example turns off verification for an assembly called myAssembly.dll.
Sn –Vr myAssembly.dll

√ Just before shipping, you submit the assembly to your organization's signing authority for the actual strong name signing using the –R option with the Strong Name tool. The following example signs an assembly called myAssembly.dll with a strong name using the sgKey.snk key pair.
Sn -R myAssembly.dll sgKey.snk

How to add and remove an assembly from GAC?


There are two ways to install .NET assembly in GAC:-
√ Using Microsoft Installer Package. You can get download of installer from http://www.microsoft.com.
√ Using Gacutil. Goto “Visual Studio Command Prompt” and type “gacutil –i (assembly_name)”, where  assembly_name) is the DLL name of the project.

What is the concept of strong names ?


Twist :- How do we generate strong names or what is the process of generating strong names, What is use the of SN.EXE , How do we apply strong names to assembly, How do you sign an assembly? Strong name is similar to GUID(It is supposed to be unique in space and time) in COM components.Strong Name is only needed when we need to deploy assembly in GAC. Strong Names helps GAC to differentiate between two versions. Strong names use public key cryptography (PKC) to ensure that no one can spoof it.PKC use public key and private key concept.

What is GAC ?


Twist :- What are situations when you register .NET assembly in GAC ?
GAC (Global Assembly Cache) is used where shared .NET assembly reside. GAC is used in the following ituations :-
√ If the application has to be shared among several application.
√ If the assembly has some special security requirements like only administrators
can remove the assembly. If the assembly is private then a simple delete of
assembly the assembly file will remove the assembly.
Note :- Registering .NET assembly in GAC can lead to the old problem of DLL hell, where COM version was stored in central registry. So GAC should be used when absolutely necessary.

Is versioning applicable to private assemblies?


Versioning concept is only applicable to global assembly cache (GAC) as private assembly lie in their individual folders.

Where is version information stored of an assembly ?

Version information is stored in assembly in manifest.

What is Manifest?


Assembly metadata is stored in Manifest. Manifest contains all the metadata needed to do the following things  (See Figure Manifest View for more details):
√ Version of assembly
√ Security identity
√ Scope of the assembly
√ Resolve references to resources and classes.
√ The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language MSIL) code or in a stand-alone PE file that contains only assembly manifest information.

What is Difference between NameSpace and Assembly?


Following are the differences between namespace and assembly :
√ Assembly is physical grouping of logical units. Namespace logically groups
classes.
√ Namespace can span multiple assembly.

What is NameSpace?


Namespace has two basic functionality :-
√ NameSpace Logically group types, example System.Web.UI logically groups
our UI related features.
√ In Object Oriented world many times its possible that programmers will use the
same class name.By qualifying NameSpace with classname this collision is able to
be removed.

What are the different types of Assembly?


There are two types of assembly Private and Public assembly. A private assembly is normally used by a single application, and is stored in the application's directory, or a sub-directory beneath. A shared assembly is normally stored in the global assembly cache, which is a repository of assemblies maintained by the .NET runtime. Shared assemblies are usually libraries of code which many applications will find useful, e.g. Crystal report classes which will be used by all application for Reports.

What is a Assembly?



Assembly is unit of deployment like EXE or a DLL.
√ An assembly consists of one or more files (dlls, exe’s, html files etc.), and represents a group of resources, type definitions, and implementations of those types. An assembly may also contain references to other assemblies. These resources, types and references are described in a block of data called a manifest. The manifest is part of the assembly, thus making the assembly self-describing.
√ An assembly is completely self-describing.An assembly contains metadata information, which is used by the CLR for everything from type checking and security to actually invoking the components methods. As all information is in the assembly itself, it is independent of registry. This is the basic advantage as compared to COM where the version was stored in registry.
√ Multiple versions can be deployed side by side in different folders. These different versions can execute at the same time without interfering with each other. Assemblies can be private or shared. For private assembly deployment, the assembly is copied to the same directory as the client program that references it. No registration is needed, and no fancy installation program is required. 100 When the component is removed, no registry cleanup is needed, and no uninstall program is required. Just delete it from the hard drive. √ In shared assembly deployment, an assembly is installed in the Global Assembly Cache (or GAC). The GAC contains shared assemblies that are globally accessible to all .NET applications on the machine.

What is a Managed Code?



Managed code runs inside the environment of CLR i.e. .NET runtime. In short all IL are managed code. But if you are using some third party software example VB6 or VC++ component they are unmanaged code as .NET runtime (CLR) does not have control over the source code execution of the language.

What is a CLS(Common Language Specification)?


This is a subset of the CTS which all .NET languages are expected to support. It was always a dream of  Microsoft to unite all different languages in to one umbrella and CLS is one step towards that. Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner.

What is a CTS?


In order that two language communicate smoothly CLR has CTS (Common Type System).Example in VB you have “Integer” and in C++ you have “long” these datatypes are not compatible so the interfacing between them is very complicated. In order to able that two different languages can 1. Basic .NET Framework 99 Communicate Microsoft introduced Common Type System. So “Integer” datatype in VB6 and “int” datatype in C++ will convert it to System.int32 which is datatype of CTS. CLS which is covered in the coming question is subset of CTS.
Note: If you have undergone COM programming period interfacing VB6 application with
VC++ application was a real pain as the datatype of both languages did not have a
common ground where they can come and interface, by having CTS interfacing is smooth.

What is a CLR?


Full form of CLR is Common Language Runtime and it forms the heart of the .NET framework.
All Languages have runtime and its the responsibility of the runtime to take care of the code
execution of the program. For example VC++ has MSCRT40.DLL,VB6 has MSVBVM60.DLL,
Java has Java Virtual Machine etc. Similarly .NET has CLR. Following are the responsibilities of
CLR
 Garbage Collection :- CLR automatically manages memory thus eliminating
memory leaks. When objects are not referred GC automatically releases those
memories thus providing efficient memory management.
 Code Access Security :- CAS grants rights to program depending on the security
configuration of the machine. Example the program has rights to edit or create
a new file but the security configuration of machine does not allow the program
to delete a file. CAS will take care that the code runs under the environment of
machines security configuration.
 Code Verification :- This ensures proper code execution and type safety while
the code runs. It prevents the source code to perform illegal operation such as
accessing invalid memory locations etc.
 IL( Intermediate language )-to-native translators and optimizer’s :- CLR uses
JIT and compiles the IL code to machine code and then executes. CLR also
determines depending on platform what is optimized way of running the IL
code.

What is a IL?

Twist : What is MSIL or CIL , What is JIT?
(IL)Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL
(Common Intermediate Language). All .NET source code is compiled to IL. This IL is then
converted to machine code at the point where the software is installed, or at run-time by a Just-In-
Time (JIT) compiler.

Saturday, April 16, 2011

ASP.NET Interview Questions

While different interviewers may ask distinctive questions. So we have to drawn up a list of frequently asked asp.net interview questions. Read all the questions for success in the job interview.

1. What is ASP.NET?
2. What are the differences between ASP.NET and ASP?
3. Tell me ASP.NET versions list?
4. Which version is easy and stable according to you?
5. What are the best practices to follow to secure connection strings in an ASP.NET web application?
6. What is the advantage of storing an XML file in the applications App_Data folder?
7. What are the steps to follow to avoid Script Injection attacks?
8. What is the difference between Class And Interface?
9. Which method can be used to remove forms authentication cookie?
10. How can you control access to subfolders in a web application?
11. Is it possible to encrypt view state data of an aspx page?
12. What are Cookies in ASP.NET?
13. What is the difference between Session Cookies and Persistent Cookies?
14. Are Cookies secure?
15. How do you create a permanent cookie?
16. What is caching?
17. Give a simple example to show how to cache a web form without using @OutputCache directive?
18. What is HttpCachePolicy object’s SetAllowResponseInBrowserHistory method used for?
19. What is an HTTP Handler?
20. What is the difference between asynchronous and synchronous HTTP Handlers?
21. What is HTTP module?
22. Which class is responsible for receiving and forwarding a request to the appropriate HTTP handler?
23. What is the difference between HTTP modules and HTTP handlers?
24. What is fragment caching?
25. When caching is set at both the Web form and user control levels, How does the cache settings interact?
26. What is PartialCaching attribute used for?
27. In which namespace is the DataSet class present?
28. What is the use of DataSet.HasChanges() Method?
29. What is Microsoft ADO.NET?
30. List the 4 common ADO.NET Namespaces?
31. What is the difference between DataReader and DataAdapter?
32. How do you read an XML file into a DataSet?
33. How is a property designated as read-only?
34. When do you use ExecuteReader, ExecuteNonQuery, ExecuteScalar methods?
35. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
36. Which control would you use if you needed to make sure the values in two different controls matched?
37. Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?
38. How would you implement inheritance using VB.NET/C#?
39. What is the difference between boxing and unboxing?
40. Describe the difference between a Thread and a Process?
41. Describe the difference between inline and code behind?
42. How do you turn off cookies for one page in your site?
43. What are the 3 major types of connection objects in ADO.NET?
44. What is the difference between Named skins and Default skins?
45. What are the security concerns to keep in mind when using themes?
46. What are different page navigation techniques in ASP.NET?
47. What is the difference between Response.Redirect and Server.Transfer?
48. What is the difference between a web farm and a web garden?
49. What is the difference between Authentication and Authorization?
50. What are the best practices to keep in mind when accepting user input on a web application?
51. What are the steps to follow to share Session state information using a SQL database?
52. What is the difference between an EXE and a DLL?
53. What is cyclomatic complexity and why is it important?
54. What is the difference between a Debug and Release build?
55. What is the difference between Response.Write() and Response.Output.Write()?

Asp.net page and control life Cycle

Use full Links

********************code Library**************************
http://www.java2s.com/Code/ASP/CatalogASP.htm
http://www.m6.net/resources/asp.net_source_code.aspx
**********************************************************

******************Interview Question**********************
http://interviews.c-sharpcorner.com
http://www.siteadvisor.com/
http://www.dotnetfunda.com/interview/showcatquestion.aspx
http://www.daniweb.com/forums/thread149988.html#
**********************************************************



**************PDF Convertor****************
http://www.pdfonline.com/pdf2word/index.asp
*******************************************


********************Nested Query************************************************
http://www.codeproject.com/KB/database/nestedsets.aspx?msg=909894
********************************************************************************

*********************Database Synchronization*********************************
http://software.intel.com/en-us/articles/data-synchronization-which-technology/
******************************************************************************


************************.NET Architecture****************************************************
http://weblogs.asp.net/bsimser/archive/2006/08/13/3_2D00_tier-Architecture-wtih-ASP.NET-2.0.aspx#
http://www.aspdotnetcodes.com/Easy_Data_Binding_Accordion_GridView.aspx
http://forums.asp.net/t/1147715.aspx
http://www.codeproject.com/KB/applications/JumpyForum.aspx
******************************************************************************

********************Gurgaon Consultant*********************
http://www.naukri2000.com/careers/consultant_gurgaon.php3
**********************************************************


*****************Web Services******************
http://www.devx.com/dotnet/Article/20369/0/page/4
***********************************************

**************************Email Varification***********************************
http://my-addr.com/free-email-verification-tool/verify-email-address/reverse-email-lookup/verify_email.php?mail=ams@caryaire.com&x=15&y=10
******************************************************************************************************************************



***************Dictionary*******************************
http://virtualsalt.com/vocablst2.htm
********************************************************



********************WCF***********************
http://www.wcftutorial.net/WCF-Architecture.aspx
http://www.csharpkey.com/aspnet/index.htm
*************************************************



*************************Sqlserver Trigger*******************
http://msdn.microsoft.com/en-us/library/ms189799.aspx
*************************************************************


*************************Film Production Templates***************
http://templates.entheosweb.com/template_number/25353.asp
*****************************************************************
*****************************************************************
http://www.cafepress.com/cp/customize/makeadesign.aspx?clear=true&no=2#designer
*****************************************************************



************************* webserives**********************************
http://msdn.microsoft.com/en-us/magazine/cc163837.aspx
******************************************************

Send Email Using CDO

'If you have a GMail account then you can try this example to use the GMail smtp server
'The example will send a small text message
'You must change four code lines before you can test the code

'.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "Full GMail mail address"
'.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "GMail password"

'Use your own mail address to test the code in this line
'.To = "Mail address receiver"

'Change YourName to the From name you want to use
'.From = """YourName"" "

'If you get this error : The transport failed to connect to the server
'then try to change the SMTP port from 25 to 465

Sub CDO_Mail_Small_Text_2()
Dim iMsg As Object
Dim iConf As Object
Dim strbody As String
Dim Flds As Variant

Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")

iConf.Load -1 ' CDO Source Defaults
Set Flds = iConf.Fields
With Flds
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "Full GMail mail address"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "GMail password"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"

.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
.Update
End With

strbody = "Hi there" & vbNewLine & vbNewLine & _
"This is line 1" & vbNewLine & _
"This is line 2" & vbNewLine & _
"This is line 3" & vbNewLine & _
"This is line 4"

With iMsg
Set .Configuration = iConf
.To = "Mail address receiver"
.CC = ""
.BCC = ""
' Note: The reply address is not working if you use this Gmail example
' It will use your Gmail address automatic. But you can add this line
' to change the reply address .ReplyTo = "Reply@something.nl"
.From = """YourName"" "
.Subject = "Important message"
.TextBody = strbody
.Send
End With

End Sub

Sunday, April 10, 2011

Difference between 3-tier architecture and MVC in ASP.Net?

At first glance, the three tiers may seem similar to the MVC (Model View Controller) concept; however, topologically they are different. A fundamental rule in a three-tier architecture is the client tier never communicates directly with the data tier; in a three-tier model all communication must pass through the middleware tier. Conceptually the three-tier architecture is linear. However, the MVC architecture is triangular: the View sends updates to the Controller, the Controller updates the Model, and the View gets updated directly from the Model.

ASP.NET MVC (Model View Controller) Architecture

Introduction

This article is intended to provide basic concepts and fundamentals of ASP.NET MVC (Model View Controller) architecture workflow for beginners.
“M” “V” “C” stands for “MODEL” “VIEW” “CONTROLLER”. ASP.NET MVC is an architecture to develop ASP.NET web applications in a different manner than the traditional ASP.NET web development. Web applications developed with ASP.NET MVC are even more SEO (Search Engine) friendly.
Developing ASP.NET MVC application requires Microsoft .NET Framework 3.5 or higher.

MVC Interaction with Browser

Like a normal web server interaction, MVC application also accepts requests and responds to the web browser in the same way.


Inside MVC Architecture

The entire ASP.NET MVC architecture is based on Microsoft .NET Framework 3.5 and in addition uses LINQ to SQL Server.

What is a Model?

  1. MVC model is basically a C# or VB.NET class
  2. A model is accessible by both controller and view
  3. A model can be used to pass data from Controller to view
  4. A view can use model to display data in page.

What is a View?

  1. View is an ASPX page without having a code behind file
  2. All page specific HTML generation and formatting can be done inside view
  3. One can use Inline code (server tags ) to develop dynamic pages
  4. A request to view (ASPX page) can be made only from a controller’s action method
What is a Controller?
  1. Controller is basically a C# or VB.NET class which inherits system.mvc.controller
  2. Controller is a heart of the entire MVC architecture
  3. Inside Controller’s class action methods can be implemented which are responsible for responding to browser OR calling views.
  4. Controller can access and use model class to pass data to views
  5. Controller uses ViewData to pass any data to view 

MVC File Structure & File Naming Standards

MVC uses a standard directory structure and file naming standards which are a very important part of MVC application development.
Inside the ROOT directory of the application, there must be 3 directories each for model, view and Controller.
Apart from 3 directories, there must have a Global.asax file in root folder, and a web.config like a traditional ASP.NET application.
  • Root [directory]
    • Controller [directory]
      • Controller CS files
    • Models [directory]
      • Model CS files
    • Views [directory]
      • View CS files
    • Global.asax
    • Web.config






Friday, April 8, 2011

SQL SERVER – Fix : Management Studio Error : Saving Changes in not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can’t be re-created or enabled the option Prevent saving changes that require the table to be re-created

Once the table is created open the table in SSMS by clicking on the table name and selecting “Design.” Try to include another column to the existing table and click on save (CTRL+S). It will prevent it from saving and will emit the following error in popup.
Saving Changes in not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can’t be re-created or enabled the option Prevent saving changes that require the table to be re-created
 I like how SSMS takes stance of displaying warning message and stops user from going further to do operation, thereby preventing hanging of SSMS. However, this feature can cause inconvenience in a situation when one is required to save table using SSMS. If such situation arises, then this feature can be turned off by going to Menu >> Tools >> Options >> Designers >> Uncheck “Prevent Saving changes that require table re-creation”.


This restriction only applies to operation attempted using only SSMS. If modification of tables are attempted using T-SQL in Query Editor, it will work just fine!

ASP .Net Page Life Cycle

1. OnInit (Init) Initializes each child control of the current
2. LoadControlState: Loads the ControlState of the control. To use this method, the control must call the Page.RegisterRequiresControlState method in the OnInit method of the control.
3. LoadViewState: Loads the ViewState of the control.
4. LoadPostData: Is defined on interface IPostBackDataHandler. Controls that implement this interface use this method to retrieve the incoming form data and update the control̢۪s properties accordingly.
5. Load (OnLoad): Allows actions that are common to every request to be placed here. Note that the control is stable at this time; it has been initialized and its state has been reconstructed.
6. RaisePostDataChangedEvent: Is defined on the interface IPostBackData-Handler. Controls that implement this interface use this event to raise change events in response to the Postback data changing between the current Postback and the previous Postback. For example, if a TextBox has a TextChanged event and AutoPostback is turned off, clicking a button causes the Text-Changed event to execute in this stage before handling the click event of the button, which is raised in the next stage.
7. RaisePostbackEvent: Handles the client-side event that caused the Postback to occur
8. PreRender (OnPreRender): Allows last-minute changes to the control. This event takes place after all regular Post-back events have taken place. This event takes place before saving ViewState, so any changes made here are saved.
9. SaveControlState: Saves the current control state to ViewState. After this stage, any changes to the control state are lost. To use this method, the control must call the Page.RegisterRequiresControlState method in the OnInit method of the control.
10. SaveViewState: Saves the current data state of the control to ViewState. After this stage, any changes to the control data are lost.
11. Render: Generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display this control at the browser. In this stage, any changes to the control are not persisted into ViewState.
12. Dispose: Accepts cleanup code. Releases any unman-aged resources in this stage. Unmanaged resources are resources that are not handled by the .NET common language runtime, such as file handles and database connections.
13. UnLoad

Application State in ASP.NET

Application state is used to store data on the application machine. It works as a global variable in other programming languages. Application variable is an object that is shared by the multiple sessions. We can use application variable within page, HttpHandler and Global.asax.

When request a page from client machine, an instance will create at application machine by the help of HttpApplicationState class. Entire application will have only one instance which is provided by HttpContext property named Application.

How to create Application state?

It's very easy to create application state in the ASP.NET application. I am going to take you to write simple application state program now.

Example 1:  In the Global.asax page

void Application_Start(object sender, EventArgs e)

    {

        // Code that runs on application startup

        Application["LoginID"] = "annathurai";

        Application["DomainName"] = "www.annathurai.com";

    }

Example 2:  Inside the .aspx page

protected void Page_Load(object sender, EventArgs e)

    {

// Code that runs on page load

        Application["LoginID"] = "annathurai";

        Application["DomainName"] = "www.annathurai.com";

    }

How to retrieve application state?

It's very easy to retrieve application state in the ASP.NET application. I am going to take you to write simple application state program now.

string loginID=string.Empty;

loginID = Application["LoginID"].ToString();

string loginID = string.Empty;

loginID = Application.GetKey(0);

We can retrieve all application variable on the currently running application's keys by using HttpApplicationState class.

HttpApplicationState appState = null;

appState = Application.Contents;



String[] StateVars = new String[appState.Count];

StateVars = appState.AllKeys;

How to remove application variable?

We have three methods to remove application variable from the ASP.NET application.



  Application.Remove("LoginID");

        Application.RemoveAt(0);

        Application.RemoveAll();

How to implement Synchronization in application state?

We can avoid deadlock occurrence while we updating application variable by multiple users with help of Lock() and UnLock().

        Application.Lock();
        Application["LoginID"] = "annathurai";
        Application["Domain"] = "www.annathurai.com";
        Application.UnLock();

Advantages of application state:

  •           Application object memory relased when we removed.
  •           Multi user can able to access application variable.
  •           To avoid deadlock or conflict we should use Lock and Unlock when we use write or update in the application object.
  •           Other application can't access this application values.

Disadvantages of application state:
  •           Application variable will exists until exit our application.
  •           If we do not have Lock() and Unlock, deadlock will occur.
  •           Its gloable variable so anyone can access within this application.