Wednesday, June 7, 2017

Implementing Service Locator (To Resolve Dependency)

using System;

/// <summary>
/// Summary description for Class1
/// </summary>
public class serviceLocator
{
    public serviceLocator()
{
// TODO: Add constructor logic here
}


    //Interface
    public interface IService
    {
        void Service_Starting();
        void Service_Completed();
    }


    //Implement Interface in the Service Class
    public class Service : IService
    {
        public void Service_Starting()
        {
            Console.WriteLine("Service Starting Method is calling : Service_Starting.............");
            Console.ReadLine();
        }

        public void Service_Completed()
        {
            Console.WriteLine("Service completed Method is calling : Service_Completed Method...............");
            Console.ReadLine();
        }
    }


    //Service Locator Class
    public static class LocateService
    {
        public static IService _Service { get; set; }

        public static IService GetService()
        {
            if (_Service == null)
                _Service = new Service();

            return _Service;
        }
    }


    //Client Class
    public class Client
    {
        private IService _service;

        public Client()
        {
            this._service = LocateService.GetService();
        }

        public void Start()
        {
            Console.WriteLine("Client :Method is Calling.........\n");
            this._service.Service_Starting();
            this._service.Service_Completed();
            Console.ReadLine();
        }
    }


    //Main Programm
    class Program
    {
        static void Main(string[] args)
        {
            var client = new Client();
            client.Start();
            Console.ReadKey();
        }
    }
}

Monday, May 29, 2017

IDENT_CURRENT (Transact-SQL) / IDENT_CURRENT( 'table_name' )

IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope.

When the IDENT_CURRENT value is NULL (because the table has never contained rows or has been truncated), the IDENT_CURRENT function returns the seed value.

Let's Start With the Below Process:
---Create Table-----
 Create Table empTable 
 (
 empId numeric(4),
 empname varchar(100)

 )

--Insert the record in the table
Now Insert some values (values for 'empid' is not required as this is an identity column ).
insert into dbo.empTable values ('employee 1')
insert into dbo.empTable values ('employee 2')
insert into dbo.empTable values ('employee 3')
insert into dbo.empTable values ('employee 4')
insert into dbo.empTable values ('employee 5')
insert into dbo.empTable values ('employee 6')
just to confirm run the below query:
select * from dbo.empTable
output:
1 employee 1
2 employee 2
3 employee 3
4 employee 4
5 employee 5
6 employee 6


Now run the below query:
select IDENT_CURRENT( 'empTable' )
NOTE: The above function accepts table / view name.
Output:
6
Now insert one more row and then check this:
insert into dbo.empTable values ('employee 7')
select IDENT_CURRENT( 'empTable' )
Output:
7.
What does the function do ? This always give you the current 'empid' value from the table.
Now run the query below.
insert into dbo.empTable values ('employee 8')
select IDENT_CURRENT( 'empTable' )
select @@IDENTITY
what is the output :
8
That means @@IDENTITY does the same thing!!!!
Wait and watch:
Open a new Query window and run the below query again:
select IDENT_CURRENT( 'empTable' )
select @@IDENTITY
Output:
8
NULL
Oops Strange ! RIGHT???
The difference between them is
·  IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope.
·  @@IDENTITY returns the last identity value generated for any table in the current session, across all scopes.
One more observation which is very important:
Run the below query in seperate query window:
select MAX(empid) from dbo.empTable
select IDENT_CURRENT( 'empTable' )
delete from dbo.empTable where empid = 8
select MAX(empid) from dbo.empTable
select IDENT_CURRENT( 'empTable' )
What is the output we get?
8
8
7
8
What we see is MAX(empid) always give the max of the row but the
IDENT_CURRENT( 'empTable' ) gives the last inserted value. this is very useeful for transactions table where we have some data retrieving logic between more than one table but having dependency on the identity column.
IDENT_CURRENT( 'tablename/viewname')  decoded.

Thursday, May 11, 2017

What is difference between Factory and Abstract factory design pattern?


Try to understand the two design patter with some simple examples factory design pattern:

You have some raw materiel (Input) , you provided it to one factory (factory class) and the factory gives you a product (object) so based on your raw material and factory implementation you get a product this is a simple illustration of factory design pattern


Now for the Abstract factory design: It’s like you have raw material, you provided it to one factory as input but instead of processing your input this factory delegates the task to create product to its sub factories. 

So simply, an abstract factory means multiple factories.

Thursday, April 27, 2017

Design Pattern in .NET

Creational Patterns
  Abstract FactoryCreates an instance of several families of classes
  BuilderSeparates object construction from its representation
  Factory MethodCreates an instance of several derived classes
  PrototypeA fully initialized instance to be copied or cloned
  SingletonA class of which only a single instance can exist

Structural Patterns
  AdapterMatch interfaces of different classes
  BridgeSeparates an object’s interface from its implementation
  CompositeA tree structure of simple and composite objects
  DecoratorAdd responsibilities to objects dynamically
  FacadeA single class that represents an entire subsystem
  FlyweightA fine-grained instance used for efficient sharing
  ProxyAn object representing another object

Behavioral Patterns
  Chain of Resp.A way of passing a request between a chain of objects
  CommandEncapsulate a command request as an object
  InterpreterA way to include language elements in a program
  IteratorSequentially access the elements of a collection
  MediatorDefines simplified communication between classes
  MementoCapture and restore an object's internal state
  ObserverA way of notifying change to a number of classes
  StateAlter an object's behavior when its state changes
  StrategyEncapsulates an algorithm inside a class
  Template MethodDefer the exact steps of an algorithm to a subclass
  VisitorDefines a new operation to a class without change

Wednesday, April 26, 2017

Singleton Pattern – Pros Cons

RS Prajapati, 28 Dec 2014Description: https://codeproject.global.ssl.fastly.net/script/Ratings/Images/stars-fill-md.png


Introduction
The Singleton pattern is probably the most famous and at the same time the most controversial pattern known to us. It must be also be the simplest pattern to learn and implement. Like any other pattern, Singleton exists to solve a common business problem that is ‘managing the state of a resource’. But does it solve the real problem or introduce additional problems? That is exactly the topic I am covering here.
Positive Sides of Singleton
One of the toughest issues to debug is the one created by the multiple instances of a class which manages the state of a single resource. It is highly desirable if we can use some Design Pattern to control the access to that shared resource. The Singleton pattern fits the bill perfectly to solve this scenario; by wrapping a singleton class around this problem ensures that there will be only one instance of the class at any given time. A most common and clichéd example for a singleton class is the one used for logging purposes where the whole application needs only one logger instance at anytime.
The anatomy of a singleton class is very simple to understand. The class typically has a private constructor which will prohibit you to make any instance of the singleton class; instead you will access a static property or static function of the singleton class to get the reference of a preconfigured instance. These properties/methods ensure that there will be only one instance of the singleton class throughout the lifetime of the application.
The one and only instance of a singleton class is created within the singleton class and its reference is consumed by the callers. The creation process of the instance can be done using any of the following methods:
1. Lazy Instantiation
If you opt for the lazy instantiation paradigm, then the singleton variable will not get memory until the property or function designated to return the reference is first called. This type of instantiation is very helpful if your singleton class is resource intense.


However, the above implementation is not taking any precautions to be thread safe. That is, there may be situations like two or more threads accessing the Instance property at the same time which will create more than one instance of the singleton class.
We can use various thread synchronization techniques to combat the circumstances said above. One way is the use of double-checked locking. In double-checked locking, synchronization is only effective when the singleton variable is null, i.e., only for the first time call to Instance. This helps us to limit the performance penalty that comes along with the synchronization object to only happen once.

2. Static Initialization
In static initialization, memory is allocated to the variable at the time it is declared. The instance creation takes place behind the scenes when any of the member singleton classes is accessed for the first time. The main advantage of this type of implementation is that the CLR automatically takes care of race conditions I explained in lazy instantiation. We don't have to use any special synchronization constructs here. There are no significant code changes in the singleton implementation when you switch from lazy instantiation to static initialization. The only change is that the object creation part is moved to the place where we are declaring the variable.

Inheritance of Singleton Class
Inheriting a singleton class should be prohibited. Making a singleton class inheritable means any number of child classes can inherit from it creating multiple instances of the singleton class which will obviously violate the principle of singletons.
Singleton Class vs. Static Methods
Singleton takes over static classes on the following shortcomings:
1.       Static classes don’t promote inheritance. If your class has some interface to derive from, static classes makes it impossible.
2.       You cannot specify any creation logic with static methods.
3.       Static methods are procedural code.
Negative Sides of Singleton
The following points are used against the Singleton pattern:
1.       They deviate from the Single Responsibility Principle. A singleton class has the responsibility to create an instance of itself along with other business responsibilities. However, this issue can be solved by delegating the creation part to a factory object.
2.       Singleton classes cannot be sub classed.
3.       Singletons can hide dependencies. One of the features of an efficient system architecture is minimizing dependencies between classes. This will in turn help you while conducting unit tests and while isolating any part of the program to a separate assembly. A singleton will make you sacrifice this feature in your application. Since the object creation part is invisible to us, we cannot expect the singleton constructor to accept any parameters. This setback may look unimportant on the first glance but as the software complexity increases, it will limit the flexibility of the program.
Programmers often resort to the idea of Dependency Injection to overcome this problem. When dependency Injection is used, Singleton instance is not retrieved inside the class but is passed through the constructor or a property
Hide   Copy Code
IMathFace obj = Singleton.Instance;
SingletonConsumer singConsumer = new SingletonConsumer(obj);
singConsumer.ConsumerAdd(10,20);
In the above example, SingletonConsumer's constructor accepts a parameter of type IMathFace. It can be the real singleton instance or a mock object.
When to Use a Singleton Class?
There is no straightforward answer to this question. A scenario which is acceptable to some will be unacceptable to others.
However, it is commonly accepted that the singleton can yield best results in a situation where various parts of an application concurrently try to access a shared resource. An example of a shared resource would be Logger, Print Spooler, etc.
The following points are suggested to be considered while designing a singleton class:
1.       Singleton classes must be memory-leak free. The instance of the singleton class is to be created once and it remains for the lifetime of the application.
2.       A real singleton class is not easily extensible.
3.       Derive the singleton class from an interface. This helps while doing unit testing (using Dependency Injection).
Conclusion
The notion of Singleton pattern replacing global variables is not always true. You should keep all the positive and negative aspects of the Singleton pattern in mind before deciding on it.


Tuesday, July 14, 2015

Solved :An unexpected error occurred while compiling expressions. Native compiler return value: ‘[BC2001] file 'C:\Windows\TEMP\bgmkithf.0.vb' could not be found’.

Solution:
Follow the following instructions to get rid of the error.
Step 1:
Go to your IIS (Internet Information Service) manager. Click on “Application Pools” which is on left upper side of IIS manager.

Then you will see all pools list existing on IIS on the right side.
Step 2:
Create a new pool. Right click on right side. You will get the option named “Add Application Pool”.


Click on this option and a form will be popped up before you.

Put the “Name” (My project display name on browser is MFS so I used MFS. You can use your name too. No boundaries…J) And select the “.Net Framework version” which you are using in your project. Here I used .Net Framework 4.0.
After creation, a new pool will be seen on right side pool list.

Step 3:
Now change some Advance Settings (on your right side) of your newly created application pool.

Choose “Local System” as an option for Identity section in settings properties.
Step 4:
Now click on project name (left side) on IIS server. Then click on its Advance Settings section (right side) to change its pool from “DefaultAppPool” to “MFS” (your provided pool name).

Step 5:
Your all steps are done. Now just let’s “Restart” (This option is provided on right side of your window) the IIS manager to kick out this problem from your deployment difficulties list.

Now enjoy your reports without seeing any crazy error. Happy coding…J

Implementing Service Locator (To Resolve Dependency)

using System; /// <summary> /// Summary description for Class1 /// </summary> public class serviceLocator {     public s...