Wednesday, October 9, 2019

what is LOCK and Monitor

Lock:


When working with a multithreading application it is very important for developers to handle multiple threads for a critical section of code.

Monitor and lock is the way to provide thread safety in a multithreaded application in C#. Both provide a mechanism to ensure that only one thread is executing code at the same time to avoid any functional breaking of code.



C# Lock keyword ensures that one thread is executing a piece of code at one time. The lock keyword ensures that one thread does not enter a critical section of code while another thread is in that critical section.

Lock is a keyword shortcut for acquiring a lock for the piece of code for only one thread.


Monitor


Monitor provides a mechanism that synchronizes access to objects. It can be done by acquiring a significant lock so that only one thread can enter in a given piece of code at one time. Monitor is no different from lock but the monitor class provides more control over the synchronization of various threads trying to access the same lock of code.

Using a monitor it can be ensured that no other thread is allowed to access a section of application code being executed by the lock owner, unless the other thread is executing the code using a different locked object.

The Monitor class has the following methods for the synchronize access to a region of code by taking and releasing a lock,
  • Monitor.Enter 
  • Monitor.TryEnter
  • Monitor.Exit.
Monitor locks objects (that is, reference types), not value types. While you can pass a value type to Enter and Exit, it is boxed separately for each call.

Thread

What is threading.


To define Threading in a one line, means parallel work or code execution. To perform any multiple task simultaneously means Threading.

For example executing Microsoft PPTX and Excel simultaneously in a desktop, laptop or any device is known as Threading.

Work or a code task is always been executed in a two ways i.e. Synchronous or Asynchronous way.


Synchronous way means where work multiple jobs are executed one after the other. Here Work 2 have to wait till Work 1 is completed same way the others.

Asynchronous:

Asynchronous means multiple work has been executed simultaneously like doing multitask at a same time.



For creating threading application there some important methods which used regularly for implementing threading.

1 : Thread Join

2 : Thread Sleep

3 : Thread Abort


Thread Join:


Thread.Join() make thread to finish its work or makes other thread to halt until it finishes work. Join method when attached to any thread, it makes that thread to execute first and halts other threads. Now on the same we will see a simple example where we apply Join method to thread.


Use of Thread Sleep:


Thread.Sleep a method used to suspend current thread for a specific interval of time. Time can be specified in milliseconds or Timespan. While in a Sleep mode a method does not consumes any CPU resources so indirectly it save memory for other thread processes.

On the same we will create a simple example where in the for loop while printing output we will make a thread to sleep for 4000 milliseconds i.e. 4 secs for per print and total we are going to print 6 outputs. To count it properly we have used .NET Diagnostics namespace which allows us to use Stopwatch and TimeSpan to count elapsedTime.



Use of Thread Abort

As name implies "Abort" so same way Thread.Abort helps to end or abort any thread to process it further. It raises ThreadAbortException in the thread for process of termination.


Types of Threads in C#

here are two types of Thread in Csharp i.e.
 1. Foreground Thread 
 2. Background Thread


Foreground Thread

As we know that Main method is also runs on single thread, So in a Main method when we attach any other method to a thread it means we are making a multithread application. Foreground threads are those threads which keeps running until it finishes his work even if the Main method thread quits its process. To make you understand more better let me show you. Lifespan of foreground threads does not depends on main thread.



Background Thread


Background thread is just opposite of foreground thread here background thread quits its job when main thread quits. Here lifespan of background threads depends on main thread. In order to implement background thread in a program we need to set property called IsBackground to true.





A property of type System.Threading.ThreadState, used to get the value containing the state of the thread.

Start()

Starts the execution of the thread.

Abort() 

Allows the current thread to stop the execution of the thread permanently.

Suspend() 

Pauses the execution of the thread temporarily.

Resume() 

Resumes the execution of a suspended thread.

Join() 


Make the current thread wait for another thread to finish.








Monday, October 7, 2019

server.transfer and response.redirect


Server.Transfer                                    Response.Redirect

Redirection Redirection is done by the server. Redirection is done by the browser client.

Browser URL Does not change.                 Changes to the redirected target page.

When to use Redirect between pages of the same server. Redirect between pages on different server and domain.

Response.redirected:

We can bookmark the page because the full address is shown in a browser URL.
An extra round trip happens to the server.
It is used in HTML, ASP and ASP.Net pages to navigate from one page to another.

server.transfer:

We cannot bookmark the page because the full address is not shown in a browser URL.
An extra round trip does not happen to the server; because of this it saves server resources.
It is only used to navigate within an ASP or ASP.Net page, not within HTML pages.


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

Response.Redirect(URL,true) vsResponse.Redirect(URL,false) ?
Response.Redirect(URL,false): Client is redirected to a new page and the current page on the server will keep processing ahead.

Response.Redirect(URL,true): Client is redirected to a new page but the processing of the current page is aborted.


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







Saturday, September 7, 2019

IIS -InterNet Information Service

Internet Information Server:



Internet Information Server (IIS) is one of the most popular web servers from Microsoft that is used to host and provide Internet-based services to ASP.NET and ASP Web applications. A web server is responsible for providing a response to requests that come from users. When a request comes from client to server IIS takes that request from users and process it and send response back to users.


Internet Information Server (IIS) has it's own ASP.NET Process Engine to handle the ASP.NET request. The way you configure an ASP.NET application depends on what version of IIS the application is running on.



Application Pooling:


Application Pools are logical groupings of web applications that will execute in a common process, thereby allowing greater granularity of which programs are grouped together in a single process. For instance, if you wanted every Web Application to execute in a separate process, you simply create an Application Pool for each application. The Application Pool is the heart of a website. Application Pools enable us to isolate our Web Application for better security, reliability and availability.



Application Pool




The worker process serves as the process boundary that separates each Application Pool so that when a worker process or application is having an issue or recycles, other applications or worker processes are not affected.



Web Garden and Web Farmimg:

A Web Garden is a site configured to run within multiple processes on a single server. You can still have multiple servers configured in a web farm, but the Web Garden reflects the configuration of a specific individual server. Now I am explaining how to deploy a Web Site on IIS.



Advantage of Application Pool
  1. If we deploy an application in one worker process and it is running and another Application Pool's Web Application is also running and if it has any other problem then it will not be affected by other Application Pool's Web Application.
  2. Deploying an applications to multiple Application Pools enable us to achieve the degree of application isolation that we need, in terms of availability and security.



Web Farm

This is the case where you have only one web server and multiple clients requesting for resources from the same server. But when are is huge amount of incoming traffic for your web sites, one standalone server is not sufficient to process the request. You may need to use multiple servers to host the application and divide the traffic among them. This is called “Web Farm”. So when you are hosting your single web site on multiple web servers over load balancer is called “Web Farm”. The below diagram shows the overall representation of Web Farms.

Web Farms


Web garden

Just to recall, when we are talking about requesting processing within IIS, Worker Process (w3wp.exe) takes care of all of these. Worker Process runs the ASP.NET application in IIS. All the ASP.NET functionality inside IIS runs under the scope of worker process. Worker Process is responsible for handling all kinds of request, response, session data, cache data. Application Pool is the container of worker process. Application pool is used to separate sets of IIS worker processes and enables a better security, reliability, and availability for any web application.
apppools

Now, by default, each and every Application pool contains a single worker process. Application which contains the multiple worker process is called “Web Garden”.










compare Get and Post

 GETPOST
BACK button/ReloadHarmlessData will be re-submitted (the browser should alert the user that the data are about to be re-submitted)
BookmarkedCan be bookmarkedCannot be bookmarked
CachedCan be cachedNot cached
Encoding typeapplication/x-www-form-urlencodedapplication/x-www-form-urlencoded or multipart/form-data. Use multipart encoding for binary data
HistoryParameters remain in browser historyParameters are not saved in browser history
Restrictions on data lengthYes, when sending data, the GET method adds the data to the URL; and the length of a URL is limited (maximum URL length is 2048 characters)No restrictions
Restrictions on data typeOnly ASCII characters allowedNo restrictions. Binary data is also allowed
SecurityGET is less secure compared to POST because data sent is part of the URL

Never use GET when sending passwords or other sensitive information!
POST is a little safer than GET because the parameters are not stored in browser history or in web server logs
VisibilityData is visible to everyone in the URLData is not displayed in the URL

Sunday, September 1, 2019

IS vs AS Operators in C#

is Operator:

The ‘is’ operator in C# is used to check the object type and it returns a bool value: true if the object is the same type and false if not.

For null objects, it returns false.

In other words, The “is” operator is used to check whether the run-time type of an object is compatible with a given type or not.



as Operator:

The ‘as‘ operator does the same job of ‘is‘ operator but the difference is instead of bool,
it returns the object if they are compatible to that type, else it returns null. In otherwords,
The ‘as‘ operator is used to perform conversions between compatible types.

Monday, August 12, 2019

Page Life Cycle In ASP.NET

ASP.NET Page Life Cycle

Preinit:

Check the IsPostBack property to determine whether this is the first time the page is being processed.
Create or re-create dynamic controls.
Set a master page dynamically.
Set the Theme property dynamically.


Note:

If the request is a postback then the values of the controls have not yet been restored from the view state.

If you set a control property at this stage, its value might be overwritten in the next event.


Init:

  1. This event fires after each control has been initialized.
  2. Each control's UniqueID is set and any skin settings have been applied.
  3. Use this event to read or initialize control properties.
  4. The "Init" event is fired first for the bottom-most control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself.

InitComplete:


Until now the viewstate values are not yet loaded, hence you can use this event to make changes to the view state that you want to ensure are persisted after the next postback.
Raised by the Page object.
Use this event for processing tasks that require all initialization to be complete.



OnPreLoad:


Loads ViewState: ViewState data are loaded to controls.
Loads Postback data: Postback data are now handed to the page controls.

Load:


This is the first place in the page lifecycle that all values are restored.

  1. Most code checks the value of IsPostBack to avoid unnecessarily resetting state.
  2. You may also call Validate and check the value of IsValid in this method.
  3. You can also create dynamic controls in this method.

Control PostBack Event(s):


  1. Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
  2. In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.
  3. This is just an example of a control event. Here it is the button click event that caused the postback.


LoadComplete:



  1. Raised at the end of the event-handling stage.
  2. Use this event for tasks that require that all other controls on the page be loaded.

OnPreRender:


  1. Allows final changes to the page or its control.
  2. This event takes place before saving ViewState, so any changes made here are saved.
  3. For example: After this event, you cannot change any property of a button or change any viewstate value.
  4. Each data bound control whose DataSourceID property is set calls its DataBind method.
  5. Use the event to make final changes to the contents of the page or its controls.

OnSaveStateComplete:


  1. Raised after view state and control state have been saved for the page and for all controls.
  2. Before this event occurs, ViewState has been saved for the page and for all controls.
  3. Any changes to the page or controls at this point will be ignored.
  4. Use this event perform tasks that require the view state to be saved, but that do not make any changes to controls.

Render Method:


  1. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.

UnLoad:


  1. This event is used for cleanup code.
  2. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object.









Example of Code Abstraction and Encapsulation

Encapsulation:

Encapsulation is a process of binding the data members and member functions into a single unit. In c#, class is the real time example for encapsulation because it will combine a various type of data members and member functions into a single unit.


If we define a class fields with properties, then the encapsulated class won’t allow us to access the fields directly, instead we need to use getter and setter functions to read or write a data based on our requirements.



Example:

Following is the example of defining an encapsulation class using properties with get and set accessors.

using System;
using System.Text;

namespace Tutlane
{
    class User
    {
        private string location;
        private string name;
        public string Location
        {
            get
            {
                return location;
            }
            set
            {
                location = value;
            }
        }
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            User u = new User();
            // set accessor will invoke
            u.Name = "Suresh Dasari";
            // set accessor will invoke
            u.Location = "Hyderabad";
            // get accessor will invoke
            Console.WriteLine("Name: " + u.Name);
            // get accessor will invoke
            Console.WriteLine("Location: " + u.Location);
            Console.WriteLine("\nPress Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}
If you observe above example, we defined a fields in encapsulated class using properties and we are able to manipulate field values using get and set accessors of properties.



Abstraction:


In c#, Abstraction is a principle of object oriented programming language (OOP) and it is used to hide the implementation details and display only essential features of the object.

In Abstraction, by using access modifiers we can hide the required details of object and expose only necessary methodsand properties through the reference of object.

In real time, laptop is the perfect example for abstraction in c#. A laptop which consists of many things such as processor, RAM, motherboard, LCD screen, camera, USB ports, battery, speakers, etc. To use it, we just need to know how to operate the laptop by switching it on, we don’t need to know how internally all the parts are working. Here, the laptop is an object which is designed to expose only required features by hiding its implementation details.

In object oriented programming, class is the perfect example for abstraction. In c#, we can create a class with required methodsproperties and we can expose only necessary methods and properties using access modifiers based on our requirements.

Following is the example of defining a class with required methodsproperties and exposing it by using access modifiers to achieve abstraction functionality.



public class Laptop
{
    private string brand;
    private string model;
    public string Brand
    {
        get { return brand; }
        set { brand = value; }
    }
    public string Model
    {
        get { return model; }
        set { model = value; }
    }
    public void LaptopDetails()
    {
        Console.WriteLine("Brand: " + Brand);
        Console.WriteLine("Model: " + Model);
    }
    public void LaptopKeyboard()
    {
        Console.WriteLine("Type using Keyword");
    }
    private void MotherBoardInfo()
    {
        Console.WriteLine("MotheBoard Information");
    }
    private void InternalProcessor()
    {
        Console.WriteLine("Processor Information");
    }
}



If you observe above code, we defined a Laptop class with required fieldsproperties and methods with publicprivate access modifiers to achieve an abstraction functionality by hiding and exposing some of methods and properties based on our requirements.





Here, the public modifier is used to allow a defined fieldsproperties and methods to access outside of the class and the private modifier is used to hide or restrict an access of required fieldsproperties and methods from the outside of class.

What is difference between Override and New KeyWord

As it shows the difference between new and override that override extends the method in derived class but new only hides the method of base class in derived class.


Friday, August 2, 2019

Reflection in C#

what is Reflection:

Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and type information at runtime.
In other words, reflection provides objects that encapsulate assemblies, modules and types.


It gives the below info at run time:
  • Assembly
  • Module
  • Enum
  • MethodInfo
  • ConstructorInfo
  • MemberInfo
  • ParameterInfo
  • Type
  • FieldInfo
  • EventInfo
  • PropertyInfo



Example:

  1.  int n = 45;  
  2.             //string n = "vineet";  
  3.             System.Type t = n.GetType();






Sunday, July 28, 2019

Why we used Method overriding?

Ans:

When we need to Extend the parent Class Method's behavior  with some modifications.

This is the situation where we inherit the class and override the methods which are required as per
our business requirement.


What is Webconfig, Appconfig, MachineConfig.

WebConfig:

It is a configuration file, which is used in web application and it can be an ASP.NET project or MVC project. Some project contains multiple web.config file inside the same project but with different folder. They have their unique benefits. You can create several web.config file in each folder with their unique benefits as per your project requirement.

It is used to store the application level configuration. Sometimes it inherits the setting from the machine.config. It parses at runtime, means if you make any changes then web application will load all the settings in the config file. You don’t need to create a web.config file because it is auto generated when you create a new web application. If you want to create a web.config manually you can create it.


Machine Config:

It is a special type of configuration file which creates into the OS when you install visual studio. This stores machine level configuration setting. Only one machine.config file exists into the system and it stores highest level of configuration settings.

Machine.config settings apply to all web applications which is residing on the server. The setting of machine.config can be overridden by web.config’s settings. If your system does not contain the machine.config then you cannot execute the application.


Path of Machine.config
    32-bit System

    %windir%\Microsoft.NET\Framework\[version]\config\machine.config

    64-bit System
    %windir%\Microsoft.NET\Framework64\[version]\config\machine.config.

    Appconfig:
It is also a special type of configuration file which is basically used with Windows Services, Windows application, Console Apps or it can be WPF application or any others.

It parses at compile time; it means if you edit the app.config when program is running, then you need to restart the application to reload the configuration setting into the program.

When you run the application which contains the app.config, at the time of compilation a copy of app.config with different name moves into build folder for running the application, So that's why we need to restart the program if any changes made in app.config.

It is not added auto when you create a project, to add this you need to go to solution explorer and choose Add New Item and choose “Application Configuration File”. Windows application always contains the App.config file into the project.