observer design pattern

Here is the definition of observer design pattern

The observer is know as a behavioral pattern, as it’s used to form relationship between object at run time. Its define a 1-m dependency objects so that when one object changes state, all its dependents are notified and update automatically.

Bounce! Bounce! Bounce!
OK, lets define above definition once more, little easy

In ODP an object called the subject, maintains a list of its dependents, called observers, and notify them automatically of any state change, usually by calling one of their method.

OK! OK! OK! little easy

In ODP, Observer and Subject are two interface, where all classes those implement Subject interface have a list of observer object to notify and classes those implement Observer interface have list of Subject object to be notify.

Ohhh GOD! last attempt.

Observer register with the subject and wait for notification.
Subject notify observer about a change in state. Observer take action.

When ODP come into action?

  • When we want to reduce coupling.
  • If we have an object that need to share it’s state with other, without knowing who those objects are, the observer pattern come into action.

Case Study
There is a terrorist group that the RAW(Research And Analysis Wing) are trying to catch.So we need a tracking system that track terrorist information immediately. We need to create a alert device, if terrorist are near.
There are following step we need to follow,

Step 1: Identify the observer and subject
In this case terrorist will be subject and RAW tracking device will be observer.
So we need to represent information about the terrorist in a few line of code which represent by a class.
/* A single terrorist has a location*/
class Terrorist
{
public string location;
}

The RAW device will be the observers. Which will push alert on critical notification.
/*A device has an alert status(as a Boolean), notification update(as a string), location(as a string), it can push alert & update alert.*/

class Module
{
public string location;
public Boolean alert;
public string notification,
void sendAlert()
{
if(alert)
{
Console.WriteLIne("Alert:"+notification+"Agent in "+this.location);
}
}
}

Step 2: Set up the observer and subject abstractions
The abstractions for observer and subject will be interface.

/*All observer classes implement an observer interface, it can update object data based
on subjects. Observer classes may need a list of subject to access*/
interface IObserver
{
void update();
}

/*All subject classes implement a subject interface, it can notify observer, add/remove
observer in its update list. Subject classes also need a list of observer to update*/
interface ISubject
{
void NotifyObserver();
void AddObject(IObserver obj);
void RemoveObject(IObserver obj);
}

Step 3: Modify our subject class via implement ISubject interface
class Terrorist : ISubject
{
public string location;
private List obs = new List();
public void NotifyObserver()
{
foreach (var o in obs)
{
o.update(this);
}
}

public void AddObject(IObserver obj)
{
obs.Add(obj);
}

public void RemoveObject(IObserver obj)
{
obs.Remove(obj);
}
}

Step 4: Modify our observer class via implement IObserver interface
class Module : IObserver
{
public string notification;
public Boolean alert;
public string location;
public void update(Terrorist t)
{
if (this.location == t.location)
{
this.alert = true;
this.notification = "Terrorist Nearby ";
}
else
{
this.alert = false;
this.notification = "";
}
SendAlert();
}
void SendAlert()
{
if (alert)
{
Console.WriteLine("Alert: " + notification + "Agent in " + this.location);
}
}
}

Step 5: Finally run the code
namespace d2cObserverDesignPatternSample
{
class Program
{
static void Main(string[] args)
{
//create all data objects
Terrorist t = new Terrorist();
Module m1 = new Module();
Module m2 = new Module();
Module m3 = new Module();
//Add observer
t.addObs(m1);
t.addObs(m2);
t.addObs(m3);
//create all location
string[] locs = new string[5];
locs[0] = "New Delhi";
locs[1] = "Kolkata";
locs[2] = "Mumbai";
locs[3] = "Punjab";
locs[4] = "Pune";
// Set observer to their location
m1.location = locs[1];
m2.location = locs[3];
m3.location = locs[4];
//As the terrorit relocates all over India, it will notify all device modules of its location.
//Module will trigger when a terrorist is nearby
for (int i = 0; i < 5; i++)
{
t.location = locs[i];
t.notifyObservers();
}
Console.ReadLine();
}
}
}

Output
Alert: Terrorist Nearby Agent in Kolkata
Alert: Terrorist Nearby Agent in Punjab
Alert: Terrorist Nearby Agent in Pune

Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same.

Error:
Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same.

ss

Solution:

  • Type dcomcnfg in run command.
  • Component Service form will appear, select services (Local) section.
  • Check ASP.NET State service.
  • right click on ASP.NET State service.
  • Select Properties.
  • You will see service status is stopped, click start button, wait for task completion.
  • Reload you web page again.

1

C# Multithreading interview questions with answers Part 1

What is the difference between Process and Thread?

  • A process is what the operating system uses to facilitate the execution of a program by providing the resources required.
  • A process can start multiple threads.
  • Every process is start with a single thread called primary thread.
  • A single process can have multiple threads.
  • Threads share the resources allocated to process.
  • A process is the parent and threads are his children.

How to create and start a Thread in C#?

We have to use the Thread class provided by System.Threading namespace. In the constructor of the class, we have to pass the method name which we want to run in separate thread. After than we have to call the start method of Thread class. Below is the example.

using System;
using System.Threading;

namespace d2cThreadSample
{
class Program
{
static void Main(string[] args)
{
Thread objThread1 = new Thread(d2cThreadMethod);
objThread1.Start();
}

private static void d2cThreadMethod()
{
Console.WriteLine("Welcome to desire2code.com");
Console.ReadLine();
}

}
}

How to pass parameter in Thread?

In the constructor of Thread, we can pass the method name which accepts only a single parameter. Then we have to pass parameter into the Start method. Below is the example.
using System;
using System.Threading;

namespace d2cThreadSample
{
class Program
{
static void Main(string[] args)
{
Thread objThread1 = new Thread(d2cThreadMethod);
objThread1.Start("Welcome to desire2code.com");
}

private static void d2cThreadMethod(object inputString)
{
Console.WriteLine(inputString);
Console.ReadLine();
}

}
}

What is Deadlock? What are four necessary conditions for Deadlock?

A deadlock is a situation in which two or more processes cannot complete their work.They are blocked and each thread waiting for other threads to release resource they want. For example, we have two threads T1 and T2 and we have two resources R1 and R2. Both threads want to work with both resources. But in opposite fashion, T1 want to work with R1 first and then with R2. T2 want to work with R2 first and then with R1. Both threads starts at the same time. T1 locked R1 while at the same time T2 locked R2. Now T1 want a lock on R2 which is already locked by T2 and T2 want a lock on R1 which is already locked by T1. Both threads waiting for other threads to unlock the resources. Both threads are waiting for infinite time and cann’t continue forever.

deadlock

Deadlock Conditions
mutual exclusion
The resources involved must be unshareable; otherwise, the processes would not be prevented from using the resource when necessary.
hold and wait or partial allocation
The processes must hold the resources they have already been allocated while waiting for other (requested) resources. If the process had to release its resources when a new resource or resources were requested, deadlock could not occur because the process would not prevent others from using resources that it controlled.
no pre-emption
The processes must not have resources taken away while that resource is being used. Otherwise, deadlock could not occur since the operating system could simply take enough resources from running processes to enable any process to finish.
resource waiting or circular wait
A circular chain of processes, with each process holding resources which are currently being requested by the next process in the chain, cannot exist. If it does, the cycle theorem (which states that “a cycle in the resource graph is necessary for deadlock to occur”) indicated that deadlock could occur.

What is immutable object? How to create an immutable object?

An immutable object is an object which states cannot be changed after creation. Immutable objects are useful in concurrent programming as they are thread-safe. Immutable objects are objects which once loaded cannot be changed / modified by any way external or internal.

Immutable objects can be created only from immutable classes. To create an immutable class is a three step process:

Step 1: Remove the setters of the class, only have getters.

class ImmutableObject
{
private string _applicationSessionId;
public string applicationSessionId
{
get { return _applicationSessionId; }
}
}

Step 2: Provide parameters via constructor.

class ImmutableObject
{
private string _applicationSessionId;
public string applicationSessionId
{
get { return _applicationSessionId; }
}
public ImmutableObject(string iapplicationSessionId)
{
_applicationSessionId = iapplicationSessionId;
}
}

Step 3: Make the variables of the property READONLY

class ImmutableObject
{
private readonly string _applicationSessionId;
public string applicationSessionId
{
get { return _applicationSessionId; }
}
ImmutableObject(string iapplicationSessionId)
{
_applicationSessionId = iapplicationSessionId;
}
}

How .NET Program Execute

Using dotnet we can create different types of applications. A few of the common types of .NET applications include Web, Windows, Console and Mobile Applications. Irrespective of the type of the application, when you execute any .NET application the following happens

1. The .NET application gets compiled into Intermediate language (IL). IL is also referred as Common Intermediate language (CIL) and Microsoft Intermediate language (MSIL).

So, in .NET the application execution consists of 2 steps
1. Language compiler, compiles the Source Code into Intermediate Language (IL)
2. JIT compiler in CLR converts, the IL into native code which can then be run on the underlying operating system.

dot-net-program-execution

Since, a .NET assembly is in Intermedaite Language format and not native code, .NET assemblies are portable to any platform, as long as the target platform has the Common Language Runtime (CLR). The target platform’s CLR converts the Intermedaite Language into native code that the underlying operating system can understand. Intermediate Languge is also called as managed code. This is because CLR manages the code that runs inside it.

The native code is not stored permanently anywhere, after we close the program the native code is thrown awaya. When we execute the program again, the native code gets generated again.

.NET program is similar to java program execution. In java we have byte codes and JVM (Java Virtual Machine), where as in .NET we Intermediate Language and CLR (Common Language Runtime)