Wednesday, 22 November 2017

Singleton pattern

Singleton pattern:


Definition:-
A singleton is a class which only allows a single instance of itself to be created,and
usually gives simple access to that instance.
Often, a system only needs to create one instance of a class, and that instance will be
accessed throughout the program.
Schnerio:-
  1. Examples would include objects needed for logging, communication, database access, etc.
  2. Let's say you're creating an application that has reporting functionality, and the client
2.wants to maintain a count of all reports that are generated & printed. Since the Singleton
2.design pattern allows for only a single instance, and it a global access point for the
2.reporting module, this would allow you, the designer, to ensure that an accurate count is
2.always maintained, without having to rely on global statics variables.
So, if a system only needs one instance of a class, and that instance needs to be accessible
in many different parts of a system, one control both instantiation and access by making
that class a singleton.
รจ A Singleton is the combination of two essential properties:
Ensure a class only has one instance.
Provide a global point of access to it.
A singleton is a class that can be instantiated once, and only once.
To achieve this we need to keep the following things in our mind.
1. Create a public Class (name SingleTonSample).
public class SingleTonSample
{}
2. Define its constructor as private.
private SingleTonSample()
{}
3. Create a private static instance of the class (name singleTonObject).
private volatile static SingleTonSample singleTonObject;
4. Now write a static method (name InstanceCreation) which will be used to create an
instance of this class and return it to the calling method.
public static SingleTonSample InstanceCreation()
{
    private static object lockingObject = new object();
    if(singleTonObject == null)    {         lock (lockingObject)
         {      if(singleTonObject == null)
              {  singleTonObject = new SingleTonSample();           }
         }
    }
    return singleTonObject; }
Now we to need to analyze this method in depth. We have created an instance of object named
lockingObject, its role is to allow only one thread to access the code nested within the
lock block at a time. So once a thread enter the lock area, other threads need to wait until
the locking object get released so, even if multiple threads try to access this method and
want to create an object simultaneously, it's not possible. Further only if the static
instance of the class is null, a new instance of the class is allowed to be created.
Hence only one thread can create an instance of this Class because once an instance of this
class is created the condition of singleTonObject being null is always false and therefore
rest all instance will contain value null.
5. Create a public method in this class, for example I am creating a method to display
     message (name DisplayMessage), you can perform your actual task over here.
public void DisplayMessage() {
     Console.WriteLine("My First SingleTon Program"); }
6. Now we will create an another Class (name Program).
class Program
{}
7. Create an entry point to the above class by having a method name Main.
static void Main(string[] args) {
    SingleTonSample singleton = SingleTonSample.InstanceCreation();
    singleton.DisplayMessage();
    Console.ReadLine(); }
Now we to need to analyse this method in depth. As we have created an instance singleton of
the class SingleTonSample by calling the static method SingleTonSample.InstanceCreation() a
new object gets created and hence further calling the method singleton.DisplayMessage()
would give an output "My First SingleTon Program".
------------------------------------------------------------------------------------------------------------------------------------
The Singleton pattern ensures that a class only has one instance and provides a global point
of access to it from a well-known access point. The class implemented using this pattern is
responsible for keeping track of its sole instance rather than relying on global variables
to single instances of objects.
namespace DesignPatterns
{     public sealed class Singleton     {
           private static readonly Singleton    instance = new Singleton();
           private Singleton()        {         }
          public static Singleton Instance
          {             get              {                 return instance;             }         }
    }
}
using System.Diagnostics;
using DesignPatterns;
Trace.WriteLine(Singleton.Instance.ToString());
Explanation
First, you'll notice that the Singleton's constructor is set to private. This ensures that
no other code in your application will be able to create an instance of this class. This
enforces the requirement that there ever only be one instance of this class.
Then, an instance member variable is defined of the same type as the class. This instance
member is used to hold the only instance of our class. The variable is static so that it is
defined only once. In the .NET Framework, static variables are defined at a point before
their first use (that's the actual description of their implementation). Also, the instance
variable is readonly so that it cannot be modified - not even by any code that you may write
in the class's implementation.
And, a public Instance property is defined with only a get method that way callers can
access the instance of this class without ever being able to change it. The property is also
static to provide global access from anywhere in your program. This ensures the global point
of access requirement for the Singleton.
Finally, to test the code, you can run code that accesses your Singleton class. As you can
see above, it's easy enough to get at the instance of your class:
Singleton.Instance;
Place a breakpoint in instance member variable definition and another one in the Instance
property get code, then run the Debugger on this code. You will notice that the member
variable creation is hit just before the call to the Instance property. Also, if you place
multiple calls to Singleton.Instance, you will notice that the instance member variable is
only the first time, all other calls just return the cached instance variable.
And, that is the only way to get an instance of a singleton class. If you try to create an
instance of the Singleton class using the new operator:
Singleton NewInstance = new Singleton();
Than, you will get a compiler error stating that the class cannot be created because the
constructor is inaccessible due to its protection level.
Thread-Safe Singleton Code:--
The previous code is the simplest implementation of a Singleton and can be used for most
purposes. Typical WinForms applications runs in the UI thread, so the simple singleton will
provide you with the functionality that you're looking for. However, if you are creating a
multi-threaded application that needs to access a singleton across all of its threads, then
you will need to create a thread-safe singleton class instead. What you gain in
functionality comes at the cost of some performance, so you shouldn't use this form of the
class unless you actually intend to use the class from multiple threads.
namespace DesignPatterns {
    public sealed class MTSingleton     {

        private static volatile MTSingleton    instance = null;
        private static object syncRoot = new object();
        private MTSingleton()
        {         }
        public static MTSingleton Instance
        {              get              {
                if (instance == null)
               {
                   lock(syncRoot)
                   {
                      if (instance == null)
                          instance = new MTSingleton();
                   }
                }                return instance;
           }         }      } }
// code to access the Singleton.
using System.Diagnostics;
using DesignPatterns;
Trace.WriteLine(MTSingleton.Instance.ToString());
As you can see, this class is similar in structure to the Singleton class. The instance
member variable is no longer set at creation time, but in the Instance property instead. The
instance variable is declared to be volatile in order to assure that the assignment of
instance complete before the instance can be accessed.
The syncRoot object is used to lock on. The lock ensures that only one thread can access the
instance creation code at once. That way, you won't get into a situation where two different
threads are trying to create the singleton simultaneously.
And, you'll notice that we double-check the existence of the instance variable within the
locked code to be sure that exactly one instance is ever created.
Finally, in your application code, access to the MTSingleton class is done in exactly the
same way as with the simple singleton.
The Singleton design pattern has proven to be a useful pattern in many programs that I've
written. Now, the code in this tutorial shows how to implement that same pattern in the .NET
Framework.

WCF Vs ASMX Web services

WCF Vs ASMX Web services
Simple and basic difference is that ASMX web service is designed to send and receive messages using SOAP over HTTP only. While WCF service can exchange messages using any format (SOAP is Default) over any protocol (HTTP, TCP/IP, MSMQ, Named Pipes etc).
ASMX is simple but limited in many ways as compared to WCF:
  1. ASMX web service can be hosted only in IIS, while WCF service has all the following hosting options:
    1. IIS
    2. WAS (Window Process Activation Services)
    3. WCF provided Host (Self Hosting)
    4. Console Application
    5. Window NT services
    6. ASMX web services support is limited to HTTP while WCF supports HTTP, TCP, MSMQ, and Named Pipes.
    7. ASMX Security is limited. Normally Authentication (Objects) and Authorization (Class or classes, we can say subject) is done using IIS and ASP.NET Security Configuration and Transport Layer Security. For message Layer Security, WSE can be used.
WCF provide a consistent security programming model for any protocol and it supports many of the same capabilities as IIS and WS-* Security protocols, additionally, it provides support for claim-based Authorization that provides finer-grained control over resources than role-based security. WCF security is consistent regardless of the host that is used to implement WCF service.
  1. Another major different between is that ASMX web services uses XmlSerializer for Serialization while WCF uses DataContractSerializer which is far better in performance than XmlSerializer .
Key Issues with XmlSerializer in serializing .NET types to XML are:
  1. Only public fields or properties of the  .NET types can be translated to xml.
  2. Only the classes that implement IEnumerable can be translated.
  3. Classes the implement IDectionary, such as Hashtable cannot be serialized.





WCF Service - Simple Steps to Enable Transactions
Transaction is basically a logical unit of work comprising of activities that all needed to be succeeded or failed, and also it must be compliant with ACID principals.

Movement of money from a bank account to another is a simple example of a transaction. In this single transaction, two operations will be performed. One account will be debited (amount will be
taken from) and other will be credited (amount will be deposited).

Enabling transactions in Windows Communication Foundation is simple and straight forward but implementation sometimes becomes difficult depending upon the scenario. For example, implementing transactions in a distributed environment will definitely require effort and more things to consider.

Now, consider we already have developed a WCF service and we wanted to enable transactions on it. So, we will follow the steps below:
  1. Add System.Transactions namespace to WCF Service project.
  2. Set TransactionFlow property of the OperationContract attribute to Mandatory.
    Available options for TransactionFlow are:
    a. Mandatory - transaction must be flowed
    b. Allowed - transaction may be flowed
    c. Not Allowed - transaction is not flowed

    For example, our WCF service contract as follows:

    [TransactionFlow(TransactionFlowOptions.Mandatory]
    void MyMethod();
  1. Now, set the OperationBehavior attribute for the implementing method.

    [OperationBehavior(TransactionScopeRequired=true, TransactionAutoComplete=true)]
    void MyMethod()
    {
    }

    TransactionScopeRequired = true means it can only be called in a transaction.
    TransactionAutoComplete = true means that if the operation completes successfully, transaction will be committed.
  1. Enable Transactions for WCF Binding being used.
    For Example, In our configuration file bindings will be as follows:

    <bindings>
      <wsHttpBinding>
         <binding name="”httpBinding” ">transactionFlow=”true” /></binding>
      </ wsHttpBinding >
    </bindings>

    Remember that we must choose a binding that supports transactions i.e. netTcpBinding, netNamedPipeBinding, wsHttpBinding, wsDualHttpBinding, and wsFederationHttpBinding.
  1. Need to start the transaction from client as:

    using System.Transaction;
    Using( var transScope = new TransactionScope())
    {   

         //Calling service methods
         IMyServiceClient client = new IMyServiceClient();
         client.MyMethod();
        
         transScope.complete();
       
    }
Optionally, If we wanted to specify the Isolation level for the transaction, we can add serviceBehavior attribute to implementing class as follows:

[ServiceBehavior(TransactionIsolationLevel=System.Transaction.IsolationLevel.Serializable)]
Public class MyService : IMyService{}

This is all we need to do for enabling transactions in WCF.
There are few more things regarding "Service Instancing and Sessions" that need to be considered while working with Transactions but this basic WCF tutorial is more focused on enabling transactions in simple scenario. In my later WCF article on Windows Communication Foundation Transactions on this blog, I'll discuss those concepts in more details.

ASYNCRONOUS METHOD'S DEFINTION AND DELEGATES AS CALLBACK METHOD

ASYNCRONOUS METHOD'S DEFINTION AND DELEGATES AS CALLBACK METHOD


An asynchronous method call is a method used in .NET programming that returns to the caller immediately before the completion of its processing and without blocking the calling thread.

When an application calls an asynchronous method, it can simultaneously execute along with the execution of the asynchronous method that performs its task. An asynchronous method runs in a thread separate from the main application thread. The processing results are fetched through another call on another thread.

Asynchronous methods help optimize the execution of resources resulting in scalable application. These are used to execute time-consuming tasks such as opening large files, connecting to remote computers, querying a database, calling Web services and ASP.NETWeb forms.

Asynchronous method call may also be referred to as asynchronous method invocation (AMI).

NET framework provides two design patterns to implement the asynchronous method, which are those using asynchronous delegates (IASyncResult objects) and events. Asynchronous delegates' pattern is more complex and provides flexibility, which makes it well-suited to various complex programming models. The event-based model is simple and should be used in most cases.

In the asynchronous delegates pattern, a delegate object uses two methods: BeginInvoke and EndInvoke. BeginInvoke has a list of parameters, which are similar to its wrapped function, along with two additional optional parameters; it returns the IAsyncResult object. EndInvoke returns two parameters (out and ref type) along with the IAsyncResult object. BeginInvoke is used for initiating the asynchronous call, whereas EndInvoke is used to retrieve the results of the asynchronous call.

Events-based asynchronous patterns use a class that has one or more methods, named MethodNameAsync, which have corresponding synchronous versions that execute on the current thread. Events-based patterns may also have a MethodNameCompleted event and MethodNameAsyncCancel method. This pattern enables the class to communicate with pending asynchronous operations using the delegate event model.




Using Delegates as Callback Methods

Used extensively in programming for Microsoft Windows, callback methods are used when you need to pass a function pointer to another function that will then call you back (via the passed pointer). An example would be the Win32 API EnumWindows function. This function enumerates all the top-level windows on the screen, calling the supplied function for each window. Callbacks serve many purposes, but the following are the most common: -
  • Asynchronous processing Callback methods are used in asynchronous processing when the code being called will take a good deal of time to process the request. Typically, the scenario works like this: Client code makes a call to a method, passing to it the callback method. The method being called starts a thread and returns immediately. The thread then does the majority of the work, calling the callback function as needed. This has the obvious benefit of allowing the client to continue processing without being blocked on a potentially lengthy synchronous call.
  • Injecting custom code into a class's code path Another common use of callback methods is when a class allows the client to specify a method that will be called to do custom processing. Let's look at an example in Windows to illustrate this. Using the Listbox class in Windows, you can specify that the items be sorted in ascending or descending order. Besides some other basic sort options, the Listbox class can't really give you any latitude and remain a generic class. Therefore, the Listbox class also enables you to specify a callback function for sorting. That way, when Listbox sorts the items, it calls the callback function and your code can then do the custom sorting you need.
Now let's look at an example of defining and using a delegate.In this example, we have a database manager class that keeps track of all active connections to the database and provides a method for enumerating those connections. Assuming that the database manager is on a remote server, it might be a good design decision to make the method asynchronous and allow the client to provide a callback method. Note that for a real-world application you'd typically create this as a multithreaded application to make it truly asynchronous. However, to keep the example simple-and because we haven't covered multithreading yet-let's leave multithreading out.
First, let's define two main classes: DBManager and DBConnection.
class DBConnection { } class DBManager { static DBConnection[] activeConnections; public delegate void EnumConnectionsCallback(DBConnection connection); public static void EnumConnections(EnumConnectionsCallback callback) { foreach (DBConnection connection in activeConnections) { callback(connection); } } }
The EnumConnectionsCallback method is the delegate and is defined by placing the keyword delegate in front of the method signature. You can see that this delegate is defined as returning void and taking a single argument: a DBConnection object. The EnumConnectionsmethod is then defined as taking an EnumConnectionsCallback method as its only argument. To call the DBManagerEnumConnections method, we need only pass to it an instantiated DBManagerEnumConnectionCallback delegate.
To do that, you new the delegate, passing to it the name of method that has the same signature as the delegate. Here's an example of that: -
DBManager.EnumConnectionsCallback myCallback = new DBManager.EnumConnectionsCallback(ActiveConnectionsCallback); DBManager.EnumConnections(myCallback);
Also note that you can combine this into a single call like so: -
DBManager.EnumConnections(new DBManager.EnumConnectionsCallback(ActiveConnectionsCallback));
That's all there is to the basic syntax of delegates. Now let's look at the full example application: -
using System; class DBConnection { public DBConnection(string name) { this.name = name; } protected string Name; public string name { get { return this.Name; } set { this.Name = value; } } } class DBManager { static DBConnection[] activeConnections; public void AddConnections() { activeConnections = new DBConnection[5]; for (int i = 0; i < 5; i++) { activeConnections[i] = new DBConnection("DBConnection " + (i + 1)); } } public delegate void EnumConnectionsCallback(DBConnection connection); public static void EnumConnections(EnumConnectionsCallback callback) { foreach (DBConnection connection in activeConnections) { callback(connection); } } } class Delegate1App { public static void ActiveConnectionsCallback(DBConnection connection) { Console.WriteLine("Callback method called for " + connection.name); } public static void Main() { DBManager dbMgr = new DBManager(); dbMgr.AddConnections(); DBManager.EnumConnectionsCallback myCallback = new DBManager.EnumConnectionsCallback(ActiveConnectionsCallback); DBManager.EnumConnections(myCallback); } }
Compiling and executing this application results in the following output: -
Callback method called for DBConnection 1 Callback method called for DBConnection 2 Callback method called for DBConnection 3 Callback method called for DBConnection 4 Callback method called for DBConnection 5

All details about assembly

Assembly : =>
รฐ  Assemblies are the building blocks of .NET Framework applications; they create the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions.
รฐ  An assembly is a collection of types and resources that are built to work together and make a logical unit of functionality.
รฐ  They are self-describing components that have no dependencies on registry entries.
รฐ  Assemblies enable zero-impact application installation. They also simplify uninstalling and replicating applications.
รฐ  Assemblies can be static or dynamic .

รฐ  Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in portable executable (PE) files.
รฐ  You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed.
รฐ  Assemblies are designed to simplify application deployment and to solve versioning problems that can occur with component-based applications.
รฐ  Many deployment problems have been solved by the use of assemblies in the .NET Framework. Because they are self-describing components that have no dependencies on registry entries, assemblies enable zero-impact application installation. They also simplify uninstalling and replicating applications.
รฐ   
รฐ  Note:- It contains code that the common language runtime executes. Microsoft intermediate language (MSIL) code in a portable executable (PE) file will not be executed if it does not have an associated assembly manifest.
To solve versioning problems, as well as the remaining problems that lead to DLL conflicts, the runtime uses assemblies to do the following:
รฐ  Enable developers to specify version rules between different software components.
รฐ  Provide the infrastructure to enforce versioning rules.
รฐ  Provide the infrastructure to allow multiple versions of a component to be run simultaneously (called side-by-side execution).
In general, a static assembly can consist of four elements:
  • The assembly manifest, which contains assembly metadata.
  • Type metadata.
  • Microsoft intermediate language (MSIL) code that implements the types.
  • A set of resources.
Only the assembly manifest is required, but either types or resources are needed to give the assembly any meaningful functionality.
There are several ways to group these elements in an assembly. You can group all elements in a single physical file, which is shown in the following illustration.
Single-file assembly

รฐ 

Assembly contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. An assembly manifest contains all the metadata needed to specify the assembly's version requirements and security identity having assembly name, version number, culture and strong name, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a standalone PE file that contains only assembly manifest information.
Global Assembly Cache:--
Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer.
Strong Name:รจ 
A strong name consists of the assembly's identity having its simple text name, version number, and culture information , as well as public key and a digital signature.
Strong name provides uniqueness to assembly by relying on unique key pairs. It indicates that an assembly generated with one private key has a different name than an assembly generated with another private key.
When you reference a strong-named assembly, you expect to get certain benefits, such as versioning and naming protection. If the strong-named assembly then references an assembly with a simple name, which does not have these benefits, you lose the benefits you would derive from using a strong-named assembly and revert to DLL conflicts. Therefore, strong-named assemblies can only reference other strong-named assemblies.
 Satellite Assemblyร  
  • A satellite assembly consists of resources specific to a given language. Using satellite assemblies, we can place resources for different languages in different assemblies and the correct assembly is loaded into memory only if the user elects to view the application in that language.
       ·   A single satellite assembly must include all the resources for a particular culture.
       ·   The satellite assembly must have the same name as the application, and must use the file name extension ".resources.dll". For example, if an application is named Example.exe, the name of each satellite assembly should be Example.resources.dll.
 Note that the satellite assembly name does not indicate the culture of its resource files. However, the satellite assembly appears in a directory that does specify the culture.
This means that you develop your application in a default language and add flexibility to react with change in the locale. Say, for example, you developed your application in an en-US locale. Now, your application has multilingual support. When you deploy your code in, say, India, you want to show labels, messages shown in the national language which is other than English.
Satellite assemblies give this flexibility. You create any simple text file with translated strings, create resources, and put them into the bin\debug folder. That's it. The next time, your code will read the CurrentCulture property of the current thread and accordingly load the appropriate resource.
This is called the hub and spoke model. It requires that you place resources in specific locations so that they can be located and used easily. If you do not compile and name resources as expected, or if you do not place them in the correct locations, the common language runtime will not be able to locate them. As a result, the runtime uses the default resource set.
Creating a Satellite Assembly
  1. Create a folder with a specific culture name (for example, en-US) in the application's bin\debug folder.
  2. Create a .resx file in that folder. Place all translated strings into it.
  3. Create a .resources file by using the following command from the .NET command prompt. (localizationsample is the name of the application namespace. If your application uses a nested namespace structure like MyApp.YourApp.MyName.YourName as the type of namespace, just use the uppermost namespace for creating resources files—MyApp.)
1.  resgen Strings.en-US.resx LocalizationSample.
  1.    Strings.en-US.resources
3.  al /embed:LocalizationSample.Strings.en-US.resources
  1.    /out:LocalizationSample.resources.dll /c:en-US
The above step will create two files, LocalizationSample.Strings.en-US.resources and LocalizationSample.resources.dll. Here, LocalizationSample is the name space of the application.
  1. In the code, find the user's language; for example, en-US. This is culture specific.
  2. Give the assembly name as the name of .resx file. In this case, it is Strings.
Using a Satellite Assembly
Follow these steps:
1.  Thread.CurrentThread.CurrentCulture =
  1.    CultureInfo.CreateSpecificCulture(specCult);
3.  Thread.CurrentThread.CurrentUICulture =
  1.    new CultureInfo(specCult);
5.  ResourceManager resMgr =
  1.    new ResourceManager(typeof(Form1).Namespace + "." +
  2.                        asmName, this.GetType().Assembly);
8.  btnTest.Text = resMgr.GetString("Jayant");
That's it. See how simple is it to create a satellite assembly and use it in your code.
Here's how to use a satellite assembly if your assembly is a strong named assembly. When you create an assembly with a string name, all the assemblies it refers to must have a strong name. This is true with a satellite assembly also. Here are the steps to create a strong named satellite assembly.
String Naming a Satellite Assembly
1.  al /embed:ExploreDotNet2005.Strings.en-US.resources
  1.    /out:ExploreDotNet2005.resources.dll /c:en-US
  2.    /template:../ExploreDotNet2005.exe /keyfile:../../..
  3.    /KeyPair.snk
Remember that /template is very important because it inherits the parent assembly manifest, and the strong name key pair must be the same as that for the running assembly. I've tried using different strong names for satellite assembly and executing the assembly. but it throws an exception.
Side-by-side execution is the ability to store and execute multiple versions of an application or component on the same computer. This means that you can have multiple versions of the runtime, and multiple versions of applications and components that use a version of the runtime, on the same computer at the same time. Side-by-side execution gives you more control over what versions of a component an application binds to, and more control over what version of the runtime an application uses.
Assembly Version Number
Each assembly has a version number as part of its identity. As such, two assemblies that differ by version number are considered by the runtime to be completely different assemblies. This version number is physically represented as a four-part string with the following format:
major version>.minor version>.build number>.revision>
For example, version 1.5.1254.0 indicates 1 as the major version, 5 as the minor version, 1254 as the build number, and 0 as the revision number.
The version number is stored in the assembly manifest along with other identity information, including the assembly name and public key, as well as information on relationships and identities of other assemblies connected with the application.
Delay Signing:==
Delay signing is a process of generating partial signature during development with access only to the public key. The private key can be stored securely and used to apply the final strong name signature just before shipping the project.
Scenerio:-
Delayed Signing = It is possible that you come to a situation where you have to give your assembly for further modification to an external person/developer, but you cannot give him the private key of the assembly, then how could he work? This problem has been solved by the Delayed Signing technique.
In this, we can skip the signing of the assembly with the private key and turn off the assembly verification. So now, the Assembly signs with only Public key. Now you can give the developer the assembly and public key only, there is no need of private key. This can be done like this, we have already created "StrongFile" assembly.
Process:-
With the help of sn.exe, we can extract the public key in the file:
Collapse | Copy Code
Syntax : sn -p [infile] [outfile] 
Extract the public key in key pair in [infile] and export it to the [outfile].
Collapse | Copy Code
sn /p FileKey.snk PublicKey.snk   
This will create the file "PublicKey.snk" which contains the public key of our assembly StrongFile.
Now it's time to edit the AssemblyInfo.cs like this:

Build Assembly StrongFile again.
Note = If you delayed signing of assembly by Properties Signing tab, then you need not edit AssemblyInfo.cs.
Now we have to turn off the verification process in this way:
sn /Vr StrongFile.dll
Then, you will get the following message:

Now you can send the developer your assembly with the public key file only, i.e., StrongFile.dll assembly with ThePublicKey.snk only. After he is done with his work, you can reassign the assembly with a private key like this:
sn /R StrongFile.dll FileKey.snk

Difference between value type and reference type

Difference between Value Type and Reference Type :
Oct 18, 2011
Value type Reference type Value type they are stored on stack Reference type they are stored on heap When passed as value type new copy is created and passed so changes to variable does not get reflected back When passed as Reference type then reference of that variable is passed so changes to variable does get reflected back Value type store real data Reference type store reference to the data. Value types are faster in access Reference types are slower in access. Value type consists of primitive data types, structures, enumerations. Reference type consists of class, array, interface, delegates Value types derive from System.ValueType Reference types derive from System.Object Value types can not contain the value null. Reference types can contain the value null.

Shallow Copy And Deep Copy With Example

Shallow Copy: 

Shallow copy is the way copying an object's value type fields bit by bit into target object and object's reference types are copied as references into the target object but not the referenced object itself. This can be done in C# using MemberwiseClone() method on an object. As in MSDN, "The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object."

Example: the following clsShallow class is to be cloned which includes value types (like Age) and ref types (like EmpSalary is a class):


public class clsShallow
{
public static string CompanyName = "My Company";
public int Age;
public string EmployeeName;
public clsRefSalary EmpSalary;
public clsShallow CreateShallowCopy(clsShallow inputcls)
{
return (clsShallow)inputcls.MemberwiseClone();
}
}
public class clsRefSalary
{
public clsRefSalary(int _salary)
{ Salary = _salary; }
public int Salary; }

Now let us debug and trace the outputs to do shallow copy using the CreateShallowCopy() method.
First, use the following code to call the CreateShallowCopy method from other classes.

// Creates an instance of clsShallow and assign values to its fields.
clsShallow objshallow = new clsShallow();
objshallow.Age = 25;
objshallow.EmployeeName = "Ahmed Eid";
// add the ref value to the objshallow
clsRefSalary clsref = new clsRefSalary(1000);
objshallow.EmpSalary = clsref;
// Performs a shallow copy of m1 and assign it to
m2. clsShallow m2 = objshallow.CreateShallowCopy(objshallow);
// then modify the clsref salary value to be 2000 clsref.Salary = 2000;
// so the m1 object salary value become 2000 int EmpSalary = objshallow.EmpSalary.Salary;

After assigning the values (value and ref types) to the object objShallow and before doing the shallow copy, the values are (for the current object value): Age: 25 (value type), EmpSalry: has salary value of 1000 (ref type).

then do the shallow copy and modify the value of clsref.salary, reference field type, then check the value of m2, the newly created object (ref and value fields) again.

The values are (for the newly created object): Age: 25 (value type), a new copy of the objShallow object; EmpSalry: has a salary value of 2000 (ref type), a reference to objShallow.EmpSalry object, which is also referenced to the clsref object.
Note: values of m2.EmpSalry and clsref are the same after modifying the clsref values (reference type concept).

Deep Copy: 

Deep copy is the way of copying an object completely bit-by-bit i.e. Deep copy copies value of every field inside an object. For nested objects(objects that contain other objects), deep copy creates new instances for each object inside nested object and copies all the values for fields inside them.


[Serializable] // serialize the classes in case of deep copy public class clsDeep { public static string CompanyName = "My Company"; public int Age; public string EmployeeName; public clsRefSalary EmpSalary; public clsDeep CreateDeepCopy(clsDeep inputcls) { MemoryStream m = new MemoryStream(); BinaryFormatter b = new BinaryFormatter(); b.Serialize(m, inputcls); m.Position = 0; return (clsDeep)b.Deserialize(m); } } [Serializable] public class clsRefSalary { public clsRefSalary(int _salary) { Salary = _salary; } public int Salary; }
Now let us debug and trace the outputs to do deep copy using the CreateDeepCopy() method.
First, use the following code to call the CreateDeepCopy method from other classes.
Collapse | Copy Code
// Creates an instance of clsDeep and assign values to its fields. clsDeep objdeep = new clsDeep(); objdeep.Age = 25; objdeep.EmployeeName = "Ahmed Eid"; // add the ref value clsRefSalary clsref = new clsRefSalary(1000); objdeep.EmpSalary = clsref; // Performs a shallow copy of m1 and assign it to m2. clsDeep m2 = objdeep.CreateDeepCopy(objdeep); // then modify the clsref salary value to be 2000 clsref.Salary = 2000; // so the m1 object salary value become 2000 int EmpSalary = objdeep.EmpSalary.Salary;

Difference Between Static Constructor and private constructor


a.) The static constructor will only be executed once while the private constructor will be executed each time it is called.
b. ) The static constructor cannot have parameters but The private Constructor may have parameters
c.) A static constructor is called before the first instance is created. So it’s kind of global initialize.
    Private constructor is called after the instance of the class is created.
d.) A class can have only one static constructor but a class can have multiple private constructors.
e.) Static constructor can not be overloaded but private constructor can be.

web portal

What is a web portal and what types of portals
A portal is a web site that acts as a multi sources or single source for all information on a specific domain. The Web portal offers the user a broad array of information, arranged in a way that is most convenient for the user to access. When designed, implemented and maintained correctly a web portal becomes the starting or entry point of a web user introducing him into various information, resources and other sites in the internet. It has the power to draw together a common group of people, common on the basis of their age, profession, location etc.
Portals are browser-based applications that enable activities including connecting business processes within the business and across the supply chain by unifying access to structured and unstructured data, integrating applications to support the business processes as well as providing access to real-time, current and consistent information.
Popular Portals are Yahoo, MSN etc.

Types of portals
The portals can be differentiated on the basis of their content and intended users.
There are a different types of portals, most of the time we will refer to a portal as a place packed with enterprise information, it is important to know what type of portal you want to build. Surely, some portals may focus on an other type of portal.
They can be categorized into:

- Vertical Portals
These are web portals which focus only on one specific industry, domain or vertical. Vertical portals provide tools, information, articles, research and statistics on the specific industry or vertical. As the web has become a standard tool for business.
There are innumerable possibilities for establishing special vertical portals on the market. The numerous solutions can be divided into 2 major groups that partially overlap:
*- Corporate Portals:
provide personalized access to selected information of a specific company
*- Commerce Portals:
support business-to-business and business-to-consumer e-commerce

- Horizontal Portals
These are web portals which focus on a wide array of interests and topics. They focus on general audience and try to present something for everybody. Horizontal portals try act as an entry point of a web surfer into the internet, providing content on the topic of interest and guiding towards the right direction to fetch more related resources and information. Classic examples of horizontal portals are yahoo.commsn.com etc which provide visitors with information and on a wide area of topics.

- Enterprise Portals
These are portals developed and maintained for use by members of the intranet or the enterprise network. In today’s demanding business enterprise the key to productivity of the employees depends on access to timely information and resources. The most common implementation of enterprise portals focus on providing employees with this information on a regularly updated manner along with document management system, availability of applications on demand, online training courses and web casts etc along with communication in the form of emails, messaging, web meetings etc.

- Knowledge Portals
Knowledge portals increase the effectiveness of knowledge workers by providing easy access to information that is necessary or helpful to them in one or more specific roles. Knowledge portals are not mere intranet portals since the former are supposed to provide extra functionality such as collaboration services, sophisticated information discovery services and a knowledge map.

- Corporate Portals
An corporate portal provides personalized access to an appropriate range of information about a particular company.
Corporate portals have become one of the hottest new technologies of the Internet. Initially called intranet portals - corporate portals existing for the benefit of the company’s own employees, this set of technologies has developed to assist and provide access to a company’s business partners (suppliers, customers) as well.
As opposed to public web portals, corporate portals aim at providing a virtual workplace for each individual using them - executives, employees, suppliers, customers, third-party service providers. Rather than offering access to consumer goods, services, and information, corporate portals are designed to give each individual using them access to all of the information, business applications, and services needed to perform their jobs.
A company’s public Website itself is not automatically a corporate portal. It can become one if the Website provides personalization and navigation functionality, as many are beginning to do.

- Market space Portals
Market space portals exist to support the business-to-business and business-to-customer e-commerce, software support for e-commerce transactions and ability to find and access rich information about the products on sale also, ability to participate in discussion groups with other vendors and/or buyers

All the above definitions have merits when it comes to explaining what a portal is and what a portal can be, in fact a mixture of the definitions to create a vertical portal in that you are serving a niche sector of a market - but you may determine that you wish to make it content centric and include profiles to enhance the user experience - and you may or may not decide that users will be able to read information only (making it an Information type of portal) or you may elect to allow them to collaborate on content depending on the nature of the portal.