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

multicast delegate

Multicast Delegate

  • A Multicast delegate is delegate which has references to more than one function.
  • When we invoke a multicast delegate, all function the delegate is pointing to, are invoked.
  • A multicast delegate, invoke the methods in same order in which they are added.
  • We can register a method with a delegate using + OR += operator.
  • We can un-register a method with from a delegate using – OR -= operator.

Example:

namespace d2cMulticastDelegateSample
{
class Program
{
public delegate void d2cDelegateObj();
static void Main(string[] args)
{
d2cDelegateObj delObj1 = new d2cDelegateObj(d2cMethodOne);
d2cDelegateObj delObj2 = new d2cDelegateObj(d2cMethodTwo);
d2cDelegateObj delObj3 = new d2cDelegateObj(d2cMethodThree);
d2cDelegateObj delObj4;

//register delegate using + operator
delObj4 = delObj3 + delObj1 + delObj2;// register a method with a delegate
Console.WriteLine("Multicast Delegate after register method with + operator");
delObj4();
// invoke the methods in same order in which they are added
Console.WriteLine("\n\nMulticast Delegate after un-register method with -= operator");
delObj4 -= delObj2;
delObj4();
Console.ReadLine();
}

public static void d2cMethodOne()
{
Console.WriteLine("Method One, Welcome to desire2code.com ");
}
public static void d2cMethodTwo()
{
Console.WriteLine("Method Two, Welcome to desire2code.com ");
}
public static void d2cMethodThree()
{
Console.WriteLine("Method Three, Welcome to desire2code.com ");
}
}
}

Output:

Multicast Delegate after register methos with + operator
Method Three, Welcome to desire2code.com
Method One, Welcome to desire2code.com
Method Two, Welcome to desire2code.com

Multicast Delegate after un-register methos with -= operator
Method Three, Welcome to desire2code.com
Method One, Welcome to desire2code.com

  • A delegate has a return type other than void, and if the delegate is a multicast delegate, only the value of the last invoked method will be returned.

Example:

public delegate string d2cDelegateObj();
static void Main(string[] args)
{
d2cDelegateObj delObj1 = new d2cDelegateObj(d2cMethodOne);
d2cDelegateObj delObj2 = new d2cDelegateObj(d2cMethodTwo);
d2cDelegateObj delObj3 = new d2cDelegateObj(d2cMethodThree);
d2cDelegateObj delObj4;

//register delegate using + operator
delObj4 = delObj3 + delObj1 + delObj2; // register a method with a delegate
Console.WriteLine("Multicast Delegate after register method with + operator");
Console.WriteLine(delObj4());
// Because delObj2 added at last so this multicast delegate invoked function and return delObj2 return value
Console.ReadLine();
}

public static string d2cMethodOne()
{
return "Method One";
}
public static string d2cMethodTwo()
{
return "Method Two";
}
public static string d2cMethodThree()
{
return "Method Three";
}

Output:

Multicast Delegate after register method with + operator
Method Two

Basics of delegate

What is delegate

  • A delegate is a type safe function pointer.
  • Delegate hold a reference to a function.
  • The signature of the delegate must match the signature of the function, the delegate points to,otherwise we get a compiler error.This is the reason delegates as called type safe function pointers.
  • A delegate is similar to a class, we can create an instance of it, and when we do so, we pass in the function as parameter to the delegate, constructor, and it is to this function the delegate will point to.

Example

using System;
namespace d2cDelegatesSample
{
class Program
{
public delegate void WelcomeWindowDelegate(string inputMeggage);

static void Main(string[] args)
{
WelcomeWindowDelegate objDelegate = new WelcomeWindowDelegate(WelcomeWindow);
objDelegate("Welcome To Desire2Code.com");
}

public static void WelcomeWindow(string inputMessage)
{
Console.WriteLine(inputMessage);
Console.ReadLine();
}
}
}

Triggers in SQL Server

A trigger in SQL Server is a special kind of stored procedure that automatically executes when an event occurs in the database server. There are following types of triggers available in SQL Server,

  • DML Triggers
  • DDL Triggers
  • Logon Triggers

DML Triggers: DML Triggers get executed when a user tries to modify data through data manipulation language (DML) like INSERT, UPDATE, or DELETE statements on a table or view. DML triggers fire when any valid event is performed, regardless of whether or not any table rows are affected.

Example: 

CREATE TRIGGER d2c_trgInsertAuditInfo ON d2c_tblStudents AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
declare @studentName varchar(100)
select @studentName=tmp.studentName from INSERTED tmp
insert into d2c_tblStudentsAuditInfo
(auditInfo)
VALUES('New record inserted Student Name: '+@studentName+')
END

Explanation:
In above example we have created d2c_trgInsertAuditInfo trigger on d2c_tblStudents table.
Whenever any new record will insert into d2c_tblStudents table, d2c_trgInsertAuditInfo trigger
will fire and mentioned query will execute.

DDL Triggers:DDL triggers fire in response to a variety of Data Definition Language (DDL) events. These events primarily correspond to Transact-SQL statements that start with the keywords CREATE, ALTER, DROP, GRANT, DENY, REVOKE or UPDATE STATISTICS.Real word use of DDL Triggers is to track database changes or all database in server.

Example:

CREATE TRIGGER d2c_trgDatabaseChange ON ALL SERVER FOR CREATE_DATABASE
AS
BEGIN
SET NOCOUNT ON;
PRINT 'Database Created...'
END

Explanation:
In above example we have created d2c_trgDatabaseChange trigger on all server for creation of new database.Whenever any new database will create in server, d2c_trgDatabaseChange trigger will fire and mentioned query will execute.

Logon Triggers: Logon Triggers get executed in response to the LOGON event that is raised when a user sessions is being established. These are useful in cases where we want to track which all users are connecting to the SQL Server instance and and write that information in to a table which can be later used to review. General use is for auditing purposes and sometimes to prevent actions when login happens from a suspicious computer.

Example:

/* Create Audit Database */
CREATE DATABASE d2c_AuditDb
GO
USE d2c_AuditDb
GO
/* Create Audit Table */
CREATE TABLE d2c_ServerLogonLog
(SystemUser VARCHAR(512),DBUser VARCHAR(512),SPID INT,LogonTime DATETIME)
GO
/* Create Logon Trigger */
CREATE TRIGGER d2c_trgServerLogon ON ALL SERVER FOR LOGON
AS
BEGIN
INSERT INTO d2c_AuditDb.dbo.d2c_ServerLogonLog
SELECT SYSTEM_USER,USER,@@SPID,GETDATE()
END
GO

Explanation:
In above example we have created d2c_trgServerLogon trigger on all server for LOGON.
Whenever any new session will created d2c_trgServerLogon trigger will fire and mentioned query will execute.

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;
}
}

Saving changes is not permitted in SQL Server

Error: Some time when we try to edit the table design, like change a column type from int to real, we usually get following error:

Saving changes is not permitted. The change you have made requires the following table to be dropped and re-created. You have either made changes to a table that can’t be recreated or enabled the option prevent saving changes that require the table to be re-created.

Solution: 

To change this option, on the Tools menu, click Options, expand Designers, and then click Table and Database Designers. Select or clear the Prevent saving changes that require the table to be re-created check box.

saving-changes-is-not-permitted-in-sql-server