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.

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

 

top 15 sql server interview questions with answers

Q. What is sub query and its properties?
A. A sub-query is a query which can be nested inside a main query like Select, Update, Insert or Delete statements. This can be used when expression is allowed. Properties of sub query can be defined as

  • A sub query should not have order by clause.
  • A sub query should be placed in the right hand side of the comparison operator of the main query.
  • A sub query should be enclosed in parenthesis because it needs to be executed first before the main query.
  • More than one sub query can be included.

Q. What are the types of sub query?
A. There are three types of sub query –

  • Single row sub query which returns only one row.
  • Multiple row sub query which returns multiple rows.
  • Multiple column sub query which returns multiple columns to the main query. With that sub query result, Main query will be executed.

Q. What are the differences between local and global temporary tables?
A. Local temporary tables are visible when there is a connection, and are deleted when the connection is closed.

CREATE TABLE #<tablename>

Global temporary tables are visible to all users, and are deleted when the connection that created it is closed.

CREATE TABLE ##<tablename>

Q. What is COALESCE in SQL Server?
A. COALESCE is used to return first non-null expression within the arguments. This function is used to return a non-null from more than one column in the arguments. Lets suppose we have d2c_tblStudents table and having following data:

what-is-coalesce-in-sql-server

 

SELECT coalesce(studentName,studentClass,studentAddress) FROM d2c_tblStudents

output of above query will be “student1”. If we change above query as follow

SELECT coalesce(studentAddress,studentName,studentClass) FROM d2c_tblStudents

output will be remain same as previous one.

Q. What is a Trigger? How many types of triggers?
A. Triggers are used to execute a batch of SQL code when insert or update or delete commands are executed against a table. Triggers are automatically triggered or executed when the data is modified. It can be executed automatically on insert, delete and update operations.

There are four types of triggers and they are:
• Insert
• Delete
• Update
• Instead of

Q. What is an IDENTITY column in insert statements?
A. IDENTITY column is used in table columns to make that column as Auto incremental number or a surrogate key.

Q. What is the difference between UNION and UNION ALL?
A. UNION: To select related information from two tables UNION command is used. It is similar to JOIN command.
UNION All: The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values. It will not remove duplicate rows, instead it will retrieve all rows from all tables.

Q. What are the differences between Stored Procedure and the dynamic SQL?
A. Stored Procedure is a set of statements which is stored in a compiled form. Dynamic SQL is a set of statements that dynamically constructed at run time and it will not be stored in a Database and it simply execute during run time.

Q. What are Magic Tables in SQL Server?
A. Insert and Delete tables are created when the trigger is fired for any DML command. Those tables are called Magic Tables in SQL Server. These magic tables are used inside the triggers for data transaction.

Q. What is the difference between COMMIT and ROLLBACK?
A. Every statement between BEGIN and COMMIT becomes persistent to database when the COMMIT is executed. Every statement between BEGIN and ROLLBACK are reverted to the state when the ROLLBACK was executed.

Q. What is the difference between varchar and nvarchar types?
A. Varchar and nvarchar are same but the only difference is that nvarhcar can be used to store Unicode characters for multiple languages and it also takes more space when compared with varchar.

Q. What is SQL injection?
A. SQL injection is an attack by malicious users in which malicious code can be inserted into strings that can be passed to an instance of SQL server for parsing and execution. All statements have to checked for vulnerabilities as it executes all syntactically valid queries that it receives.
Even parameters can be manipulated by the skilled and experienced attackers

Q. What are the methods used to protect against SQL injection attack?
A. Following are the methods used to protect against SQL injection attack:

  • Use Parameters for Stored Procedures.
  • Filtering input parameters.
  • Use Parameter collection with Dynamic SQL.
  • In like clause, user escape characters.

Q. What is Filtered Index?
A. Filtered Index is used to filter some portion of rows in a table to improve query performance, index maintenance and reduces index storage costs. When the index is created with WHERE clause, then it is called Filtered Index.

Q. Explain the difference between DELETE , TRUNCATE and DROP commands?
A. Following are the differences

  • Once delete operation is performed, Commit and Rollback can be performed to retrieve data.
  • Once the truncate statement is executed, Commit and Rollback statement cannot be performed. Where condition can be used along with delete statement but it can’t be used with truncate statement.
  • Drop command is used to drop the table or keys like primary,foreign from a table.