Garbage Collection in C#

The garbage collector serves as an automatic memory manager.

When you create any object in C#, CLR (common language runtime) allocates memory for the object from heap. This process is repeated for each newly created object, but there is a limitation to everything, Memory is not un-limited and we need to clean some used space in order to make room for new objects, Here, the concept of garbage collection is introduced, Garbage collector manages allocation and reclaiming of memory. GC (Garbage collector) makes a trip to the heap and collects all objects that are no longer used by the application and then makes them free from memory. When any process gets triggered, separate virtual space is assigned to that process, from a physical memory.


Virtual memory has three blocks:

• Free (empty space)

• Reserved (already allocated)

• Committed (This block is give-out to physical memory and not available for space allocation)


GC checks the below information to check if the object is live:

• It collects all handles of an object that are allocated by user code or by CLR

• Keeps track of static objects, as they are referenced to some other objects

• Use stack provided by stack walker and JIT


GC automatically starts operation on the following conditions:

1. When virtual memory is running out of space.

2. When allocated memory is suppressed acceptable threshold (when GC found if the survival rate 

    (living objects) is high, then it increases the threshold allocation).

3. When we call GC.Collect() method explicitly, as GC runs continuously, we actually do not need to call this method.


There are different ways to cleanup unmanaged resources:

• Implement IDisposable interface and Dispose method

• 'using' block is also used to clean unmanaged resources


Send data from javascript to ASP.NET MVC controller using URL

HTML


<input type="text" id="UserName" name="UserName" />
<input type="button" onclick="MyFunction()"value="Send" />

<div id="UpdateDiv"></div> 

---------------------------

Javascript

function MyFunction() {
    var data= {
        UserName: $('#UserName').val(),
    };
    $.ajax({
        url: "/Home/GetEmployer",
        type: "POST",
        dataType: "json",  
        data: JSON.stringify(data),
        success: function (mydata) {
            $("#UpdateDiv").html(mydata);
            history.pushState('', 'New URL: '+href, href); // This Code lets you to change url 
        });
        return false;
    }
}

-----------------------------

public JsonResult GetEmployer(string UserName)
{
    var employer = unit.Repository<Employer>().GetByID(id);
    return Json(employer, JsonRequestBehavior.AllowGet);
}

Authentication and Authorization in ASP.NET

Authentication and Authorization are two interrelated security concepts.
Authentication is knowing the identity of the user. For example, Alice logs in with her username and password, and the server uses the password to authenticate Alice. It prove genuineness.
Authorization is deciding whether a user is allowed to perform an action. For example, Alice has permission to get a resource but not create a resource.It is the process of granting approval or permission on resources.

Types of authentication and authorization in ASP.NET

There are three ways of doing authentication in ASP.NET:-
Windows authentication: - In this methodology ASP.NET web pages will use local windows users and groups to authenticate and authorize resources.
Forms Authentication: - This is a cookie based authentication where username and password are stored on client machines as cookie files or they are sent through URL for every request. Form-based authentication presents the user with an HTML-based Web page that prompts the user for credentials.
Passport authentication :- Passport authentication is based on the passport website provided
by the Microsoft .So when user logins with credentials it will be reached to the passport website ( i.e. hotmail,devhood,windows live etc) where authentication will happen. If Authentication is successful it will return a token to your website.  
None :- No Authentication provided. This is the default Authentication mode.

In the web.config file of your application, you can specify the Authentication mode as shown below : - 



ASP.NET allows two ways to authorize access to a given resources: -

. URL authorization
URL authorization maps users and roles to URLs in ASP.NET applications
. File authorization
File authorization validate the ACL (access control list) of the .aspx or .asmx handler file to determine whether a user should have access to the file.




SOAP Vs REST Services

REST stands for Representational State Transfer.
SOAP stands for Simple Object Access Protocol.
Only main difference is that How Client accesses our Service.
Normal WCF service runs on the SOAP format but when we create REST service then client can access your service in different architecture style like JSON.

REST uses4 HTTP methods to insert/delete/update/retrieve information which is below:
GET - Retrive a specific representation of a resource
PUT - Creates or updates a resource with the supplied representation
DELETE - Deletes the specified resource
POST - Submits data to be processed by the identified resource

WCF
1. It is also based on SOAP and return data in XML form.
2. It is the evolution of the web service(ASMX) and support various protocols like 3. TCP, HTTP,
    HTTPS, Named Pipes, MSMQ.
4. The main issue with WCF is, its tedious and extensive configuration.
5. It is not open source but can be consumed by any client that understands xml.
6. It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest
1. To use WCF as WCF Rest service you have to enable webHttpBindings.
2. It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
3. To enable other HTTP verbs you have to do some configuration in IIS to accept request of that
    particular verb on .svc files
4. Passing data through parameters using a WebGet needs configuration. The UriTemplate must be
    specified
5. It support XML, JSON and ATOM data format.

Web Service is an abstract term encompassing a large variety of data providers for distributed systems. Perhaps you are referring to ASMX web services, which can still be found in the wild but aren't really widely used in new development these days.

WCF Service is Microsoft's implementation of SOAP. There are others implementations or you could roll your own (not recommended).
SOAP is a kind of stateful, session-based, message-based web service. It's good if your service is designed as a set of complex actions.

REST is a stateless, sessionless, resource-based web service. It's good if your service is designed to access data and perform simple CRUD operations on it. SOAP and REST are mutually exclusive. A service cannot be both. There are ways to manipulate vanilla WCF to make is RESTful but these techniques are becoming deprecated. If you want to implement a RESTful web service there are two main choices in the Microsoft world: WCF Data Services and ASP.NET Web API..

SOAP

Without getting too deep into its history, Simple Object Access Protocol (SOAP) is a Microsoft invented protocol that was meant to create a structured way of sending and receiving data over the wire.  This protocol is one of the main foundations of WCF and utilizes XML to create services with typed data and methods.  In the typical scenario, a Web Services Description Language (WSDL) file is created from service code and is provided, usually through a static URL, to the client.  The client uses this WSDL file to understand what methods are available on the service, how to call them, and what the classes of the returned objects will be.  This is a very action-driven model that focuses on what actions a service is a capable of performing.

REST

REpresentational State Transfer (REST) is not a protocol, but an architecture and design pattern for building and calling web services.  This is the pattern that Web API was designed to utilize to build web services.  It is a very resource-driven architecture that exposes endpoints based on objects and not functions.  RESTful services also make use of the standard HTTP methods and constructs to exchange data; using GET, POST, PUT, DELETE, and sometimes PATCH a caller can denote which action to perform on the object being accessed at the requested endpoint.  Query parameters and content in the body of the request can also provide ways to pass parameters to the service.

Sealed Class in C#

Sealed Class
It is a type of class that cannot be inherited.

The following ar some key points:
  • A Sealed class is created by using the sealed keyword
  • The Access modifiers are not applied upon the sealed class
  • To access the members of the sealed we need to create the object of that class
  • To restrict the class from being inherited, the sealed keyword is used
Example :
     public sealed class CustoMerDetails 
    { 
        public string AccountIno() 
        { 
            return "Vithal Wadje"; 
        } 
    } 

In the preceding example, the class is declared using the sealed keyword so that this class and the class member cannot be inherited

Private Vs sealed class
Private Sealed
Private classes cannot be declared directly inside the namespace. Sealed classes can be declared directly inside the namespace.
We cannot create an instance of a private class. We can create the instance of sealed class.
Private Class members are only accessible within a declared class. Sealed class members are accessible outside the class through object.

State Management in ASP.NET

What does stateless actually mean?
Stateless means, whenever we visit a website, our browser communicates with the respective server depending on our requested functionality or the request. The browser communicates with the respective server using the HTTP or HTTPs protocol.

What's next or what will happen when we visit that website again after closing our web browser?
In this case HTTP/HTTPs doesn't remember what website or URL we visited or in other words we can say it doesn't hold the state of a previous website that we visited before closing our browser, that is called stateless. So our browsers are stateless.


Client Side

Whenever we use Client-Side State Management, the state related information will directly get stored on the client-side. That specific information will travel back and communicate with every request generated by the user then afterwards provides responses after server-side communication.

Client side state management techniques are:
  • View State
  • Hidden field
  • Cookies
  • Control State
  • Query Strings

Server Side

Server-Side State Management is different from Client-Side State Management but the operations and working is somewhat the same in functionality. In Server-Side State Management all the information is stored in the user memory. Due to this functionality there is more secure domains at the server side in comparison to Client-Side State Management.

Server side state management techniques are:
  • Session State
  • Application State

Globalization and Localization

Globalization refers to formatting data in formats relevant for the current culture setting. Globalization is the process of designing and developing applications that function for multiple cultures.
example:
a) Consider this tag in Web.Config file.
           
    It would cause the dates to be displayed in French for the web page of
    the folder where this Web.Config file is located.
b) CultureInfo d=new CultureInfo("de-DE");
    Response.Write(DateTime.Now.ToString("D",d);
    It would display date in long format using German culture
------------------------------------------------------------------------------------------------------------
Localization is the process of customizing your application for a given culture and local. Localization refers to retrieving and displaying appropriately localized data based on the culture.
It can be done by using the Resource files.
example:
we have 2 resource files:
a)default.aspx.fr-FR.resx
b)default.aspx.en-US.resx



Resource Files
A resource file is an XML file that contains the strings that you want to translate into different languages or paths to images.
The resource file contains key/value pairs. Each pair is an individual resource. Key names are not case sensitive.
e.g. A resource file might contain a resource with the key Button1 and the value Submit

Resource files in ASP. NET have an .resx extension. At run time, the .resx file is compiled into an assembly.


Global Resource Files
You create a global resource file by putting it in the reserved folder App_GlobalResources at the root of the application.

Any .resx file that is in the App_GlobalResources folder has global scope.


Local Resource Files
A local resources file is one that applies to only one ASP. NET page or user control (an ASP. NET file that has a file-name extension of .aspx, .ascx, or .master).

Logged Uer Details using C#




string user = this.Request.ServerVariables["LOGON_USER"];

'LOGON_USER'   -Returns the Windows account that the user is logged into



To get more details, Follow this link
http://www.w3schools.com/asp/coll_servervariables.asp


Set default page in Asp.Net MVC

In the project ->  App_Start ->  RouteConfig.cs 


public static void RegisterRoutes(RouteCollection routes)
{
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                   defaults: new { controller = "Home", action = "Register" id = UrlParameter.Optional }
            );
}

What is global.asax

Global.asax is an optional file which is used to handling higher level application events such as Application_Start, Application_End, Session_Start, Session_End etc. It is also popularly known as ASP.NET Application File. This file resides in the root directory of an ASP.NET-based application.