Sunday, March 24, 2019

State management


SESSION MODES IN ASP.NET:

ASP.NET provides various Session Modes for storage of Session Data. Here is the different session modes available in ASP.NET.
  • InProc mode: This is the default Session State modes which store the session data in memory on the web server.

  • StateServer (Out-Proc) mode: This stores the session data in separate memory called the ASP.NET Service. This mode ensures that the session data preserves when the Application Process restarts.

  • SQL Server mode: In this mode session data is stored in the SQL Server Database. This mode also ensures that the session data preserves when the Web Application restarted. Also, this mode makes session data available to several Web Server.

  • Custom mode: This mode enables you to specify the custom storage option.
  • Off mode: This mode disables the session state. This increases the performance of the application.



Load Balance Example in Session:

InProcMode:


OutProc Mode:




ViewState:

The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. When an ASP.NET page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. If the data is too long for a single field, then ASP.NET performs view state chunking (new in ASP.NET 2.0) to split it across multiple hidden fields. The following code sample demonstrates how view state adds data as a hidden form within a Web page’s HTML:



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

Encrypting of the View State: You can enable view state encryption to make it more difficult for attackers and malicious users to directly read view state information. Though this adds processing overhead to the Web server, it supports in storing confidential information in view state. To configure view state encryption for an application does the following:


Cookies:

Controlling the Cookie Scope: By default, browsers won’t send a cookie to a Web site with a different hostname. You can control a cookie’s scope to either limit the scope to a specific folder on the Web server or expand the scope to any server in a domain. To limit the scope of a cookie to a folder, set the Path property, as the following example demonstrates:

Example:

Response.Cookies["lastVisit"].Path = "/Application1"; 


Through this the scope is limited to the “/Application1” folder that is the browser submits the cookie to any page with in this folder and not to pages in other folders even if the folder is in the same server. We can expand the scope to a particular domain using the following statement:
Example:
Response.Cookies[“lastVisit”].Domain = “Contoso”;

Storing Multiple Values in a Cookie:
Though it depends on the browser, you typically can’t store more than 20 cookies per site, and each cookie can be a maximum of 4 KB in length. To work around the 20-cookie limit, you can store multiple values in a cookie, as the following code demonstrates:
Example:

Response.Cookies["info"]["visit"].Value = DateTime.Now.ToString();
Response.Cookies["info"]["firstName"].Value = "Tony";
Response.Cookies["info"]["border"].Value = "blue";
Response.Cookies["info"].Expires = DateTime.Now.AddDays(1);


https://www.c-sharpcorner.com/UploadFile/de41d6/view-state-vs-session-state-vs-application-state/



what is global.aspx file

The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level events raised by ASP.NET or by HttpModules.





The Global.asax file resides in the root directory of an ASP.NET-based application. The Global.asax file is parsed and dynamically compiled by ASP.NET.

The Global.asax file itself is configured so that any direct URL request for it is automatically rejected; external users cannot download or view the code written within it.

The Global.asax file does not need recompilation if no changes have been made to it. There can be only one Global.asax file per application and it should be located in the application's root directory only.
The Global.asax contains two types of events those are

Events which are fired for every request

Events which are not fired for every request



Events which are fired for every request

Application_BeginRequest() – This event raised at the start of every request for the web application.

Application_AuthenticateRequest – This event rose just before the user credentials are authenticated. We can specify our own authentication logic here to provide custom authentication.

Application_AuthorizeRequest() – This event raised after successful completion of authentication with user’s credentials. This event is used to determine user permissions. You can use this method to give authorization rights to user.

Application_ResolveRequestCache() – This event raised after completion of an authorization request and this event used in conjunction with output caching. With output caching, the rendered HTML of a page is reused without executing its code.

Application_AcquireRequestState() – This event raised just before session-specific data is retrieved for the client and is used to populate Session Collection for current request.

Application_PreRequestHandlerExecute() – This event called before the appropriate HTTP handler executes the request.

Application_PostRequestHandlerExecute() – This event called just after the request is handled by its appropriate HTTP handler.

Application_ReleaseRequestState() – This event raised when session specific information is about to serialized from the session collection.

Application_UpdateRequestCache() – This event raised just before information is added to output cache of the page.
       
Application_EndRequest() – This event raised at the end of each request right before the objects released.

Now we will see

Events which are not fired for every request

Application_Start() – This event raised when the application starts up and application domain is created.

Session_Start() – This event raised for each time a new session begins, This is a good place to put code that is session-specific.

Application_Error() – This event raised whenever an unhandled exception occurs in the application. This provides an opportunity to implement generic application-wide error handling. 

Session_End() – This event called when session of user ends.

Application_End() – This event raised just before when web application ends.

Application_Disposed() – This event fired after the web application is destroyed and this event is used to reclaim the memory it occupies.

Now we will see all these events with simple example in Global.asax

First Open visual Studio ---> Create New Website after that right click on Solution explorer and select new item

What is Caching and Types

What is Cache.

Cache is Technique of storing  data/ information in a memory. so that when next time same data/information needed. it could be directly retrieved from the memory instead of being generated by the application.


Three type of caching.

1.Data cacheing

2. page Caching

3. Fragmentation caching



Saturday, March 23, 2019

What is Event


Events and delegate work together. An event is a reference to a delegate i.e. when an event is raised, a delegate is called. In C# terms, events are a special form of delegates.

What is Delegate and Types with Examplea



A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.

Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.


Types of Delegates.

1. Single cast delegate

2. Multi cast Delegate

3. Generic Delegate

  •   Action
  •   Func
  •   Predicate


Why Delegates?

Delegates are used in the following cases:

Delegates can be used to handle(call/invoke) multiple methods on a single event.
Delegates can be used to define callback(asynchronous) methods.
Delegates can be used for decoupling and implementing generic behaviors.
Delegates can be invoked method at runtime.
Delegates can be used in LINQ for parsing the ExpressionTree.
Delegates can be used in different Design Pattern.

==============================================================

Func, Action and Predicate are generic inbuilt delegates present in System namespace.

All three can be used with method, anonymous method and lambda expression.

Func can contains 0 to 16 input parameters and must have one return type.

Action can contain 1 to 16 input parameters and does not have any return type.

Predicate delegate should satisfy some criteria of method and must have one input parameter and one Boolean return type either true or false.

Input parameters of custom delegates is fixed but Func and Actions input parameter is variable from 0 to 16 and 1 to 16 respectively.



Example:

    public delegate void DelTest(string str);

    public class SampleA
    {
        public void SampleAA(string st)
        {
            Console.WriteLine(st);
        }
        public void MethodB(string stt)
        {
            Console.WriteLine(stt);
        }

        public static void SampleC()
        {
            Console.WriteLine("MethodC");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            SampleA a1 = new SampleA();
           // DelTest DelA = SampleA.SampleC;

            DelTest d1 = new DelTest(a1.SampleAA);// Single Cast
            d1 += new DelTest(a1.MethodB);//Multicast
            d1("Mike");
            Console.ReadKey();
        }
    }


Where to use

A Delegate can be used in various ways depending on the requirements of the project. The following are the lists of areas where a delegate can be used to provide better output and enhance the performance of the application.

Method Invocation (using delegate instance)
Event Handling using delegate
Callback and asynchronous implementation
Multiple method calls using Multicast delegate


Conclusion

A normal delegate or a Multicast delegate is a very powerful feature in C# and it can be used by developers in various scenarios for more flexibility and a better way to improve the performance of the application.


Saturday, March 16, 2019

Default Access Modifier

                     | Default   | Permitted declared accessibilities
------------------------------------------------------------------
namespace            | public    | none (always implicitly public)

enum                 | public    | none (always implicitly public)

interface            | public    | none

class                | Internal   | All¹

struct               | private   | public, internal, private²

delegate             | private   | All¹

constructor          | private   | All¹

interface member     | public    | none (always implicitly public)

method               | private   | All¹

field                | private   | All¹

user-defined operator| none      | public (must be declared public)

Class Default   - Internal  use below link
https://www.c-sharpcorner.com/UploadFile/84c85b/default-scope-of-a-C-Sharp-class/

What is constant and Readonly

 What is Difference Between constant and readonly.

Ans:

const
  • They can not be declared as static (they are implicitly static)
  • The value of constant is evaluated at compile time
  • constants are initialized at declaration only
readonly
  • They can be either instance-level or static
  • The value is evaluated at run time
  • readonly can be initialized in declaration or by code in the constructor

imp

const: Can't be changed anywhere.
readonly: This value can only be changed in the constructor. Can't be changed in normal functions



.NET Framework and Architecture


What is .Net Framework.

It is a platform to develop application.

============================================================

Difference between Visual Studio and VS.NET

Visual StudioVisual Studio .Net
It is object basedIt is object oriented
Internet based application
- Web Application
- Web services
- Internet enable application
- Third party API
- Peer to peer Application
All developing facilities in internet based application
Poor error handling Exception/ErrorAdvance error handler and debugger
Memory Management System Level TaskMemory Management Application Domain with help of GC (Garbage Collector)
DLL HELLVS .NET has solved DLL HELL Problem


What is DLL Hell:


I have two applications, A and B installed, both of them installed on my PC.
Both of these applications use the same shared assembly SharedApp.dll.

Somehow, I have the latest version of SharedApp.dll installed on my PC.
The latest SharedApp.dll replaces the existing DLL, that App A was also using earlier.
Now App B works fine whereas App A doesn't work properly due to the newer SharedApp.dll.



DLLHELL1.jpg





Solution of Dll-Hell Problem 

This problem of dynamic link library (.dll) is resolved through Versioning.



versin mmmmm.GIF



What is GAC(Global Assembly Cache):


The GAC implements the feature of shared library where different applications reuse the code placed in the files located in a common folder. 



What is Assembly:


An assembly is a file that is automatically generated by the compiler upon successful compilation of every .NET application. It can be either a Dynamic Link Library or an executable file.

it is Unit of Deployment. like EXE or DLL.

==============================================================
What is Difference between EXE and DLL

Ans:

1.EXE is an extension used for executable files while DLL is the extension for a dynamic link library.
2.An EXE file can be run independently while a DLL is used by other applications.
3.An EXE file defines an entry point while a DLL does not.
4.A DLL file can be reused by other applications while an EXE cannot.
5.A DLL would share the same process and memory space of the calling application while an EXE creates its separate process and memory space.






Types of Assembly:

  1. private
  2. shared (Public assembly)
  3. sattelite Assembly 

Private Assembly
 
Private assembly requires us to copy separately in all application folders where we want to use that assembly’s functionalities; without copying we cannot access the private assembly features and power. Private assembly means every time we have one, we exclusively copy into the BIN folder of each application folder.



2. Shared Assembly

Assemblies that can be used in more than one project are known to be a shared assembly. Shared assemblies are generally installed in the GAC. Assemblies that are installed in the GAC are made available to all the .Net applications on that machine.

However there are two more types of assemblies in .Net, Satellite Assembly and Shared Assembly. 


Satellite Assembly
 
Satellite assemblies are used for deploying language and culture-specific resources for an application.


GAC:

GAC stands for Global Assembly Cache. It is a memory that is used to store the assemblies that are meant to be used by various applications. 


 











Saturday, March 9, 2019

what is Structure in c#

=>Structure is a value type data type.

=>It helps you to make single variable to hold related data in different data types.

Points to Remember:

Structures can have methods, fields, indexers, properties, operator methods, and events.

Structures can have defined constructors, but not destruction. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and cannot be changed.

Unlike classes, structures cannot inherit other structures or classes.

Structures cannot be used as a base for other structures or classes.

A structure can implement one or more interfaces.

Structure members cannot be specified as abstract, virtual, or protected.

When you create a struct object using the New operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the New operator.

If the New operator is not used, the fields remain unassigned and the object cannot be used until all the fields are initialized.



*** If you want to initialize fields inside the struct it get compile error.


  1. struct MyStruct {  
  2.     int x = 20; // Error its not possible to initialize  
  3.     int y = 20; // Error its not possible to initialize  
  4. }  



Class versus Structure
  • Classes and Structures have the following basic differences
  • classes are reference types and structs are value types
  • structures do not support inheritance
  • structures cannot have default constructor


Example:

  struct Books
    {
        public string Tittle;
        public string BookName;
        public int bookId;
    }

    class Program
    {
     
        static void Main(string[] args)
        {
            Books b1;
            b1.Tittle = "XYZ";
            b1.BookName = "Name";
            b1.bookId = 1;


            Books obj = new Books();
            obj.Tittle = "Alok";
            Console.WriteLine(b1.BookName);
            Console.ReadLine();


        }
    }