Tuesday, June 15, 2010

Reading a Unix file using C#.Net

private void button1_Click(object sender, EventArgs e)
{
MyFtp ftp = new MyFtp("hostname", "username", "password");
string buffer = string.Empty;
string x;
ftp.OpenFile("filepath", AccessMode.Read, TransferMode.Ascii);

while (ftp.ReadFile(out buffer))
{
x = buffer;
}

ftp.CloseFile();
ftp.Close();
}


// Wininet.cs
using System;
using System.Text;
using System.Runtime.InteropServices;

namespace FTP
{
///
/// Summary description for WinInet.
///

internal sealed class WinInet
{
public const int INTERNET_OPEN_TYPE_PRECONFIG = 0;
public const int INTERNET_OPEN_TYPE_DIRECT = 1;
public const int INTERNET_OPEN_TYPE_PROXY = 3;
public const short INTERNET_DEFAULT_FTP_PORT = 21;
public const int INTERNET_SERVICE_FTP = 1;
public const int FTP_TRANSFER_TYPE_ASCII = 0x01;
public const int FTP_TRANSFER_TYPE_BINARY = 0x02;
public const int GENERIC_WRITE = 0x40000000;
public const int GENERIC_READ = unchecked((int)0x80000000);
public const int MAX_PATH = 260;

[DllImport("wininet.dll", CharSet = CharSet.Auto,
SetLastError = true)]
public static extern IntPtr InternetOpen(
string lpszAgent,
int dwAcessType,
string lpszProxyName,
string lpszProxyBypass,
int dwFlags);

[DllImport("wininet.dll", CharSet = CharSet.Auto,
SetLastError = true)]
public static extern IntPtr InternetConnect(
IntPtr hInternet,
string lpszServerName,
short nServerPort,
string lpszUserName,
string lpszPassword,
int dwService,
int dwFlags,
ref int dwContext);

[DllImport("wininet.dll", CharSet = CharSet.Auto,
SetLastError = true)]
public static extern bool FtpGetCurrentDirectory(
IntPtr hConnect,
StringBuilder lpszCurrentDirectory,
ref int lpdwCurrentDirectory);

[DllImport("wininet.dll", CharSet = CharSet.Auto,
SetLastError = true)]
public static extern bool FtpSetCurrentDirectory(
IntPtr hConnect,
string lpszCurrentDirectory);

[DllImport("wininet.dll", CharSet = CharSet.Auto,
SetLastError = true)]
public static extern IntPtr FtpOpenFile(
IntPtr hConnect,
string lpszFileName,
int dwAccess,
int dwFlags,
out int dwContext);

[DllImport("wininet.dll", SetLastError = true)]
public static extern bool InternetWriteFile(
IntPtr hFile,
[MarshalAs(UnmanagedType.LPArray)] byte[] lpBuffer,
int dwNumberOfBytesToWrite,
out int lpdwNumberOfBytesWritten);

[DllImport("wininet.dll", SetLastError = true)]
public static extern bool InternetReadFile(
IntPtr hFile,
[MarshalAs(UnmanagedType.LPArray)] byte[] lpBuffer,
int dwNumberOfBytesToRead,
out int lpdwNumberOfBytesRead
);

[DllImport("wininet.dll", CharSet = CharSet.Auto,
SetLastError = true)]
public static extern bool InternetCloseHandle(IntPtr hInternet);

[DllImport("wininet.dll", CharSet = CharSet.Auto,
SetLastError = true)]
public static extern bool FtpPutFile(
IntPtr hConnect,
string lpszLocalFile,
string lpszNewRemoteFile,
int dwFlags,
out int dwContext);

[DllImport("wininet.dll", CharSet = CharSet.Auto,
SetLastError = true)]
public static extern bool FtpGetFile(
IntPtr hConnect,
string lpszRemoteFile,
string lpszLocalFile,
bool failIfExists,
int dwFlagsAttributes,
int dwFlags,
out int dwContext);

[DllImport("wininet.dll", CharSet = CharSet.Auto,
SetLastError = true)]

private WinInet()
{
}
}
}


// SimpleFtp.cs
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;

namespace FTP
{
[Flags()]
public enum AccessMode
{
Read = WinInet.GENERIC_READ,
Write = WinInet.GENERIC_WRITE,
}

public enum TransferMode
{
Ascii = WinInet.FTP_TRANSFER_TYPE_ASCII,
Binary = WinInet.FTP_TRANSFER_TYPE_BINARY,
}

///
/// Summary description for SimpleFTP.
///

public sealed class MyFtp : IDisposable
{
private IntPtr internet;
private IntPtr connection;
private IntPtr fileHandle;
private int context;

private const int BUFFER_SIZE = 2048;

public MyFtp(string host, string userName, string password)
{
internet = WinInet.InternetOpen(
null,
WinInet.INTERNET_OPEN_TYPE_DIRECT,
null,
null,
0);

if (internet == IntPtr.Zero)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}

connection = WinInet.InternetConnect(
this.internet,
host,
WinInet.INTERNET_DEFAULT_FTP_PORT,
userName,
password,
WinInet.INTERNET_SERVICE_FTP,
0,
ref this.context);

if (connection == IntPtr.Zero)
{
WinInet.InternetCloseHandle(this.internet);
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}

~SimpleFtp()
{
this.CleanUp();
}

void IDisposable.Dispose()
{
this.CleanUp();
GC.SuppressFinalize(this);
}

public string CurrentDirectory
{
get
{
StringBuilder path = new StringBuilder(260);
int bufferSize = path.Capacity;

if (!WinInet.FtpGetCurrentDirectory(this.connection,
path, ref bufferSize))
{
throw new
Win32Exception(Marshal.GetLastWin32Error());
}
return path.ToString();
}
set
{
if (!WinInet.FtpSetCurrentDirectory(this.connection,
value))
{
throw new
Win32Exception(Marshal.GetLastWin32Error());
}
}
}

public void Close()
{
((IDisposable)this).Dispose();
}

public void OpenFile(string fileName, AccessMode access,
TransferMode mode)
{
this.fileHandle = WinInet.FtpOpenFile(this.connection,
fileName, (int)access, (int)mode, out this.context);
if (this.fileHandle == IntPtr.Zero)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}

public void CloseFile()
{
if (this.fileHandle != IntPtr.Zero)
{
if (WinInet.InternetCloseHandle(this.fileHandle))
{
this.fileHandle = IntPtr.Zero;
}
else
{
throw new
Win32Exception(Marshal.GetLastWin32Error());
}
}
}

public int WriteFile(string buffer)
{
byte[] bytes = new ASCIIEncoding().GetBytes(buffer);
return this.WriteFile(bytes);
}

public int WriteFile(byte[] buffer)
{
int byteCount;
if (!WinInet.InternetWriteFile(this.fileHandle, buffer,
buffer.Length, out byteCount))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return byteCount;
}

public bool ReadFile(out string buffer)
{
// clear the buffer...
buffer = string.Empty;

// read from the file
int bytesRead;
byte[] readBuffer = new byte[SimpleFtp.BUFFER_SIZE];
bool success = WinInet.InternetReadFile(this.fileHandle,
readBuffer, readBuffer.Length, out bytesRead);

// the call failed!
if (!success)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}

// we got some data, so convert it for the return...
if (bytesRead != 0)
{
buffer = Encoding.ASCII.GetString(readBuffer, 0,
bytesRead);
}

return (bytesRead != 0) ? true : false;
}

public bool ReadFile(byte[] buffer)
{
int bytesRead;
bool success = WinInet.InternetReadFile(this.fileHandle,
buffer, buffer.Length, out bytesRead);
if (!success)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return (bytesRead != 0) ? true : false;
}

public void GetFile(string localFile, string remoteFile, bool
fail)
{
GetFile(localFile, remoteFile, TransferMode.Ascii, fail);
}

public void GetFile(string localFile, string remoteFile,
TransferMode mode, bool fail)
{
if (!WinInet.FtpGetFile(connection, remoteFile, localFile,
fail, 0, (int)mode, out context))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}

public void PutFile(string localFile, string remoteFile)
{
this.PutFile(localFile, remoteFile, TransferMode.Ascii);
}

public void PutFile(string localFile, string remoteFile,
TransferMode mode)
{
if (!WinInet.FtpPutFile(this.connection, localFile,
remoteFile, (int)mode, out this.context))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}

private void CleanUp()
{
if (this.fileHandle != IntPtr.Zero)
{
WinInet.InternetCloseHandle(this.fileHandle);
}

if (this.connection != IntPtr.Zero)
{
WinInet.InternetCloseHandle(this.connection);
}

if (this.internet != IntPtr.Zero)
{
WinInet.InternetCloseHandle(this.internet);
}
}
}
}

Friday, November 27, 2009

Parsing CSV string using C#

public static string[] SplitCSV(string s)
{
List list = new List();
StringBuilder work = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (c == '"')
{
int p2;
while (true)
{
p2 = s.IndexOf('"', i + 1);
work.Append(s.Substring(i + 1, p2 - i - 1));
i = p2;

// If this is a double quote, keep going!
if (((p2 + 1) < s.Length) && (s[p2 + 1] == '"'))
{
work.Append('"');
i++;

// otherwise, this is a single quote, we're done
}
else
{
break;
}
}
}
else if (c == ',')
{
list.Add(work.ToString());
work.Length = 0;
}
else
{
work.Append(c);
}
}
list.Add(work.ToString());
return list.ToArray();
}

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

Thursday, April 30, 2009

Set ProgressBar properties in a Thread

delegate void SetControlValueCallback(Control oControl, string propName, object propValue);
private void SetControlPropertyValue(Control oControl, string propName, object propValue)
{
if (oControl.InvokeRequired)
{
SetControlValueCallback d = new SetControlValueCallback(SetControlPropertyValue);
oControl.Invoke(d, new object[] { oControl, propName, propValue });
}
else
{
Type t = oControl.GetType();
PropertyInfo[] props = t.GetProperties();
foreach (PropertyInfo p in props)
{
if (p.Name.ToUpper() == propName.ToUpper())
{
p.SetValue(oControl, propValue, null);
}
}
}
}


Thread thread = new Thread(new ThreadStart(Generate));
thread.Name = "Generate";
thread.IsBackground = true;
thread.Start();


The control properties like progressbar properties can be set in Generate Method


SetControlPropertyValue(progressBar1, "Visible", true);
SetControlPropertyValue(progressBar1, "Minimum", 0);
SetControlPropertyValue(progressBar1, "Maximum", dtCompareSets.Rows.Count);

Tuesday, April 28, 2009

Authenticate the logged on windows user

string userId = Environment.UserName;

public class Authenticate
{
[DllImport("SenaInet.dll")]
static extern int getAuthToken (string tokentype, StringBuilder tokenbuf,ref long tokenbuflen, StringBuilder idbuf, ref long idbuflen);

public static string UserToken()
{
String tokenType = "ldap";
String userid;
String token;
int retcode = 0;
long tbuflen = 16000;
StringBuilder tbuf = new StringBuilder (Convert.ToInt32 (tbuflen));
long ibuflen = 16000;
StringBuilder ibuf = new StringBuilder (Convert.ToInt32 (ibuflen));
retcode = getAuthToken(tokenType,tbuf,ref tbuflen,ibuf,ref ibuflen);
token = tbuf.ToString();
return token;
}
}