Tuesday, August 11, 2009

Custom ToolStrip Controls

Use the below code to create a ToolStrip host which enable to make any custom control to be used in the toolstrip bar


using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms.Design;
using System.Windows.Forms;

namespace My.Controls
{
[System.ComponentModel.DesignerCategory("code")]
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip | ToolStripItemDesignerAvailability.StatusStrip)]
public class ComboToolStripControlHost : ToolStripControlHost
{

static ToolStripComboExt m_combo = new ToolStripComboExt();

public ComboToolStripControlHost()
: base(CreateControlInstance())
{
}

private static Control CreateControlInstance()
{
return m_combo;
}

public ToolStripComboExt TSCombo
{
get { return m_combo; }
}
}
}

Monday, August 3, 2009

Reading from Excel to DataTable

Fallowing util method allows to select data from excel to DataTable

public static DataTable ReadFromExcel(string fileName)
{
DataTable dt = new DataTable();
try
{
OleDbConnection con = new OleDbConnection(string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0", fileName));
OleDbDataAdapter da = new OleDbDataAdapter("select * from list", con);
da.Fill(dt);
}
catch (Exception ex)
{
if (ex.Message.Contains("list"))
{
throw new ExcelRangeException();
}
else
{
throw ex;
}
}
return dt;
}


select * from list, where list is a range in excel

Outlook Mailing

Create an Util Class as below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Net.Mime;
using log4net.Repository;
using log4net;
using System.Reflection;
using log4net.Appender;

namespace PWCSecurities.Utils
{
public class OutlookEmailHelper
{
#region Logging

private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

#endregion

private Outlook._Application outlookApp;
private Outlook.NameSpace outlookNameSpace;
private Outlook.MAPIFolder maipFolder;
private Outlook._MailItem mailItem;



public delegate void MessageSentHandler(object sender, MessageSentEventArgs e);
public event MessageSentHandler MessageSent;

public string MailSubject = "SecurityTool Error Report";

//static SmtpClient smtpClient = new SmtpClient("mailhost.lehman.com");

public Outlook._MailItem MessageItem
{
get
{
return mailItem;
}
set
{
mailItem = value;
}

}

public OutlookEmailHelper()
{
try
{
outlookApp = new Outlook.Application();
outlookNameSpace = outlookApp.GetNamespace("MAPI");
outlookNameSpace.Logon(null, null, true, true);

// Gets defaultfolder for my Outlook Outbox
maipFolder = outlookNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderSentMail);

//create a a new mailitem object
mailItem = (Outlook.MailItem)outlookApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

}
catch (Exception)
{
}

}

///
///
///

///
/// Outlook Mail Recipient Type : To = 1 and Cc = 2
///
public string Resolve(string[] names, object type)
{
Outlook.OlMailRecipientType recType;
if ((string)type == "1")
{
recType = Microsoft.Office.Interop.Outlook.OlMailRecipientType.olTo;
}
else
{
recType = Microsoft.Office.Interop.Outlook.OlMailRecipientType.olCC;
}
return Resolve(names, mailItem, recType);
}

///
///
///

///
///
///
///
public string Resolve(string[] names, Outlook._MailItem mailItem, Outlook.OlMailRecipientType type)
{
string resolvedNames = string.Empty;
Outlook.Recipients or = mailItem.Recipients;
//Add recipients
foreach (string strName in names)
{
try
{
if (string.IsNullOrEmpty(strName))
continue;
Outlook.Recipient rec = or.Add(strName);
// if cannot be resolved remove from the recipients collection
rec.Resolve();

if (!rec.Resolved)
{
rec.Delete();
}
else
{
//type = cc
rec.Type = (int)type;
resolvedNames += rec.Name + ";";

}
}
catch (System.Exception)
{
}
}
return resolvedNames;
}

void outlookApp_ItemSend(object Item, ref bool Cancel)
{
try
{
// outlookApp.ItemSend -= new Microsoft.Office.Interop.Outlook.ApplicationEvents_10_ItemSendEventHandler(m_olApp_ItemSend);

Outlook._MailItem oMailItem = Item as Outlook._MailItem;

string toIds = string.Empty;
string ccIds = string.Empty;
foreach (Outlook.Recipient rec in oMailItem.Recipients)
{
if (rec.Type == 1)
toIds += rec.Name + ";";
else if (rec.Type == 2)
ccIds += rec.Name + ";";
}

if (MessageSent != null)
this.MessageSent(oMailItem, new MessageSentEventArgs(oMailItem.Subject, toIds, ccIds));
}
finally
{
outlookNameSpace.Logoff();
outlookNameSpace = null;
outlookApp = null;
}
}


public void SendMail(string toAddress, string body)
{
SendMail(toAddress, "SecurityTool Support", body);
}

public void SendMail(string toAddress, string subject, string body)
{
SendMail(toAddress, "", subject, body, null);
}

public void SendMail(string toAddress, string ccAdress, string subject, string body)
{
SendMail(toAddress, ccAdress, subject, body, null);
}

public void SendMail(string toAddress, string ccAdress, string subject, string body, IList attachments)
{
SendMail(toAddress, ccAdress, subject, body, attachments, null);
}

public void SendMail(string toAddress, string ccAdress, string subject, string body, IList attachments, IList attachmentsDisplayNames)
{
try
{
Logger.Debug("Create the mail item...");
// Creates a new MailItem object
mailItem = (Outlook._MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);

//resolve the address to make sure we don't have any junk values.
toAddress = Resolve(toAddress.Split(';'), mailItem, Outlook.OlMailRecipientType.olTo);

if(toAddress == string.Empty)
throw new MailException("Unable to resolve the name");
// mailItem.To = toAddress;
//resolve the address to make sure we don't have any junk values.
ccAdress = Resolve(ccAdress.Split(';'), mailItem, Outlook.OlMailRecipientType.olCC);
//oMailItem.Recipients.Remove(2);

// mailItem.CC = ccAdress;
mailItem.Subject = subject;
mailItem.Body = body;
mailItem.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatRichText;
mailItem.SaveSentMessageFolder = maipFolder;

if (attachments != null && attachments.Count > 0)
{
for (int i = 0, iPosition = mailItem.Body.Length + 1; i < attachments.Count; i++, iPosition++)
{
string fileName = attachments[i];

int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
mailItem.Attachments.Add(attachments[i], iAttachType, iPosition, attachmentsDisplayNames[i]);
Logger.Debug("Adding the attachment " + fileName);
}
}
Logger.Debug("Sending the mail item");
// adds it to the outbox
mailItem.Send();
Logger.Debug("EMail sent successfully to " + toAddress);
}
catch (Exception e)
{
throw new MailException(e.Message, e);
}
finally
{

//Logger.Debug("Disposing outlook objects...");
//oMailItem = null;
//m_olSentFolder = null;
//m_olNameSpace.Logoff();
//m_olNameSpace = null;
//m_olApp = null;
}
}

//public static void SendMail(string body)
//{
// try
// {
// MailMessage msg = new MailMessage("prashkum@lehman.com", "prashkum@lehman.com", "SecurityTool Error Report", body);

// //Environment.GetEnvironmentVariable("Temp")+"\\SecurityPricing.log";
// string logFile = "C:\\Edit Sets to Group Error.txt";//GetCurrentLogFileName();

// // Create the file attachment for this e-mail message.
// Attachment attData = new Attachment(logFile, MediaTypeNames.Application.Octet);
// // Add time stamp information for the file.
// ContentDisposition disposition = attData.ContentDisposition;
// disposition.CreationDate = System.IO.File.GetCreationTime(logFile);
// disposition.ModificationDate = System.IO.File.GetLastWriteTime(logFile);
// disposition.ReadDate= System.IO.File.GetLastAccessTime(logFile);

// msg.Attachments.Add(attData);

// smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
// smtpClient.Send(msg);
// }
// catch (Exception ex)
// {

// }
//}


}

///
/// Exception wrapper for any exceptions thrown from IMailHandler
///

public class MailException : System.Exception
{
public MailException()
{
}

public MailException(string message)
: base(message)
{
}

public MailException(string message, Exception innerException)
: base(message, innerException)
{
}
}

public class MessageSentEventArgs : EventArgs
{
private string m_subject;
private string m_to;
private string m_cc;

public MessageSentEventArgs(string subject, string to, string cc)
{
this.m_subject = subject;
this.m_to = to;
this.m_cc = cc;
}

public string Subject
{
get
{
return m_subject;
}
set
{
m_subject = value;
}
}

public string To
{
get
{
return m_to;
}
set
{
m_to = value;
}
}

public string CC
{
get
{
return m_cc;
}
set
{
m_cc = value;
}
}
}
}



Use the send method from the above class to send mails from the outlook

Get Screenshot

Create a Util class as below

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;

namespace Utils
{
///
/// Provides functions to capture the entire screen, or a particular window, and save it to a file.
///

public class ScreenCapture
{
///
/// Creates an Image object containing a screen shot of the entire desktop
///

///
public Image CaptureScreen()
{
return CaptureWindow(User32.GetDesktopWindow());
}

///
/// Creates an Image object containing a screen shot of a specific window
///

/// The handle to the window. (In windows forms, this is obtained by the Handle property)
///
public Image CaptureWindow(IntPtr handle)
{
// get te hDC of the target window
IntPtr hdcSrc = User32.GetWindowDC(handle);
// get the size
User32.RECT windowRect = new User32.RECT();
User32.GetWindowRect(handle, ref windowRect);
int width = windowRect.right - windowRect.left;
int height = windowRect.bottom - windowRect.top;
// create a device context we can copy to
IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
// create a bitmap we can copy it to,
// using GetDeviceCaps to get the width/height
IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, width, height);
// select the bitmap object
IntPtr hOld = GDI32.SelectObject(hdcDest, hBitmap);
// bitblt over
GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, GDI32.SRCCOPY);
// restore selection
GDI32.SelectObject(hdcDest, hOld);
// clean up
GDI32.DeleteDC(hdcDest);
User32.ReleaseDC(handle, hdcSrc);
// get a .NET image object for it
Image img = Image.FromHbitmap(hBitmap);


int cursorX = 0, cursorY = 0;
using (Bitmap cursorImage = CaptureCursor(ref cursorX, ref cursorY))
using (Graphics g = Graphics.FromImage(img))
{
g.DrawImage(cursorImage, cursorX, cursorY, 32, 32);
}

// free up the Bitmap object
GDI32.DeleteObject(hBitmap);
return img;
}

static Bitmap CaptureCursor(ref int x, ref int y)
{
Bitmap bmp;
IntPtr hicon;
User32.CURSORINFO ci = new User32.CURSORINFO();
User32.ICONINFO icInfo;
ci.cbSize = Marshal.SizeOf(ci);
if (User32.GetCursorInfo(out ci))
{
if (ci.flags == User32.CURSOR_SHOWING)
{
hicon = User32.CopyIcon(ci.hCursor);
if (User32.GetIconInfo(hicon, out icInfo))
{
x = Control.MousePosition.X;
y = Control.MousePosition.Y;
x -= ((int)icInfo.xHotspot);
y -= ((int)icInfo.yHotspot);

// x = ci.ptScreenPos.x - ( (int)icInfo.xHotspot );
// y = ci.ptScreenPos.y - ( (int)icInfo.yHotspot );
Icon ic = Icon.FromHandle(hicon);
bmp = ic.ToBitmap();
return bmp;
}
}
}
return null;
}

///
/// Captures a screen shot of a specific window, and saves it to a file
///

///
///
///
public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format)
{
Image img = CaptureWindow(handle);
img.Save(filename, format);
}

///
/// Captures a screen shot of the entire desktop, and saves it to a file
///

///
///
public void CaptureScreenToFile(string filename, ImageFormat format)
{
Image img = CaptureScreen();
img.Save(filename, format);
}

///
/// Helper class containing Gdi32 API functions
///

private class GDI32
{

public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter

[DllImport("gdi32.dll")]
public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest,
int nWidth, int nHeight, IntPtr hObjectSource,
int nXSrc, int nYSrc, int dwRop);

[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth,
int nHeight);

[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleDC(IntPtr hDC);

[DllImport("gdi32.dll")]
public static extern bool DeleteDC(IntPtr hDC);

[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);

[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
}

///
/// Helper class containing User32 API functions
///

private class User32
{
[DllImport("user32.dll", EntryPoint = "CopyIcon")]
public static extern IntPtr CopyIcon(IntPtr hIcon);

[DllImport("user32.dll", EntryPoint = "GetIconInfo")]
public static extern bool GetIconInfo(IntPtr hIcon, out ICONINFO piconinfo);
[DllImport("user32.dll", EntryPoint = "GetCursorInfo")]
public static extern bool GetCursorInfo(out CURSORINFO pci);

[StructLayout(LayoutKind.Sequential)]
public struct CURSORINFO
{
public Int32 cbSize; // Specifies the size, in bytes, of the structure.
public Int32 flags; // Specifies the cursor state. This parameter can be one of the following values:
public IntPtr hCursor; // Handle to the cursor.
public POINT ptScreenPos; // A POINT structure that receives the screen coordinates of the cursor.
}

[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public Int32 x;
public Int32 y;
}

public const Int32 CURSOR_SHOWING = 0x00000001;

[StructLayout(LayoutKind.Sequential)]
public struct ICONINFO
{
public bool fIcon; // Specifies whether this structure defines an icon or a cursor. A value of TRUE specifies
public Int32 xHotspot; // Specifies the x-coordinate of a cursor's hot spot. If this structure defines an icon, the hot
public Int32 yHotspot; // Specifies the y-coordinate of the cursor's hot spot. If this structure defines an icon, the hot
public IntPtr hbmMask; // (HBITMAP) Specifies the icon bitmask bitmap. If this structure defines a black and white icon,
public IntPtr hbmColor; // (HBITMAP) Handle to the icon color bitmap. This member can be optional if this
}

[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}

[DllImport("user32.dll")]
public static extern IntPtr GetDesktopWindow();

[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr hWnd);

[DllImport("user32.dll")]
public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);

[DllImport("user32.dll")]
public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);
}
}
}


Create an Util Method as below

///
/// Creates a screenshot of the main application UI and returns the temp filename.
///

///
public static string GetScreenshot()
{
// Attempt to get a screenshot saved into a temproary file
string imageFilename = string.Empty;
try
{
IntPtr hwndMain = Process.GetCurrentProcess().MainWindowHandle;
if (hwndMain != IntPtr.Zero)
{
ScreenCapture capture = new ScreenCapture();

string filename = Path.GetTempFileName();
filename += ".jpg";
capture.CaptureWindowToFile(hwndMain, filename, ImageFormat.Jpeg);
imageFilename = filename;

//Debug.WriteLine("Image: " + m_imageFilename);
}
}
catch (Exception)
{
}

return imageFilename;
}


calling the above method where ever required