Search

Creating a Windows Service for Microsoft Dynamics CRM 4.0

When it comes to automating things in Microsoft Dynamics CRM, you usually create server-side logic in workflows or plug-ins. Workflows are great to perform simple tasks and can be greatly enhanced with custom workflow activities. However, they always need an entity context. Plug-Ins are great as well, but they are more complex. They also require an entity context. What if you want to automate a data import or export, or you want to schedule other tasks that are not triggered by an action in CRM?
Windows Services
A good alternative to workflows and plug-ins is a Windows Service and as I haven't seen an example of it so far, I'm doing it now, because it's really easy. Since I have my new notebook, I only have Visual Studio 2008 installed. If you are running an older version, you should still be able to follow this article, because the Windows Service template was available at least since Visual Studio 2003.
Create a new project and select the Windows Service template: 
New Project
Note that I'm using the .NET Framework 3.5 (dropdown in the top right corner). I do have the .NET Framework installed on my server machines, so I'm not limiting me to the 3.0 Framework as recommended for other CRM server development. You can choose whatever you are comfortable with though. I'm not even sure if I'm using .NET 3.5 features, but as the application is not running in the context of CRM, I have the freedom of choice.
Everything else is a standard project setup, so choose a name, location and solution name and hit the OK button to create the new project.
Empty Project
You don't get very much when creating a new service project. The Program.cs file contains the startup code like in a console or Windows forms application. However, the code is slightly different:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace CrmOpportunityService
{
    static class Program
    {
        /// 
        /// The main entry point for the application.
        /// 
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
               new Service1() 
            };
            ServiceBase.Run(ServicesToRun);
        }
    }
}

The ServiceBase class is used to declare the services to run and ServiceBase.Run actually starts them. Each service implementation must inherit from ServiceBase like the Service1 class that was auto-generated as well:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace CrmOpportunityService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }
        protected override void OnStart(string[] args)
        {
        }
        protected override void OnStop()
        {
        }
    }
}

There are two empty methods generated for us: OnStart and OnStop. Obviously these are called when the service is started or stopped. However, there are more methods you can implement, like OnPause, OnContinue or OnShutdown. I'm adding a few of them later in this article, but for now let's start with a basic implementation. The goal of this service is to write an export file whenever opportunities were created or updated. The CRM logic will be pretty simple here, because the sample itself concentrates on the service.
Before writing any code, let's change some service properties. Open the Service1.cs in design mode and change the (Name) and ServiceName properties:
Service Properties
The (Name) property defines the class name of our service and when changing it to CrmOpportunityService, then the Service1 class is renamed to CrmOpportunityService as well. The ServiceName property is the display name you see when looking at the Service Manager window. The various Canxxx properties define the characteristics of this service. If you want to support Pause and Continue, then set CanPauseAndContinue to true and implement the appropriate methods in the service class.
Finally, I renamed Service.cs to CrmOpportunityService.cs, because I like file names to be the same as the contained class. Now you can compile the project and you get a CrmOpportunityService.exe, which is your service. Great, isn't it?
Of course it's not. Even at this very early stage you might ask how to test the application and you are right. The most natural thing is hitting F5 to run the application:
Cannot start service
Well, that seems correct, but it doesn't really help when writing code. You don't want installing the application as a service to see if it works, then stop and uninstall to go back to development. So here's a very easy workaround:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
namespace CrmOpportunityService
{
    static class Program
    {
        /// 
        /// The main entry point for the application.
        /// 
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new CrmOpportunityService() 
            };
#if RUN_IN_VS
            CrmOpportunityService service = new CrmOpportunityService();
            service.StartService();
#else
            ServiceBase.Run(ServicesToRun);
#endif
        }
    }
}

I'm using a new conditional compilation symbol named RUN_IN_VS and defined it in the debug configuration:
RUN_IN_VS
You could also check if the DEBUG symbol is defined, but I decided to go for a new symbol. The release build does not define the RUN_IN_VS symbol, so when compiling the release version, you can safely install the service and it will act as a service.
The ServiceBase class does not have a StartService method and I changed the service implementation as well:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace CrmOpportunityService {
public partial class CrmOpportunityService : ServiceBase {
public CrmOpportunityService() {
            InitializeComponent();
        }
protected override void OnStart(string[] args) {
this.StartService();
        }
protected override void OnStop() {
        }
public void StartService() {
        } 
    }
} 

OnStart is called when Windows starts our service and it calls the same StartService method we're calling directly from the main program when running in Visual Studio. You can now set a breakpoint on the StartService method and successfully run the code.
There's one thing missing though: as soon as the StartService method returns, the service is done. A real service, however, should run until it's stopped. If you compile the code in release mode, install the service and start it, then it will instantly go into the stopped state. To prevent it, we need a main execution thread.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace CrmOpportunityService {
public partial class CrmOpportunityService : ServiceBase {
public CrmOpportunityService() {
            InitializeComponent();
        }
protected override void OnStart(string[] args) {
this.StartService();
        }
protected override void OnStop() {
        }
public void StartService() {
        } 
    }
} 

The difference to the previous implementation is the MainExecutionThread. It's initialized when StartService is called and its target is the Run method. The Run method executes whatever the service is intended to do, until the StopCommandReceived property is set to true. In the current implementation this can only happen if OnStop is called. This is done by Windows when you manually stop a service or Windows shuts down. But each service also has a Stop method, defined in the base ServiceBase class. This allows a quick test of our implementation, by slightly changing the main program code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
namespace CrmOpportunityService {
static class Program {
/// 
/// The main entry point for the application.
/// 
static void Main() {
ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
new CrmOpportunityService() 
            };
#if RUN_IN_VS
CrmOpportunityService service = new CrmOpportunityService();
            service.StartService();
Thread.Sleep(5000);
            service.Stop();
#else
            ServiceBase.Run(ServicesToRun);
#endif
        }
    }
} 

After the service was started with the call to the StartService method, the thread waits for five seconds until it calls the service's Stop method, which then terminates the MainExecutionThread. When running the code you will notice that it stops after 5-7 seconds. This is because the MainExecutionThread itself sleeps for two seconds after it has done all of its work, which isn't anything at this time. So every two seconds it looks at the StopCommandReceived property. After 5 seconds the main application calls the Stop method of our service and the implementation in ServiceBase calls the OnStop method in our service, which finally sets StopCommandReceived to true. When that happens, our MainExecutionThread (the Run method) most probably is in its sleep state, so besides the 5 seconds from the main application, another 0-2 seconds are added from the Thread.Sleep(2000) in the Run method, giving a total of 5-7 seconds.
This was just for showing the basic idea. If our Run method was doing something valuable, then five seconds wouldn't be enough. Here's an easy fix:
#if RUN_IN_VS
CrmOpportunityService service = new CrmOpportunityService();
            service.StartService();
Thread.Sleep(Timeout.Infinite);
            service.Stop();
#else
            ServiceBase.Run(ServicesToRun);
#endif 




Passing Timeout.Infinite to Thread.Sleep will cause the thread to wait forever, giving us enough time to test our service implementation. You can stop the execution by selecting the Stop Debugging command in Visual Studio. But as I want to have a real test, even while developing, including pause and continue, it's not good enough and we have to find another solution. Before doing that, it's time to implement something else though.

Logging


A Windows Service, a Plug-In and a Workflow are all server-based code. And server-based code doesn't have any UI. To know what your application is doing, you have to implement a good logging mechanism. This is often ignored while developing, because the debugger tells you most of what you need to know. But at some time you deploy the application in a production environment and sooner or later there will be a problem. Without any logging mechanism it's very difficult to troubleshoot, so add it at a very early stage.
A Windows service by default logs to the Windows Event Log. While developing though, it's too time-consuming looking at the event viewer. At least in my opinion. So we need at least two different logging implementations, one for the release build and one for debugging.
My first implementation is really easy and consists of a logging interface and a simple log implementation writing to the Visual Studio output window. Here's the interface:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace CrmOpportunityService {
public interface ILog {
void Add(EventLogEntryType type, string message);
void Add(EventLogEntryType type, string message, params object[] args);
void Add(EventLogEntryType type, Exception x);
    }
}
I'm using the EventLogEntryType enumeration from the System.Diagnostics namespace to signal the event type, because it's used when writing to the Windows event log. The Visual Studio logger is as simple as the interface:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Web.Services.Protocols;
using System.Net;
namespace CrmOpportunityService {
public class VsDebugLog : ILog {
public VsDebugLog() {
        }
        #region ILog Members
public void Add(System.Diagnostics.EventLogEntryType type, string message) {
Debug.WriteLine(message, type.ToString());
        }
public void Add(System.Diagnostics.EventLogEntryType type, string message, params object[] args) {
Debug.WriteLine(string.Format(message, args), type.ToString());
        }
public void Add(System.Diagnostics.EventLogEntryType type, Exception x) {
if (x is SoapException) {
SoapException e = x as SoapException;
string details = (e.Detail != null) ? e.Detail.InnerXml : "none";
Debug.WriteLine(e.Message + "\r\nDetails: " + details, type.ToString());
            }
Debug.WriteLine(x.ToString());
        }
        #endregion
    }
}
The only special thing when logging an exception is the check for a SoapException. If something goes wrong when calling the CRM web service, a SoapException is thrown and the exception message usually contains "Server was unable to process request", while the details are available in the Details node and it's invaluable to include these details in the log file.
I'm adding appropriate code for writing to the Windows event log later. While still in development mode and far away from a release version, I added the following to the service implementation:
ILog Log { get; set; }
public CrmOpportunityService() {
   InitializeComponent();
this.Log = new VsDebugLog();
}
private void Run() {
this.StopCommandReceived = false;
this.Log.Add(EventLogEntryType.Information, "Service started.");
while (!this.StopCommandReceived) {
try {this.Log.Add(EventLogEntryType.Information, "Executing job");// do workthis.Log.Add(EventLogEntryType.Information, "Finished job");
      }
catch (Exception x) {this.Log.Add(EventLogEntryType.Error, x);
      }

Thread.Sleep(2000);
   }
this.MainExecutionThread = null;
this.Log.Add(EventLogEntryType.Information, "Service stopped.");
}
It's up to you what to include in the log file, but I wanted to have some output and added more log entries than needed. The entire "processing" code is wrapped into a try-catch block. If the code we are going to implement throws an exception that we haven't handled elsewhere, it is written to the log and the service doesn't break.
Running the code in the Visual Studio environment now produces the following output in the output window:
'CrmOpportunityService.vshost.exe' (Managed): Loaded 'D:\BLOG\CRM 4.0 Samples\CrmOpportunityService\CrmOpportunityService\bin\Debug\CrmOpportunityService.exe', Symbols loaded.
'CrmOpportunityService.vshost.exe' (Managed): Loaded 'C:\Windows\assembly\GAC_MSIL\System.Configuration\2.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Information: Service started.
Information: Executing job
Information: Finished job
Information: Executing job
Information: Finished job
Information: Executing job
Information: Finished job
Information: Stop command received.
The thread 0x1f8 has exited with code 0 (0x0).
The thread 0x1b7c has exited with code 0 (0x0).
Information: Service stopped.
The thread 0x1584 has exited with code 0 (0x0).
The thread 0x1b44 has exited with code 0 (0x0).
The program '[5068] CrmOpportunityService.vshost.exe: Managed' has exited with code 0 (0x0).
Again, it's a very simple log implementation, but you can see what commands are sent to the service, how it's working and behaving. Still not good enough, because I want to control the service the way it's used when deployed. So let's add our own service control manager application.
The Service Control Manager
It's a simple Windows form with four buttons on it for starting, stopping, pausing and resuming the service. I'm not explaining how to create a Windows Forms application. Instead I'm just showing the relevant code, which, in the beginning, only has implementations for the Start and Stop buttons:
public partial class ServiceControlManagerForm : Form, ILog {
   CrmOpportunityService.CrmOpportunityService Service { get; set; }
StringBuilder NewLogEntries { get; set; }
object NewLogEntriesLock { get; set; }
public ServiceControlManagerForm() {
      InitializeComponent();
this.btnStartService.Enabled = true;
this.btnStopService.Enabled = false;
this.btnPauseService.Enabled = false;
this.btnContinueService.Enabled = false;
this.NewLogEntries = new StringBuilder();
this.NewLogEntriesLock = new object();
   }
private void btnStartService_Click(object sender, EventArgs e) {
if (this.Service == null) {
this.btnStartService.Enabled = false;
this.btnStopService.Enabled = true;
this.btnPauseService.Enabled = true;
this.btnContinueService.Enabled = false;
this.Service = new CrmOpportunityService.CrmOpportunityService(this);
this.Service.StartService();
      }
   }
private void btnStopService_Click(object sender, EventArgs e) {
if (this.Service != null) {
this.btnStartService.Enabled = true;
this.btnStopService.Enabled = false;
this.btnPauseService.Enabled = false;
this.btnContinueService.Enabled = false;
this.Service.Stop();
this.Service = null;
      }
   }
private void logTimer_Tick(object sender, EventArgs e) {
if (this.NewLogEntries.Length > 0) {
lock (this.NewLogEntriesLock) {
this.txtLog.Text = this.txtLog.Text + this.NewLogEntries.ToString();
this.txtLog.SelectionStart = this.txtLog.Text.Length - 1;
this.txtLog.SelectionLength = 0;
this.txtLog.ScrollToCaret();
this.NewLogEntries = new StringBuilder();
         }
      }
   }
private void AddLogEntry(string message) {
lock (this.NewLogEntriesLock) {
this.NewLogEntries.AppendLine(message);
      }
   }
   #region ILog Members
public void Add(System.Diagnostics.EventLogEntryType type, string message) {
this.AddLogEntry(type.ToString() + ": " + message);
   }
public void Add(System.Diagnostics.EventLogEntryType type, string message, params object[] args) {
this.AddLogEntry(type.ToString() + ": " + string.Format(message, args));
   }
public void Add(System.Diagnostics.EventLogEntryType type, Exception x) {
if (x is SoapException) {
         SoapException e = x as SoapException;
string details = (e.Detail != null) ? e.Detail.InnerXml : "none";
this.AddLogEntry(type.ToString() + ": " + e.Message + "\r\nDetails: " + details);
      }
this.AddLogEntry(x.ToString());
   }
   #endregion
}
The event handlers for the start and stop buttons should be self-explanatory. The important thing is the implementation of the ILog interface, allowing the form to serve as a log for our service implementation. To make it available in the service class, I added a second constructor and modified the first implementation:
public CrmOpportunityService()
    : this(new VsDebugLog()) {
}
public CrmOpportunityService(ILog log) {
    InitializeComponent();
this.Log = log;
}
Besides the four buttons on the form, there's also a timer control raising the Tick event every 250ms. You cannot access a Windows form from another thread and as the log messages are generated from the MainExecutionThread in our service class, it's not possible to simply append the messages to the text field, which is used to display them. Instead, I'm using a StringBuilder object and add the new messages to it. The logTimer_Tick method checks for new messages, adds them to the text box and removes them from the buffer.  The lock statements are used to synchronize this process.
Running the form now allows starting and stopping the service and it also shows the log messages:
Service Control Manager
Supporting Pause and Continue
Now let's add pause and continue to the code. All we have to do is overriding the OnPause and OnContinue methods in the service class and add appropriate handling to our main execution thread:
namespace CrmOpportunityService {
public partial class CrmOpportunityService : ServiceBase {
      ...
bool Paused { get; set; }
      ...
protected override void OnPause() {this.Log.Add(EventLogEntryType.Information, "Pause command received.");this.Paused = true;
      }
protected override void OnContinue() {this.Log.Add(EventLogEntryType.Information, "Continue command received.");this.Paused = false;
      }
public void PauseService() {this.OnPause();
      }
public void ContinueService() {this.OnContinue();
      }

private void Run() {
this.StopCommandReceived = false;
this.Paused = false;
this.Log.Add(EventLogEntryType.Information, "Service started.");
while (!this.StopCommandReceived) {
if (!this.Paused) {
try {
this.Log.Add(EventLogEntryType.Information, "Executing job");
// do work
this.Log.Add(EventLogEntryType.Information, "Finished job");
               }
catch (Exception x) {
this.Log.Add(EventLogEntryType.Error, x);
               }
            }
Thread.Sleep(2000);
         }
this.MainExecutionThread = null;
this.Log.Add(EventLogEntryType.Information, "Service stopped.");
      }
   }
}
OnPause and OnContinue simply set a variable to either true or false and the Run method stops its execution when entering the pause state. PauseService and ContinueService are helper methods, allowing us to execute the Pause and Continue commands from our own Service Control Manager application. The last step is adding appropriate code to the Pause and Continue buttons in the Service Control Manager:
private void btnPauseService_Click(object sender, EventArgs e) {
if (this.Service != null) {
this.btnStartService.Enabled = false;
this.btnStopService.Enabled = true;
this.btnPauseService.Enabled = false;
this.btnContinueService.Enabled = true;
this.Service.PauseService();
   }
}
private void btnContinueService_Click(object sender, EventArgs e) {
if (this.Service != null) {
this.btnStartService.Enabled = false;
this.btnStopService.Enabled = true;
this.btnPauseService.Enabled = true;
this.btnContinueService.Enabled = false;
this.Service.ContinueService();
   }
}
To let Windows know that our service supports Pause and Continue, open the service class in the design view and set the CanPauseAndContinue property to true:
Pause and Continue
Implementing the CRM code
We can now start, pause, continue and stop our service and do the CRM implementation. The service is intended to run on a CRM server machine (though you can run it on any machine) and as any CRM 4.0 server has the CRM SDK assemblies installed in the GAC, I'm using them in the service project instead of adding a web reference. However, you can also add a reference to the CRM web services and use it instead of the SDK assemblies.
I'm entirely separating the CRM code from the service code to make the service framework more reusable:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace CrmOpportunityService {
public class CrmOpportunityExport {
ILog Log { get; set; }
public CrmOpportunityExport(ILog log) {
this.Log = log;
      }
public void Execute() {
      }
   }
}
The only modification to the service code is in the Run method:
private void Run() {
this.StopCommandReceived = false;
this.Paused = false;
this.Log.Add(EventLogEntryType.Information, "Service started.");
while (!this.StopCommandReceived) {
if (!this.Paused) {
try {
this.Log.Add(EventLogEntryType.Information, "Executing job");
CrmOpportunityExport export = new CrmOpportunityExport(this.Log);
            export.Execute();

this.Log.Add(EventLogEntryType.Information, "Finished job");
         }
catch (Exception x) {
this.Log.Add(EventLogEntryType.Error, x);
         }
      }
Thread.Sleep(2000);
   }
this.MainExecutionThread = null;
this.Log.Add(EventLogEntryType.Information, "Service stopped.");
}
The CrmOpportunityExport class of course needs access to the log file, which is the reason why I'm passing the log instance in the constructor. The Execute is quite simple, but I'm going to explain some helper methods in more detail:
public void Execute() {
DateTime now = DateTime.Now;
CrmService service = new CrmService();
   service.Url = this.Configuration.ServerUrl + "/2007/crmservice.asmx";
   service.UseDefaultCredentials = true;
   service.CrmAuthenticationTokenValue = new CrmAuthenticationToken();
   service.CrmAuthenticationTokenValue.AuthenticationType = 0;
   service.CrmAuthenticationTokenValue.OrganizationName = this.Configuration.Organization;
QueryExpression query = new QueryExpression(EntityName.opportunity.ToString());
   query.ColumnSet.AddColumns("estimatedclosedate", "estimatedvalue", "name", "opportunityid");
   query.Criteria.AddCondition("modifiedon", ConditionOperator.LessEqual, now.ToString("s"));
if (this.Configuration.LastRun > DateTime.MinValue) {
      query.Criteria.AddCondition("modifiedon", ConditionOperator.GreaterThan, this.Configuration.LastRun.ToString("s"));
   }
BusinessEntityCollection opportunities = service.RetrieveMultiple(query);
if (opportunities.BusinessEntities.Count == 0) {
this.Log.Add(EventLogEntryType.Information, "No new or updated opportunities since " + this.Configuration.LastRun);
   }
else {
this.Log.Add(EventLogEntryType.Information, opportunities.BusinessEntities.Count + " new or updated opportunities since " + this.Configuration.LastRun);
string fileContent = this.BuildExportFileContent(opportunities);
this.WriteExportFile(fileContent);
this.Configuration.LastRun = now;
   }
}
The code retrieves all opportunities modified since the last export and this information has to be persisted. The easiest way to configure a service is the registry and I created a helper class reading the configuration values:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Configuration;
using System.Diagnostics;
namespace CrmOpportunityService {
public class ServiceConfiguration {
public const string ServiceRegistryRoot = @"Software\Stunnware\Samples\CrmOpportunityExport";
private DateTime _lastRun;
public string ServerUrl { get; private set; }
public string Organization { get; private set; }
public string ExportDirectory { get; private set; }
public int TimeoutBetweenRunsInSeconds { get; private set; }
public ServiceConfiguration(ILog log) {
RegistryKey serviceRoot = Registry.LocalMachine.OpenSubKey(ServiceRegistryRoot);
if (serviceRoot == null) {
throw new ConfigurationErrorsException("The HKLM\\" + ServiceRegistryRoot + " key does not exist in the registry.");
         }
this.ServerUrl = this.ReadNonEmptyStringValue(serviceRoot, "ServerUrl");
this.Organization = this.ReadNonEmptyStringValue(serviceRoot, "Organization");
this.ExportDirectory = this.ReadNonEmptyStringValue(serviceRoot, "ExportDirectory");
object lastRun = serviceRoot.GetValue("LastRun");
if (lastRun != null) {
long ticks = long.Parse(lastRun.ToString());
this.LastRun = new DateTime(ticks);
         }
else {
this.LastRun = DateTime.MinValue;
            log.Add(EventLogEntryType.Warning, "The LastRun value does not exist in the HKLM\\" + ServiceConfiguration.ServiceRegistryRoot + " key of the registry. Exporting all opportunities.");
         }
object timeoutBetweenRunsInSeconds = serviceRoot.GetValue("TimeoutBetweenRunsInSeconds");
if (timeoutBetweenRunsInSeconds != null) {
this.TimeoutBetweenRunsInSeconds = int.Parse(timeoutBetweenRunsInSeconds.ToString());
         }
else {
this.TimeoutBetweenRunsInSeconds = 600;
            log.Add(EventLogEntryType.Warning, "The TimeoutBetweenRunsInSeconds value does not exist in the HKLM\\" + ServiceConfiguration.ServiceRegistryRoot + " key of the registry. Setting to " + this.TimeoutBetweenRunsInSeconds + " seconds.");
         }
      }
private string ReadNonEmptyStringValue(RegistryKey serviceRoot, string name) {
string value = (string)serviceRoot.GetValue(name);
if (string.IsNullOrEmpty(value)) {
throw new ConfigurationErrorsException("The " + name + " value does not exist in the HKLM\\" + ServiceRegistryRoot + " key of the registry.");
         }
return value;
      }
public DateTime LastRun {
get {
return this._lastRun;
         }
set {
this._lastRun = value;
RegistryKey serviceRoot = Registry.LocalMachine.CreateSubKey(ServiceRegistryRoot);
            serviceRoot.SetValue("LastRun", value.Ticks);
         }
      }
   }
}
Remember that the code will run on a server machine without any UI. Good error messages are a live saver when it comes to troubleshooting, so add as much information as possible. If a customer reads the Windows Event Log and finds a message that the CRM organization isn't configured and you also tell exactly where to add this information, then they may be able to solve the problem themselves. If you don't provide this information, then you most likely get a support call.
The ServiceConfiguration class introduces a new setting, the TimeoutBetweenRunsInSeconds. It is used in the main execution thread and controls how long the thread sleeps after having done it's job:
private void Run() {
this.StopCommandReceived = false;
this.Paused = false;
this.Log.Add(EventLogEntryType.Information, "Service started.");
ServiceConfiguration configuration = null;
try {
      configuration = new ServiceConfiguration(this.Log);
   }
catch (Exception x) {
this.Log.Add(EventLogEntryType.Error, x);
   }
if (configuration != null) {
int remainingSeconds = 0;
while (!this.StopCommandReceived) {
Thread.Sleep(1000);
         remainingSeconds--;

if (!this.Paused && (remainingSeconds <= 0)) {
try {
this.Log.Add(EventLogEntryType.Information, "Executing job");
CrmOpportunityExport export = new CrmOpportunityExport(this.Log);
               export.Execute();
this.Log.Add(EventLogEntryType.Information, "Finished job");
            }
catch (Exception x) {
this.Log.Add(EventLogEntryType.Error, x);
            }
            remainingSeconds = configuration.TimeoutBetweenRunsInSeconds;
         }              
      }
   }
this.MainExecutionThread = null;
this.Log.Add(EventLogEntryType.Information, "Service stopped.");
}
The previous implementation suspended the thread for 2000ms, which is acceptable when responding to a stop command. But say the service is configured to wait for 10 minutes after it has done its job, then stopping the service may also take up to 10 minutes, because the check for StopCommandReceived is executed after the sleep phase. To prevent such things, the thread is sleeping for one second and after that decrements the remainingSeconds variable. If it's down to 0, the job is executed and remainingSeconds is reset to the value configured in the registry.
The above implementation will instantly start the job, which, in most of the cases, is what you want. But it's just initializing remainingSeconds with configuration.TimeoutBetweenRunsInSeconds instead of setting it to 0 to wait in the beginning as well. You can easily add a new registry flag to even make it configurable.  
All that's left is the export file generation, which is a very basic implementation:
private void WriteExportFile(string content) {
string filename = "ex" + DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss") + ".csv";
string path = Path.Combine(this.Configuration.ExportDirectory, filename);
FileInfo file = new FileInfo(path);
if (!file.Directory.Exists) {
      file.Directory.Create();
   }
using (FileStream fs = file.OpenWrite()) {
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8)) {
         w.Write(content);
this.Log.Add(EventLogEntryType.Information, "Export file written to " + file.FullName);
      }
   }
}
private string BuildExportFileContent(BusinessEntityCollection opportunities) {
StringBuilder fileContent = new StringBuilder();
   fileContent.AppendLine("opportunityid;name;estimatedclosedate;estimatedvalue");
foreach (opportunity o in opportunities.BusinessEntities) {
string estimatedCloseDate = (o.estimatedclosedate == null) ? null : o.estimatedclosedate.UniversalTime.ToString("u");
decimal estimatedValue = (o.estimatedvalue == null) ? 0 : o.estimatedvalue.Value;
      fileContent.AppendLine(o.opportunityid.Value + ";" + o.name + ";" + estimatedCloseDate + ";" + estimatedValue);
   }
return fileContent.ToString();
}
To test the code in development mode, we first run our Service Control Manager without configuring any values in the registry. This is just a test to see if our error handling is correct:
Exception in Log
And the final test is adding the values to the registry:
Registry Settings
After the values have been configured, the service should work in your development environment:
Done
Supporting the Windows Event Log
Now it's time to plan for production. Our own Service Control Manager is great to test the service, but when running as a service, we cannot log to a Windows forms application. We have to implement Windows Event Logging, but you will see that it's damned easy:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Web.Services.Protocols;
using System.Net;
namespace CrmOpportunityService {
public class WindowsEventLog : ILog {
EventLog Log { get; set; }
public WindowsEventLog(EventLog log) {
this.Log = log;
      }
      #region ILog Members
public void Add(System.Diagnostics.EventLogEntryType type, string message) {
this.Log.WriteEntry(message, type);
      }
public void Add(System.Diagnostics.EventLogEntryType type, string message, params object[] args) {
this.Log.WriteEntry(string.Format(message, args), type);
      }
public void Add(System.Diagnostics.EventLogEntryType type, Exception x) {
if (x is SoapException) {
SoapException e = x as SoapException;
string details = (e.Detail != null) ? e.Detail.InnerXml : "none";
this.Log.WriteEntry(e.Message + "\r\nDetails: " + details, type);
         }
      }
      #endregion
   }
}
It's almost the same implementation as used in the other logs. The EventLog parameter is a member of each service class and we have to do a last change to our service implementation to run as a service:
public CrmOpportunityService() {
   InitializeComponent();
this.Log = new WindowsEventLog(this.EventLog);
}
public CrmOpportunityService(ILog log) {
   InitializeComponent();
this.Log = log;
}
When started as a service, the first constructor will be executed and we use the Windows Event Log to log our messages. When called from our own Service Control Manager application or using the VsDebugLog class, then the second constructor is used and we can look at the output without looking at the event log and hitting the refresh button every few seconds.
Installing the Service
Now it's time for the final test: running the application as a service. In order to do that, we have to install the service first. Open the designer view of the service class and right-click onto it:
Service Installer
The "Add Installer" option is what we need to configure our service and it's also available as a hyperlink in the properties window. Two components are added to our service: serviceInstaller1 and serviceProcessInstaller. The service installer contains most properties we need and I have set some typical values: 
Installer Properties
The service process installer defines the account the service is using. The default of "User" is what we need, so I haven't changed anything.
Service Process Installer
You can change this value to let the service run as the Local Service account, Local System account or Network Service account. However, we need a valid CRM user to successfully retrieve data from our CRM system and that means a user account. 
Remember the conditional compilation symbol in the program.cs file? You have to un-define the RUN_IN_VS symbol to execute the ServiceBase.Run method instead of our own startup code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
namespace CrmOpportunityService {
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main() {
ServiceBase[] ServicesToRun;
         ServicesToRun = new ServiceBase[]
         {
new CrmOpportunityService()
         };
#if RUN_IN_VS
         CrmOpportunityService service = new CrmOpportunityService();
         service.StartService();
         Thread.Sleep(5000);
         service.Stop();
#else
ServiceBase.Run(ServicesToRun);
#endif
      }
   }
}
I only added the RUN_IN_VS symbol to the debug configuration, so all I had to do was switching to the release configuration.
Installing the service is pretty easy. The .NET Framework SDK has a utility named "installutil". It installs or uninstalls a service by either specifying the /i or the /u command line parameter. To register the release build as a service, start a command prompt and navigate to the directory containing the installutil.exe executable, which will be C:\Windows\Microsoft.NET\Framework64\v2.0.50727 or something similar (Framework64 if it's a 64-bit machine, otherwise just Framework). If you have Visual Studio installed, then simply run a Visual Studio Command Prompt and the PATH variable is set accordingly.
In the command prompt type installutil /i "full path to the service executable", e.g.
installutil /i "D:\BLOG\CRM 4.0 Samples\CrmOpportunityService\CrmOpportunityService\bin\Release\CrmOpportunityService.exe"
When inside a Visual Studio Command Prompt, you can also navigate to the directory containing the service executable and simply type
installutil /i CrmOpportunityService.exe
The specified parameters are shown in the console window and the installation starts:
>installutil /i CrmOpportunityService.exe
Microsoft (R) .NET Framework Installation utility Version 2.0.50727.3053
Copyright (c) Microsoft Corporation. All rights reserved.
Running a transacted installation.
Beginning the Install phase of the installation.
See the contents of the log file for the D:\BLOG\CRM 4.0 Samples\CrmOpportunityService\CrmOpportunityService\bin\Release\CrmOpportunityService.exe assembly's progress.
The file is located at D:\BLOG\CRM 4.0 Samples\CrmOpportunityService\CrmOpportunityService\bin\Release\CrmOpportunityService.InstallLog.
Installing assembly 'D:\BLOG\CRM 4.0 Samples\CrmOpportunityService\CrmOpportunityService\bin\Release\CrmOpportunityService.exe'.
Affected parameters are:
logtoconsole =
assemblypath = D:\BLOG\CRM 4.0 Samples\CrmOpportunityService\CrmOpportunityService\bin\Release\CrmOpportunityService.exe
i =
logfile = D:\BLOG\CRM 4.0 Samples\CrmOpportunityService\CrmOpportunityService\bin\Release\CrmOpportunityService.InstallLog
At this point a dialog pops up asking to provide the user credentials used to run the service:
Set Service Login
And finally you get two more lines in the console window:
The Commit phase completed successfully.
The transacted install has completed.
That's it. You should now see the service in the Services window:
Services
Start the service and open the event log to see the service event messages:
Event Log
The Final Test
Our service is running now, but it doesn't mean it's working. To test, simply create a new opportunity or change an existing one and you should see a new export file in the export directory:
Export File
Because of the csv extension, a double-click opens the file in Microsoft Excel (if installed):
Export File
That's it. The entire source code is available for download and I hope that it helps you writing your own services in the future. Even if they are not related to CRM, because the majority of the code can be used for any service implementation

Import Excel data to grid

This example shows how to open,read and import excel file into DataSet or DataTable using C#.

C# Queue example

The Queue works like FIFO system , a first-in, first-out collection of Objects. Objects stored in a Queue are inserted at one end and removed from the other. The Queue provide additional insertion, extraction, and inspection operations. We can Enqueue (add) items in Queue and we can Dequeue (remove from Queue ) or we can Peek (that is we will get the reference of first item ) item from Queue. Queue accepts null reference as a valid value and allows duplicate elements.

Some important functions in the Queue Class are follows :
    Enqueue : Add an Item in Queue
    Dequeue : Remove the oldest item from Queue
    Peek : Get the reference of the oldest item

Enqueue : Add an Item in Queue
Syntax : Queue.Enqueue(Object)
  Object : The item to add in Queue
days.Enqueue("Sunday");
Dequeue : Remove the oldest item from Queue (we don't get the item later)
Syntax : Object Queue.Dequeue()
  Returns : Remove the oldest item and return.
days.Dequeue();
Peek : Get the reference of the oldest item (it is not removed permanently)
Syntax : Object Queue.Peek()
  returns : Get the reference of the oldest item in the Queue
days.peek();

The following CSharp Source code shows some of commonly used functions :

C# Stack

The Stack class represents a last-in-first-out (LIFO) Stack of Objects. Stack follows the push-pop operations. That is we can Push (insert) Items into Stack and Pop (retrieve) it back . Stack is implemented as a circular buffer. It follows the Last In First Out (LIFO) system. That is we can push the items into a stack and get it in reverse order. Stack returns the last item first. As elements are added to a Stack, the capacity is automatically increased as required through reallocation.

Commonly used methods :
  Push : Add (Push) an item in the Stack data structure
  Pop : Pop return the last Item from the Stack
Contains: Check the object contains in the Stack

Push : Add (Push) an item in the Stack data structure
  Syntax : Stack.Push(Object)
  Object : The item to be inserted.
  Stack days = new Stack();
days.Push("Sunday");

Pop : Pop return the item last Item from the Stack
  Syntax : Object Stack.Pop()
  Object : Return the last object in the Stack
days.Pop();

Contains : Check the object contains in the Stack
  Syntax : Stack.Contains(Object)
  Object : The specified Object to be search
days.Contains("Tuesday");


The following CSharp Source code shows some of important functions in Stack Class:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Stack days = new Stack();
            days.Push("SunDay");
            days.Push("MonDay");
            days.Push("TueDay");
            days.Push("WedDay");
            days.Push("ThuDay");
            days.Push("FriDay");
            days.Push("SaturDay");
            if (days.Count ==7)
            {
                MessageBox.Show(days.Pop().ToString ());
            }
            else
            {
                MessageBox.Show("SaturDay does not exist");
            }
        }
    }
}

When you execute this C# program add seven items in the stack . Then it check the count is equal to 7 , if it is seven then pop() the item. The message box will display SaturDay.

C# HashTable

Hashtable in C# represents a collection of key/value pairs which maps keys to value. Any non-null object can be used as a key but a value can. We can retrieve items from hashTable to provide the key . Both keys and values are Objects.
The commonly used functions in Hashtable are :
  Add : To add a pair of value in HashTable
  ContainsKey : Check if a specified key exist or not
  ContainsValue : Check the specified Value exist in HashTable
  Remove : Remove the specified Key and corresponding Value

 Add : To add a pair of value in HashTable
  Syntax : HashTable.Add(Key,Value)
  Key : The Key value
  Value : The value of corresponding key
  Hashtable ht;
  ht.Add("1", "Sunday");

 ContainsKey : Check if a specified key exist or not
  Synatx : bool HashTable.ContainsKey(key)
  Key : The Key value for search in HahTable
  Returns : return

 true if item exist else false
  ht.Contains("1");

 ContainsValue : Check the specified Value exist in HashTable
  Synatx : bool HashTable.ContainsValue(Value)
  Value : Search the specified Value in HashTable
  Returns : return true if item exist else false
  ht.ContainsValue("Sunday")

 Remove : Remove the specified Key and corresponding Value
  Syntax : HashTable.Remove(Key)
  Key : The key of the element to remove
  ht.Remove("1");

The following source code shows some important operations in a HashTable
using System;
using System.Collections;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Hashtable weeks = new Hashtable();
            weeks.Add("1", "SunDay");
            weeks.Add("2", "MonDay");
            weeks.Add("3", "TueDay");
            weeks.Add("4", "WedDay");
            weeks.Add("5", "ThuDay");
            weeks.Add("6", "FriDay");
            weeks.Add("7", "SatDay");
            //Display a single Item 

            MessageBox.Show(weeks["5"].ToString ());
            //Search an Item 
            if (weeks.ContainsValue("TueDay"))
            {
                MessageBox.Show("Find");
            }
            else
            {
                MessageBox.Show("Not find");
            }
            //remove an Item 
            weeks.Remove("3");
            //Display all key value pairs
            foreach (DictionaryEntry day in weeks )
            {
                MessageBox.Show (day.Key + "   -   " + day.Value );
            }
        }
    }
}

Modify Excel file using c#

using System;
using System.Data;
using System.Data.OleDb ;

public partial class _Default : System.Web.UI.Page
{
 protected void Button1_Click(object sender, EventArgs e)
 {
  try
  {
   string connStr = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='your-excel-file.xls';Extended Properties=Excel 8.0;";
   OleDbConnection MyConnection;
   OleDbCommand MyCommand = new OleDbCommand();
   MyConnection = new OleDbConnection(connStr);

   MyConnection.Open();
   MyCommand.Connection = MyConnection;
   string sql = "Update [Sheet1$] set name = 'New Name' where id=1";
   MyCommand.CommandText = sql;
   MyCommand.ExecuteNonQuery();
   MyConnection.Close();

   Label1.Text = "data updated successfully !! ";
  }
  catch (Exception ex)
  {
   Label1.Text = ex.ToString();
  }
 }
}

Write content to Excel

using System;
using System.IO;
using System.Configuration;
using System.Web.UI;

public partial class _Default : System.Web.UI.Page
{
 protected void Button1_Click(object sender, EventArgs e)
 {
  try
  {
   GridView1.Page.EnableViewState = false;
   StringWriter sWriter = new StringWriter();
   HtmlTextWriter hWriter = new HtmlTextWriter(sWriter);
   GridView1.RenderControl(hWriter);
   string HtmlInfo = sWriter.ToString().Trim();
   FileStream fStream = new FileStream("c:\\data.xls", FileMode.Create);
   BinaryWriter BWriter = new BinaryWriter(fStream);
   BWriter.Write(HtmlInfo);
   BWriter.Close();
   fStream.Close();
   Label1.Text = "File write to c:\\data.xls ";
  }
  catch (Exception ex)
  {
   Label1.Text = ex.ToString ();
  }
 }

 public override void VerifyRenderingInServerForm(Control control)
 {
 }
}

Read excel file to data grid

Export ASP.NET to Excel

using System;
using System.IO;
using System.Configuration;
using System.Web.UI;

public partial class _Default : System.Web.UI.Page
{
 protected void Button1_Click(object sender, EventArgs e)
 {
  try
  {
   Response.Clear();
   Response.Buffer = true;
   Response.AddHeader("content-disposition", "attachment;filename=gridviewdata.xls");
   Response.Charset = "";
   Response.ContentType = "application/vnd.ms-excel";
   StringWriter sWriter = new StringWriter();
   HtmlTextWriter hWriter = new HtmlTextWriter(sWriter);
   GridView1.RenderControl(hWriter);
   Response.Output.Write(sWriter.ToString());
   Response.Flush();
   Response.End();
  }
  catch (Exception ex)
  {
   Label1.Text = ex.ToString ();
  }
 }

 public override void VerifyRenderingInServerForm(Control control)
 {
 }
}

dotnet Q&A

1. What is mean by Class?

Class is a structure that describes the state (property) and behavior (methods) of the object. It is a template or blueprint to create objects of the class. Class represents the noun and it can be used as type in programming language. E.g Car, Person etc

2. What is mean by Objects?

Object is an executable copy of a class. State and behavior of the objects are defined by class definition. We can create multiple objects for single class. It is also called as instance of the class. When an object is created from the class, memory will be allocated in RAM. e.g Car- Maruthi, Alto, Zen etc. Person- Ram, Sam, John etc

3. What is mean by Struture?

Structure is a light-weight class used to create user-defined types containing only public fields. Structure can't have implementation inheritance, but it can have interface inheritance. We cannot modify the default constructors as like a class. Structure is a value type holds their value in memory when they are declared.

4. What is difference between Class and Object?

Classes are the template or blueprint its state of how objects should be and behave, where as Object is an actual real term object. E.g CAR define state like it should have four wheel and body structure with moving, accelerating and break functionality. Maruthi, Alto or Zen is the real object which has different kind of state from one another.

5. What is difference between Class and Structure?

  • Class is Reference type(Reference types hold a reference to an object in memory) - Structure is a Value type(Value types hold their value in memory when they are declared)
  • User can modify default constructor and destructor of class- structure can't modify default constructor
  • Class supports inheritance - Structure will not support inheritance
  • Classes must be instantiated using the new operator - Structure can be instantiated without using the new operator


6. Which case we have to use Class and Structure?

Structure can be used for things that we no need for identity. Class can be used when we need the identity for an object.

7. What is the advantage of Structure over Class?

Since Stucture is a value type and if we use at the proper location, it will improve the performance.

9. What are advantages of using private constructor, method, property?

Due to security reason, methods and properties are not exposed outside the class using Private access modifier. For implementing Singleton pattern we go for Private Constructor, so we will not able to create instance. Separate method is used to create and return the instance.

10. What is mean by Partial class?

It is new features in .Net 2.0; partial classes mean that class definition can be split into multiple physical files. Logically, partial classes do not make any difference to the compiler. The compiler intelligently combines the definitions together into a single class at compile-time.
Example for Partial Class
partial class Employee
    {
       string m_Name;
       public String Name
       {
           get { return m_Name; }
           set { m_Name = value; }
       }
    }

    partial class Employee
    {
        int m_Age;
        public int Age
        {
            get { return m_Age; }
            set { m_Age = value; }
        }
    }

    public class ExampleofPartical
    {
        public void Method1()
        {
            Employee objClass1 = new Employee();
            objClass1.Name="Name";
            objClass1.Age = 12;
        }
    }




8. What are different access modifiers in .Net?



  • Private - The type or member can only be accessed by code in the same class or struct.
  • Protected - The type or member can only be accessed by code in the same class or struct, or in a derived class.
  • Internal - The type or member can be accessed by any code in the same assembly, but not from another assembly.
  • Procted Internal - The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.
  • Public -The type or member can be accessed by any other code in the same assembly or another assembly that references it.

Note: In VB.Net 'Internal' is called as 'Friend'

11. What is mean by Partial method?


Partial methods are methods defined in a partial class that are (optionally) divided across two files. With partial methods one file contains the method signature - the method name, its return type, and its input parameters - while the body is (optionally) defined in a separate file. If the partial method's body is not defined then the compiler automatically removes the partial method signature and all calls to the method at compile-time.
Example for Partial method
   {
       string m_Name;
       public String Name
       {
           get { return m_Name; }
           set { m_Name = value; }
       }
      public  partial  string GetEmpDetails(string ID);
      
    }

    partial class Employee
    {
        int m_Age;
        public int Age
        {
            get { return m_Age; }
            set { m_Age = value; }
        }
       public  partial string GetEmpDetails(string ID)
        {
            return "Employee1";
        }
    }


12. Why do we go for Partial method?

Partial methods are mainly useful in auto-generated code situations. A code generating tool might know that there are certain extension points that some users are going to be interested in customizing. For example, the objects created in LINQ to SQL have partial methods like OnLoaded, OnCreated, OnPropertyNameChanging, and OnPropertyNameChanged. The auto-generated code calls the OnCreated partial method from its constructor. If you want to run custom code when one of these objects is created you can create a partial class and define the body for the OnCreated partial method.

13. Why do we go for Partial class?


  1. Improve the readability of extremely large classes by partitioning related methods into separate files.
  2. Partial classes enable the code generator to generate code in one file while the developer who may need to extend the auto-generated logic can do so in a separate file, which eliminates the worry that the code generator might overwrite a developer's customizations.


14. Where we use Partial method and class?

Partial classes and partial methods are most commonly used in auto-generated code. It provides a simple and safe way to add new functionality or extend existing functionality of auto-generated code.

15. What are restrictions for Partial method?


  1. Partial definitions must preceded with the key word "Partial"
  2. Method signature should be same in both partial class file
  3. We cannot have partial implementation in one file and another implementation in other file. We can have declaration in one file and implementation in another file.


16. What is mean by Static class?

Static class is used to create attributes and methods that can be accessed without creating the instance of the class. Static classes are loaded automatically by the .NET Framework when application or assembly is loaded. 'Static' key word is used to mention the static class. e.g MyStaticClass.PI
Example for Static Class
public static class MyStaticClass
    {
        public static decimal PI = 3.14M;
        public  static int Add(int num1, int num2)
        {
            return num1 + num2;
        }
        public static  string Append(string str1, string str2)
        {
            return str1 + str2;
        }
    }
  MyStaticClass.PI


17. What is mean by Static method?

Static method can be accessed without creating the instance of the class. 'Static' key word is used to mention the static method. Static methods can be created inside the normal class or static class. If we create the static method inside the normal class, static method will not be able to access by creating instance of the class. e.g Math.Add()

18. Can we override static method?

No, compiler will not allow overriding the static method.

19. What are uses of static class and method?

  1. Compiler will not allow creating the instance of the class
  2. Static class also makes the implementation simpler and faster
  3. Cannot inherit a static class since it is sealed


20. What is static constructor?

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
Example:
public class MyStaticClass
        {
            static int count;

            static MyStaticClass()
            {
                count = 0;
                Console.WriteLine("Static class is initialized");
            }

            public static void MyMethod(string name)
            {
                Console.WriteLine("Static class is initialized " + name);
            }
        }

MyStaticClass.MyMethod("John");

Output:
Static class is initialized
Hello John


21. What are shared (VB.NET)/Static(C#) variables?

Static members are not associated with a particular instance of any class, which can be invoked directly from the class level, rather than from its instance
Example
public static double  PI = 3.1457;


22. What is Nested Classes?

Classes with in classes are called as Nested class.
Example
public class MyClassLevel_1
    {
        public void Display()
        {
            Console.WriteLine("Level_1");
        }
      public  class MyClassLevel_2
        {
          public void Display()
          {
              Console.WriteLine("Level_2");
          }

          public class MyClassLevel_3
          {
              public void Display()
              {
                  Console.WriteLine("Level_3");
              }
          }
        }
    }

Creating instance of the nested class
MyClassLevel_1 L1 = new MyClassLevel_1();
            MyClassLevel_1.MyClassLevel_2 L2 = new MyClassLevel_1.MyClassLevel_2();
            MyClassLevel_1.MyClassLevel_2.MyClassLevel_3 L3 = new 
                MyClassLevel_1.MyClassLevel_2.MyClassLevel_3();
            L1.Display();
            L2.Display();
            L3.Display();

            Output
            Level_1
            Level_2
            Level_3


23. What are difference between Singleton and Static class?

  1. Singleton can extend classes and implement interfaces, while a static class cannot implement the interface.
  2. Singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded.
  3. Singleton class can be extended and it's methods can be overridden.


24. Why Main () method is static?

To ensure there is only one entry point to the application.

25. What is mean by inheritance?

Inheritance is one of the concepts of object-oriented programming, where a new class is created from an existing class. Inheritance class is often referred to as subclasses, comes from the fact that the subclass (the newly created class) contains the attributes and methods of the parent class. This can be used to create a highly specialized hierarchical class structure.
Example of Inheritance

class Circle
    {
        private double m_radius;

        public double Radius
        {
            get { return m_radius; }
            set { m_radius = value; }
        }
        public double Diameter
        {
            get { return Radius * 2; }
        }
        public double Circumference
        {
            get { return Diameter * 3.14; }
        }
        public double Area
        {
            get { return Radius * Radius * 3.14; }
        }
    }

    class Sphere : Circle
    {
        new public double Area
        {
            get { return 4 * Radius * Radius * 3.14; }
        }

        public double Volume
        {
            get { return 4 * 3.14 * Radius * Radius * Radius / 3; }
        }
    }


26. Can we inherit multiple classes?

No, multiple inheritances are not supported in .Net. Because consider the provided example. Here there are two Parent class Paretn1 and Parent2. This is inherited by Child class, In GetData method, child call the parent class method PrintData(). In this case which method will be executed? It is very difficult for CLR to identify which method to call. It shows that we multiple inheritance create ambiguity to oops concept. In order to avoid this ambiguity we are going for multiple interface implementations.
public class Parent1
    {
        public string PrintData()
        {
            return "This is parent1";
        }
    }
    public class Parent2
    {
        public string PrintData()
        {
            return "This is parent2";
        }
    }

    public class Child1 : Parent1, Parent2
    {
        public string GetData()
        {
            return this.PrintData();
        }
    }


27. What is mean by Shadowing?

When the method is defined in base class are not override able and we need to provide different implementation for the same in derived class. In this kind of scenario we can use hide the base class implementation and provide new implementation using Shadows (VB.Net)/new(C#) keyword.
Example:
Public Class ParentClass
    Public Sub Display()
        Console.WriteLine("Parent class")
    End Sub

End Class

Public Class ChildClass
    Inherits ParentClass

    Public Shadows Sub Display()
        Console.WriteLine("Child class")
    End Sub
End Class

  
 Dim p As New ParentClass
        Dim c As New ChildClass
        Dim pc As ParentClass = New ChildClass
        p.Display()
        c.Display()
        pc.Display()

Output:
Parent class
Child class
Parent class

28. How a base class method is hidden?

Using new keyword in the derived class, base class method can be hidden or suppressed. New implementation can be added to the derived class.

29. What does the keyword virtual mean in the method definition?

The method can be over-ridden.

30. How method overriding different from overloading?

If we are overriding the method, derived class method behavior is changed from the base class. In Overloading, method with same name by different signature is used.
Example:
{
            public virtual void Display()
            {
                Console.WriteLine("ParentClass");
            }
        }

        public class ChildClass : ParentClass
        {
            //Example for method override
            public override void Display()
            {
                Console.WriteLine("ChildClass");
            }

            //Example for method overload
            public void Display(string name)
            {
                Console.WriteLine(name);
            }
            //Example for method overload
            public void Display(string name, string country)
            { 
            Console.WriteLine("Name:"+name +"Country: "+ country );
            }
        }


  ParentClass p = new ParentClass();
            ChildClass c = new ChildClass();
            ParentClass pc = new ChildClass();
            p.Display();
            c.Display();
            pc.Display();
â€Æ’
OutPut:
ParentClass
ChildClass
ChildClass 


31. Can you declare the override method static while the original method is non-static?

No

32. What is mean by Sealed Class?

Class which cannot be inherited is called as sealed class. If we need to prevent a class from being inherited, use â€Å“Sealed” keyword. But sealed class can inherited from other classes.
Example:
public class MyBaseClass
        {
            public void Display()
            {
                Console.WriteLine("Base class");
            }
        }

        //Compile Success: This class cannot be inherited
        public sealed class MySealedClass:MyBaseClass 
        {
            public void Display()
            {
                base.Display();
                Console.WriteLine("Sealed class");
            }
        }

        //Compilation Error: cannot derive from sealed type MySealedClass
        public class MyChildClass : MySealedClass
        { 
        
        }


33. Can you allow class to be inherited, but prevent the method from being over-ridden?

Yes, just leave the class public and make the method sealed.

34. Will sealed class allows inheritance, if not why?

Sealed means it is not inheritable

35. What are the advantages of Private constructor?

  1. Private constructor will prevent the user from creating the instance of the class which contains only static members.
  2. Private constructor are used for implementing the singleton pattern


36. While using inheritance, derived class construct will call base class constructor?

Yes, base class constructor will be called before child class constructor

37. Overloaded constructor will call default constructor internally?

No, overload constructor will not call default constructor

38. What is difference between Overrides and Overridable?

Overridable (VB.Net)/ virtual (C#) is used in parent class to indicate that a method can be overridden. Overrides(VB.Net)/ override(C#) is used in the child class to indicate that you are overriding a method.

39. What is Method overloading?

Method overloading occurs when a class contains two methods with the same name, but different signatures.

40. What is operator overloading?

Operator overloading is used to provide a custom functionality to existing operators. For Example +,-,* and / operators are used for mathematical functionality. But we can overload these operators to perform custom operation on classes or structure.
Example:
To concatenate the two strings we have to use Concat method
Dim str1, str2, str3 As String
        str1 = "Hello"
        str2 = "world"
        str3 = String.Concat(str1, str2)

But .Net provides in build operator overloading for string we can use ‘+’ operator for concatenating the string value
str3=str1+str2

Similarly we can also implement operator overloading for classes or structure
Employee3= Employee1 + Employee2


41. What is mean by abstraction?

Abstraction is the process of showing necessary information and hiding unwanted information. Let us consider the "CalculateSalary" in your Employee class, which takes EmployeeId as parameter and returns the salary of the employee for the current month as an integer value. Now if someone wants to use that method. He does not need to care about how Employee object calculates the salary? An only thing he needs to be concern is name of the method, its input parameters and format of resulting member

42. What is mean by abstraction class?

Abstract classes contain one or more abstract methods that do not have implementation. An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes allow specialization of inherited classes.

43. What id mean by Interface?

Interface defines the set of properties, signature of the methods and events. It does not include any implementation. Class which implements the interface can provide the behavior to the implemented method. For example two class MyEnglishClassand MyFreanchClass implementing same interface and provide two different set of behavior in their implementation.
public interface IMyInterface
    {
        string Hello(string name);
    }

    public class MyEnglishClass:IMyInterface 
    {
        public string Hello(string name)
        {
            return "Hello " + name;
        }
    }

    public class MyFrenchClass : IMyInterface
    {
        public String Hello(string name)
        {
            return "allo " + name; 
        }
    }


44. What is difference between Abstract class and Interface?

  • In Interface all the method must be abstract; in abstract class we can have both abstract and concrete methods.
  • Access modifiers cannot be specified in interface because it should always be public; in Abstract class, we can specify the access modifier.


45. In which Scenario you will go for Abstract or Interface Class?

Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.
Interfaces are often used to describe the peripheral abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.

46. What is mean by polymorphism?

Polymorphism means the ability to take more than one form. An operation may exhibit different behaviors in different instances. The behavior depends on the data types used in the operation. Polymorphism is extensively used in implementing Inheritance.

47. What are different types of polymorphism?

There are two types of polymorphism
Static polymorphism - defining the method with same name and different signature is called as static polymorphism. In the below example there are three different Add() functionality this Add() will be executed based on the parameter passed.
Example :
public int Add(int a, int b)
        { 
            return a + b; 
        }

        public double Add(double a, double b)
        {
            return a + b;
        }

        public long Add(long a, long b)
        {
            return a + b;
        }

Dynamic polymorphism – Dynamic polymorphism can be implemented using Virtual and Override keyword. By using polymorphism, each derived class can have its own behavior, Even though classes are derived or inherited from the same parent class
Example:
In the below example ClassB is inherited from ClassA. ClassB can have its own behavior by overriding the parent class method. Parent class method should be represented with virtual keyword to override the same method in derived class.
public class ClassA
    {
        public virtual void Display()
        {
            Console.WriteLine ( "ClassA");
        }
    }

    public class ClassB:ClassA 
    {
        public override  void Display()
        {
            Console.WriteLine ( "ClassB");
        }
    }

static void Main(string[] args)
        {
            ClassA a = new ClassA();
            ClassB b = new ClassB();
            ClassA c = new ClassB();
            a.Display();
            b.Display();
            c.Display();
            Console.ReadLine();

        }

OutPut:
ClassA
ClassB
ClassB



48. What you mean by Encapsulation?

Encapsulation is the procedure of covering up of data and functions into a single unit and protects the data from the outside world. Example â€Å“Class” only public functions and properties are exposed; functions implementation and private variables are hidden from outside world.

49. What is difference between data encapsulation and abstraction?

Abstraction refers to the act of representing essential features without including the background details or explanations. Storing data and functions in a single unit is called as encapsulation.

50. What is mean by Delegate?

Delegate is a type that holds a reference to a method or a function. . Once a delegate is assigned a method, it behaves exactly like that method. We can call the method using delegate instead of directly calling the method. Using delegate, we can also pass the parameter and get return value. Any method with matched the signature of the delegate can be assigned. Simply we can say .NET implements the concept of function pointers using delegate.
Example:
There are three step to following for using Delegate
  • Declaration
  • Instantiation
  • Invocation

In the below example we have declared the new delegate â€Å“MyDelegate”, which accept string as parameter and return value as string. Two methods SayHello and SayBye function will be called using delegate.
//Declaring the delegate
        delegate string MyDelegate(string name);

        //function called by delegate dynamically
        private static  string SayHello(string name)
        {
            return "Hello " + name;
        }

        private static  string SayBye(string name)
        {
            return "Bye " + name;
        }

After declaration of delegate, we have initialized with SayHello function. Now this delegate will hold reference to specified function. Function will be called using Invoke () method of delegate. In this example we have called two methods (SayHello and SayBye) with same signature(parameter type and return type).
static void Main(string[] args)
        {
         
  //Initialllizing delegate with function name
            MyDelegate delg = new MyDelegate(SayHello);
            //Invoking function using delegate
            Console.WriteLine(delg.Invoke("Sam"));
            
            delg = new MyDelegate(SayBye);
            //Invoking diffent function using same delegate
            Console.WriteLine(delg.Invoke("Sam"));

            Console.ReadLine();
        }

OutPut:
Hello Sam
Bye Sam


51. What is a multicast delegate?

It's a delegate that stores the address of multiple methods and eventually fires off several methods. Multicast delegate must have a return type of void.

52. What is an Asynchronous delegate?

When you invoke a delegate asynchronously, no new thread is created. Instead, the CLR automatically assigns a free thread from a small thread pool that it maintains. Typically, this thread pool starts with one thread and increases to a maximum of about 25 free threads on a single-CPU computer. As a result, if you start 50 asynchronous operations, one after the other, the first 25 will complete first. As soon as one ends, the freed thread is used to execute the next asynchronous operation.

53. What is mean by Events?

Events are nothing but a publisher and subscriber model. Any subscriber who is interested in receiving notification from the publisher can subscribe the events. If source event is fired or publisher raises the event, a notification will be send to all subscribers. One publisher can have multiple subscribers. Internally events will try to make use of delegate for this publisher, subscription model.
Example:
In the below example, we have created new event called "SampleEvent" and this event will be fired once MyMethod() is called. Anyone who wants to subscribe to this event can create a instance of the MyClassWithEvent and add handler to the event. So when ever event is raised, add handler method will be called.
Public Class MyClassWithEvent

    'Created New Event, which will return a message to all subscriber
    Event SampleEvent(ByVal message As String)

    'Event will be fired once this method is called
    Public Sub MyMethod()
        Console.WriteLine("MyMethod is called")
        'Raising the event with message
        RaiseEvent SampleEvent("Event is Raised from MyClassWithEvent")
    End Sub
End Class

Module Module1

    Sub Main()
        
        Dim c As New MyClassWithEvent
        'First subscriber of the event
        AddHandler c.SampleEvent, AddressOf EventSubscriber1
        'Second subscriber of the event
        AddHandler c.SampleEvent, AddressOf EventSubscriber2
        c.MyMethod()
        Console.ReadLine()
    End Sub

    Private Sub EventSubscriber1(ByVal message As String)
        Console.WriteLine("Subscriber 1")
        Console.WriteLine("Message: " + message)
    End Sub

    Private Sub EventSubscriber2(ByVal message As String)
        Console.WriteLine("Subscriber 2")
        Console.WriteLine("Message: " + message)
    End Sub
End Module

OutPut:
MyMethod is called
Subscriber 1
Message: Event is Raised from MyClassWithEvent
Subscriber 2
Message: Event is Raised from MyClassWithEvent


54. Can event have access modifiers?

Yes, Event̢۪s can have access modifier, if we mention it as Protected events can be subscribed only within inherited class, If you mention it as Internal(C#)/Friends(VB.Net) it can be subscribed by all class inside the assembly. If you mention it as Private it can subscribed with in class where it is declared.

55. Can we have static/shared events?

Yes, we can have static(C#)/shared(VB.Net) event, but only shared method can raise shared events.

56. Can we have different access modifier for Get/Set of the properties?

Yes, in C# 3.0 and above, we can use different access modifier for Get/Set of the properties, but this is not possible in C#2.0 and lower

57. What is an indexer?

An indexer is an accessor that enables an object to be treated in the same way as an array. An indexer is considered when a class is better represented as a virtual container of data that can be retrieved or set using indices. Since an indexer is nameless, its signature is specified by the keyword â€Å“this” followed by its indexing parameters within square brackets.
Example:
In the below example we have created new index for class of type string. During get and set operation string manipulations are done.
public class MyClassForIndexer
    {
        private string m_Name = "This is example for indexer";
        public string this[int index]
        {
            get 
            {
                return m_Name.Substring( index);
            }
            set
            {
                m_Name = m_Name.Insert(index, value);
            }
        }
}
 MyClassForIndexer ind = new MyClassForIndexer();
                            Console.WriteLine (ind[0]);
                            ind[7] = "Appended String";
                            Console.WriteLine(ind[0]);
 Output:
This is example for indexer
This isAppended String example for indexer


58. What is ENUM?

ENUM means Enumeration; it is used to group related sets of constants. To create a enumeration you use the Enum statement
Example:
Enum Months
            January = 1
            Feburary = 2
            March = 3
            April = 4
            May = 5
            June = 6
            July = 7
            August = 8
            September = 9
            October = 10
            November = 11
            December = 12
        End Enum

StringBuilder in JavaScript

a simple StringBuilder class that pushes individual strings into an array and then uses the join method to produce the concatenated output string.


Process Piping

This example shows the technique called as process piping. Process piping is a technique to redirect input/out form a process to get the result in runtime. This enable us to execute any process with a given set of parameters and capture the output. In the example below weare invoking the command shell(cmd.exe) to do a ping on "Bing.com" and capture the output in the console.



We can further create a function which does the same for us, and alter the behaviour by sending different parameters.

JavaScript AJAX wrapper

This is a simple code that wraps the XmlHttp Request and Response.

Class in JavaScript

As per Wikipedia: "JavaScript is classified as a prototype-based scripting language with dynamic typing and first-class functions. This mix of features makes it a multi-paradigm language, supporting object-oriented,[6] imperative, and functional[1][7] programming styles." But we still never explore the object orientation side of it, to start with.. we can create Class & Modules to divide the program in small chucks oflogic. This example shows you how to create a class in JavaScript.
As per the above code, we have defined a class which is actually a function since JScript don't have class keyword and a constructor(will be same as the class name). "this" refers to the current object in memory and the variable1 is prototyped to it.

Module in JavaScript

Javascript has always been written with a function oriented structure, as the script goes more dense it become complicate and harder to manage & extend. With Javascript module we can segregate these as logical modules. Here is an example how this can be done in JavaScript.

Fluent interface in C#

A fluent interface is normally implemented by using method cascading (concretely method chaining) to relay the instruction context of a subsequent call (but a fluent interface entails more than just method chaining [1]). Generally, the context is
1. defined through the return value of a called method
2. self-referential, where the new context is equivalent to the last context
3. terminated through the return of a void context.

So here it code how you can implement Jquery like fluent interface(method chaning) with C# code.


Here i have chained the method using a class called "FluentInterface", which implements the StringBuilder and provided a set of method, which are chained together. This implements JQuery like accessability in c#. The function can be called as:
 

 new FluentInterface().Add("line1").Add("line2").Replace("line2","line456").
Add("line3").Add("line4").Add("line5").Print().Clear();

Builder pattern

This pattern creates object based on the Interface, but also lets the subclass decide which class to instantiate. It also has finer control over the construction process. There is a concept of Director in Builder Pattern implementation. The director actually creates the object and also runs a few tasks after that.



In case of Builder pattern you can see the Director is actually using CreateBuilder to create the instance of the builder. So when the Builder is actually created, we can also invoke a few common task in it.