What happens when we type a URL in the browser (In Depth)?

If you are reading this then i would recommend to read this  article first for a clear visibility that what we will understand in depth 🙂


Have you ever wondered, precisely – 

  • What happens in the background when we type a URL in the browser?
  • How does a web page life-cycle sequence work?
  • How browser knows, where to send request for the requested page?
  • What happens on the Web Server when a request for a web page comes in?
  • How does the Web server handle the incoming request?
  • How is the HTML that is emitted to the client generated?
  • How browser renders the page on the screen?
  • Etc…

If you are also looking answers of above mentioned questions then this article is definitely for you. In this article, we will take a deeper look at the sequence of events that take place when we visit a ASP.NET page URL –

  1. URL is typed in address bar of the browser
  2. The browser parses the URL to find the protocol, host, port, and path. Ex- http://www.jogendras.com/about will be parsed as-
  3. Browser checks cache, if requested object is in cache and is fresh then return response from cache.
  4. The browser looks up the IP address for the entered domain name.  When we want to connect to http://www.google.com, we actually want to reach out to a server where web application is hosted. One such server is having an IP address of XX.XXX.XXX.XX. Now, if we type http://XX.XXX.XXX.XX in the browser, this will take us to http://www.google.com itself. Which means, http://www.google.com and http://XX.XXX.XXX.XX are nothing but same stuff. But, it is not so. 
    As google has multiple servers in multiple locations to cater to the huge volume of requests. Thus we should let application decide which server is best suited to our needs. Using http://www.google.com does the job for us. When we type http://www.google.com DNS services comes into play and resolves the URL to a proper IP address. The DNS lookup proceeds as follows-

    • Browser cache – The browser maintain cache of DNS records for some time. So, this is the first place to resolve DNS queries
    • OS cache – If browser doesn’t contain the record in its cache, it makes a system call to underlying Operating System to fetch the record as OS also maintains a cache of recent DNS queries.
    • Router cache – If above steps fail to get a DNS record, the search continues to your router which has its own cache
    • ISP DNS cache – If above also fails then search moves on to ISP’s DNS server, first, it tries in its cache if not found then ISP’s DNS recursive search comes into the picture.
    • Recursive search – If everything fails then recursive search begins from the root level namesever.  For the DNS enthusiasts – here is a great guide worth reading
  5. Browser asks OS for entered domain’s IP address
  6. OS makes a DNS lookup and replies the IP address to the browser


Coming Soon….. 🙂


Programming is Easy…

What happens when we type a URL in the browser?

If you are curious to know what happens in the background when we type a URL in the browser then this article is definitely for you. Below are the sequence of events that occurs when we enter a URL in the browser’s address bar-

  1. You type the URL into address bar in your preferred browser
  2. The browser parses the URL to find the protocol, host, port, and path.
  3. Browser checks cache, if requested object is in cache and is fresh, skip to #15
  4. Browser asks OS for entered domain’s IP address
  5. OS makes a DNS lookup and replies the IP address to the browser
  6. Browser opens a TCP connection to the server
  7. When a connection is open, browser sends the HTTP request to the host
  8. The host forwards the request to the server software (most often Apache, IIS) configured to listen on the specified port
  9. Server handles the incoming request i.e server inspects the request (most often only the path), and launches the server plugin needed to handle the request (corresponding to the server language you use, PHP, Java, .NET, Python?)
  10. The server plugin gets access to the full request, and starts to prepare a HTTP response.
  11. Server sends the HTTP response back to the browser
  12. Browser receives HTTP response and may close the TCP connection, or reuse it for another request
  13. Browser checks if the response is a redirect or a conditional response (3xx result status codes), authorization request (401), error (4xx and 5xx), etc.; these are handled differently from normal responses (2xx)
  14. If cache-able, response is stored in cache
  15. Browser decodes response (e.g. if it’s gzipped)
  16. Browser determines what to do with response (e.g. is it a HTML page, is it an image, is it a sound clip?) Browsers often use the MIME-type to determine what default action to do when a resource is fetched.
  17. If response is HTML then browser parses the HTML. A DOM tree is built out of the response HTML. New requests are made to the server for each new resource that is found in the HTML source (typically images, style sheets, and JavaScript files). Go back to step#7 and repeat for each resource. StyleSheets are parsed, and the rendering information in each gets attached to the matching node in the DOM tree. Javascript is parsed and executed, and DOM nodes are moved and style information is updated accordingly. The browser renders the page on the screen according to the DOM tree and the style information for each node
  18. Browser renders response, or offers a download dialog for unrecognized types


Hopefully this gives you a better idea of how a URL get proceeds 🙂


Programming is Easy…

Does Session use cookies in Asp.Net?

It’s very confusing for many developers that session use cookies or not, and also a interesting interview question for .net developer 🙂 Let’s understand the relation between session and cookies-

Does session use cookies? Answer is- YES and NO.

One more confusion?

While using session in the application we have two things which are SessionID which is used to uniquely identify the session variables and Session Value which is the actual data stored in the session variables.

As session is a server side and cookies are client side state management techniques, so session actual data always stored on the server memory by default. The following list describes the available session storage modes-

  • InProc mode, which stores session state in memory on the Web server. This is the default.
  • StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  • SQLServer mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  • Custom mode, which enables you to specify a custom storage provider.
  • Off mode, which disables session state.

I hope it’s clear that session data is stored on the server and has no relationship with the cookies.

Now let’s understand the session keys storage types-





Session and cookies relationship are limited to only session keys not session value.


Session use cookies – Yes :  By default Session key is stored in an HTTP  non-persistent cookie that the client sends to the server (and server to client) on each request/responses. The server can then read the key from the cookie and re-inflate the server session state.

If we will try to run below code after disabled the cookies then it will not work that proves that session use the cookies.

Session use cookies – No : There is the possibility that browser does not support cookie or disabled, then asp.net can not create a cookie to store session keys. ASP.NET offers an alternative in the form of cookieless sessions. You can configure your application to store session keys not in a cookie, but in the URLs. This can be done by setting cookieless=”true” in the web.config file  as-

<sessionstate cookieless=”true” />



Programming is Easy…

Thread Locking in C#

Thread locking is used to ensure that only one thread can enter particular sections of code at a time…

Main exclusive locking constructs are lock , Mutex and nonexclusive locking constructs is semaphores.

class ThreadUnsafe
  static int _val1 = 1, _val2 = 1;

  static void Go()
    if (_val2 != 0) Console.WriteLine (_val1 / _val2);
    _val2 = 0;

This class is not thread-safe: if Go was called by two threads simultaneously, it would be possible to get a division-by-zero error, because _val2 could be set to zero in one thread right as the other thread was in between executing the if statement and Console.WriteLine.

Here’s how lock can fix the problem:

class ThreadSafe
  static readonly object _locker = new object();
  static int _val1, _val2;

  static void Go()
    lock (<span style="color: #ff6600;"><strong>_locker</strong></span>)
      if (_val2 != 0) Console.WriteLine (_val1 / _val2);
      _val2 = 0;

Only one thread can lock the synchronizing object (in this case, _locker) at a time, and any contending threads are blocked until the lock is released. If more than one thread contends the lock, they are queued on a “ready queue” and granted the lock on a first-come, first-served basis






All about Threading in C#

  • Threading means parallel code execution.
  • C# supports parallel execution of code through multi-threading.
  • Threading helps us to executing one or more tasks in a parallel way or asynchronous way.

.Net applications like Console, WPF or Windows starts in a single thread created automatically by the CLR and operating system (i.e main thread) and we can make multithreaded by creating additional threads.

  • Thread can not restart once completed.
  • A thread, while blocked, doesn’t consume CPU resources.


How Threading Works ?

Multithreading is managed internally by a thread scheduler, a function the CLR typically delegates to the operating system. A thread scheduler ensures all active threads are allocated appropriate execution time, and that threads that are waiting or blocked (for instance, on an exclusive lock or on user input)  do not consume CPU time.

  • On a single-processor computer, a thread scheduler performs time-slicing — rapidly switching execution between each of the active threads.
  • On a multi-processor computer, multithreading is implemented with a mixture of time-slicing and genuine concurrency, where different threads run code simultaneously on different CPUs. It’s almost certain there will still be some time-slicing, because of the operating system’s need to service its own threads — as well as those of other applications.

Threads vs Processes-

A thread is analogous to the operating system process in which your application runs. Just as processes run in parallel on a computer, threads run in parallel within a single process. Processes are fully isolated from each other; threads have just a limited degree of isolation. In particular, threads share (heap) memory with other threads running in the same application. This, in part, is why threading is useful: one thread can fetch data in the background, for instance, while another thread can display the data as it arrives.

Share Data-

Threads share data if they have a common reference to the same object instance.


Passing Data to a Thread-

  1. The easiest way to pass arguments to a thread’s target method is to execute a lambda expression that calls the method with the desired arguments
  2. Pass an argument into Thread’s Start methodUntitled

Naming Threads-

Each thread has a Name property that you can set for the benefit of debugging. This is particularly useful in Visual Studio, since the thread’s name is displayed in the Threads Window and Debug Location toolbar. You can set a thread’s name just once; attempts to change it later will throw an exception.

The static Thread.CurrentThread property gives you the currently executing thread. In the following example, we set the main thread’s name:

class ThreadNaming
  static void Main()
    Thread.CurrentThread.Name = "main";
    Thread worker = new Thread (Go);
    worker.Name = "worker";
  static void Go()
    Console.WriteLine ("Hello from " + Thread.CurrentThread.Name);


Thread Types-

  1. Foreground Thread
  2. Background Thread

Foreground threads are those threads which keeps on running to complete its work even if the main thread quits. In simple words worker thread will keeps on running (to complete work) even if the main thread has ended the session. Here lifespan of worker thread is not dependent on the main thread. Worker thread can be alive without main thread.


Background threads are those threads which quits if the main application method quits. Here lifespan of worker thread is dependent on the main thread. Worker thread quits if the main application thread quits. To use the background thread in an application we need to set a property called “IsBackground” to true.



Thread Priority-

A thread’s Priority property determines how much execution time it gets relative to other active threads in the operating system, on the following scale:

enum ThreadPriority { Lowest, BelowNormal, Normal, AboveNormal, Highest }

This becomes relevant only when multiple threads are simultaneously active.

Exception Handling-

Any try/catch/finally blocks in scope when a thread is created are of no relevance to the thread when it starts executing. Consider the following program:

public static void Main()
    new Thread (Go).Start();
  catch (Exception ex)
    // We'll never get here!
    Console.WriteLine ("Exception!");
static void Go() { throw null; }   // Throws a NullReferenceException

The try/catch statement in this example is ineffective, and the newly created thread will be encumbered with an unhandled NullReferenceException. This behavior makes sense when you consider that each thread has an independent execution path.

The remedy is to move the exception handler into the Go method:

public static void Main()
   new Thread (Go).Start();
static void Go()
    // ...
    throw null;    // The NullReferenceException will get caught below
    // ...
  catch (Exception ex)
    // Typically log the exception, and/or signal another thread
    // that we've come unstuck
    // ...

You need an exception handler on all thread entry methods in production applications. An unhandled exception causes the whole application to shut down.


Thread Pooling-

Whenever you start a thread, a few hundred microseconds are spent organizing such things as a fresh private local variable stack. Each thread also consumes (by default) around 1 MB of memory. The thread pool cuts these overheads by sharing and recycling threads, allowing multithreading to be applied at a very granular level without a performance penalty. This is useful when leveraging multicore processors to execute computationally intensive code in parallel in “divide-and-conquer” style.

The thread pool also keeps a lid on the total number of worker threads it will run simultaneously. Too many active threads throttle the operating system with administrative burden and render CPU caches ineffective. Once a limit is reached, jobs queue up and start only when another finishes. This makes arbitrarily concurrent applications possible, such as a web server.

There are a number of ways to enter the thread pool:


What are Thread.Join(), Thread.Sleep() and Thread.Abort() Methods-

  1. Thread.Join() – Join waits for a thread to end. Join method when attached to any thread it makes that thread to finish its execution first or to end first and halts other processes. In simple words we can wait for another thread to end by calling its Join method. We can include TimeSpan or milliseconds with Join method.Untitled.png
  2. Thread.Sleep() –Sleep method is used to suspend the current thread or pauses the current thread for specific time. The time can be specified in milliseconds or TimeSpan and in Sleep mode thread does not consume and CPU resources which indirectly saves the memory for other processes. Untitled.png
  3. Thread.Abort() – Thread.Abort method helps to terminate or to end thread. Abort method raises ThreadAbortException in the thread to do process of termination and throws ThreadAbortException in the thread to abort it. This exception can be caught in the application code. The complete termination can be done by calling Join method after Abort method….







What is Cookies in .Net?

Cookies are used to store data at client side. It can be used to store user name on login form or in the shopping site to store cart items etc…

There are two type of cookies-

  • Persistent cookies–  This type of cookies value does not lost even after close the browser window. Values are stored at client side until its expiration date. To create the persistent cookies just set the cookies expiration date like 1 day, 2 day etc..
  • Non Persistent cookies – This type of cookies values lost after close the browser window. To create this type of cookies do not add the expiration date.

To delete the existing cookies just set the cookies expiration date to any past date.

Cookies are created via the Response.Cookies object and can  be read using Request.Cookies object. Cookies can be created to store single value and multiple value.  Benefit of creating the multi value cookies is that we do not need to set the expiration date for each.

Multithreading and Thread safety.

If we are using the multithreading in our application then we should also keep in mind that code which can be used via mulitple threads simultaneously should be thread safe to avoid some abnormal problems.

As in the below example which is not thread safe will throw Devide by zero exception because may be same time one thread setting the value to zero and second thread trying to Devide. So it will throw the exception.

To handle this kind of  situation we should make the code thread safe. There are three techniques to handle this- lock, mutex and semaphore.

What and Why WPF?

WPF stands for Windows Representational Foundation. It’s a graphical system to create Windows application.

Why WPF as we already have win forms graphical system? There are lot of benefits of WPF over win form some are below-

  1. A- Anywhere execution(XAML). Since internal representational of WPF is XAML which is internally XML. So it can be execute as win form and in wpf browser application.
  2. B- Binding. This is also important feature of WPF. We can communicate between controls or object by just doing some property bindings instead of writing code. Ex. If there are two textbox and want the behavior like if we change the value of one textbox then second textbox value should change then it can be achieved by just setting text properties.
  3. C- Common look and feel(Styles). We can create and apply the styles like web application CSS to the wpf controls for common look and feel instead of writing same styles for defferent controls.
  4. D- Directive Programming. This is that instead of writing code we can change the behavior by just setting properties in the XAML code and rest wpf system will handle itself. Like Binding.
  5. E- Expression Blend and animation. As Wpf uses the DirectX which is a animation tool so implementing the animation is much easy in wpf application.
  6. F- Faster Execution (Hardware Rendering). As win forms rendering is done via GDI which uses the CPU for rendering( also called software rendering), as CPU also responsible for other stuff like memory management, processing etc.. os some time it become slower. But WPF rendering is done via DirectX which uses the GPU (Graphical Processing Unit) for rendering( also called hardware rendering) because this meant for only rendering so wpf rendering is faster then win forms. If GPU is not found then it uses the CPU. DirectX also responsible to identify what part of rendering should be done via CPU and what via GPU. DirectX performs this action into tiers.
  7. G- Graphic Independency(DIP). Since win forms application internally uses the device pixecles to render control so it becomes developer responsibility to handle this scenario to run application in all type of screen resolution which is itself a big task. But WPF uses the DIP(DEVICE INDEPENDENT PIXCEL) which makes the developer life easy to run application independently screen resolution.

Task Parallel Library (TPL) ?

The TPL scales the degree of concurrency dynamically to most efficiently use all the processors that are available. In addition, the TPL handles the partitioning of the work, the scheduling of threads on the ThreadPool, cancellation support, state management, and other low-level detail.

Big benefit of TPL over Threading is, It will take the maximum usage of all the available processors  as compare to threading where it had a affinity with the processor.

Threads have a core affinity i.e once a thread runs on a once core it will always run on that code but we as a developer you can write code to run thread on different cores but then you as a developer are responsible to check which core is less loaded then go and divide your logical pieces and then run on those cores and you will also be responsible to aggregate result of all cores and give back to the program. Definitely there will be lot of work like decide which core is less loaded find them and divide and run logic and sync resuts etc..

TPL encapsulate all these for us. So TPL benefits are-

  1. TPL encapsulate multi-core execution
  2. Thread Pooling
// Sequential version            
foreach (var item in sourceCollection)

// Parallel equivalent
Parallel.ForEach(sourceCollection, item =&gt; Process(item));


What is Garbage Collector in .Net?

Its a feature for Automatic Memory Management provided by CLR which help us to clean unused managed objects and by cleaning the objects basically it reclaims the memory.

Its a background thread which runs continuously and checks if there are unused managed objects(not unmanaged like COM, Excel etc.)  then clean those objects and reclaims memory.

There are three kind of  generations i,e Gen0, Gen1 and Gen2 on GC works. CLRProfiler is a nice tool to view the visual graph of these generations.