Wednesday, September 30, 2009

Open Outlook with New email - Console Application

Although there are some methodes in System.Web.Mail namespace for sending email , but sometimes customers like to open outlook automatically with a new mail inside and let user to complete the mail before sending, here I write a sample console application to do it,

note: add outlook com reference manually to your project.
 

using System;
using  System.Collections.Generic;
using  System.Text;
using  System.Diagnostics;
using  Outlook = Microsoft.Office.Interop.Outlook;

namespace Openoutlook
{
class Program
{
static void Main(string[] args)
{
Outlook.
Application objOutlk = new Outlook.Application();
object objMail = new object();
Outlook.
MailItem mic = (Outlook.MailItem)(objOutlk.CreateItem(Outlook.OlItemType.olMailItem));
//mic.To = //toTextBox.Text;
//mic.CC = ccTextBox.Text;
//mic.BCC = bccTextBox.Text;
mic.Subject ="Test Subject";// subjectTextBox.Text;
mic.Importance = Outlook.
OlImportance.olImportanceNormal;

// mic.HTMLBody = sb.ToString();
// Adds Attachment to the Mail Message.

// All you need to do is to declare this relative to the number of attachments you have.
mic.Attachments.Add( @"C:\temp\1.txt", Outlook.OlAttachmentType.olByValue, 1, "Attachment Name");
mic.Attachments.Add( @"C:\temp\2.txt", Outlook.OlAttachmentType.olByValue, 1, "Attachment Name");
//Open outlook and display new msg mail

mic.Display(mic);


}
}
}
----------------------------
I did not fill all field such as body , To or CC , you can fill the by your self.

Sunday, September 27, 2009

Adding Row Number to GridView - ASP.NET

GridView is a control which is used in all applications, most of the time showing a Row number in the left side of each row is needed. after adding a gridview on your aspx page then you should add template column , do the following things.
As the picture shows , you should set "Container.DataItemIndex + 1"  to Text property of Label within a asp:TemplateField in Columns .



Clear Form method - Windows Form

Clearing form data is one the methodes that developers sould write over and over, in this case writing a method which can be used in all forms is helpful, via this is a recursive method and depend on control type (textbox or dropdownlist ,...) it clear it's data.

public static void ClearForm(Control parent)
{
foreach (System.Windows.Forms.Control ctrControl in parent.Controls)
{
//Loop through all controls
if (object.ReferenceEquals(ctrControl.GetType(), typeof(System.Windows.Forms.TextBox)))
{
//Check to see if it's a textbox
((System.Windows.Forms.TextBox)ctrControl).Text = string.Empty;
//If it is then set the text to String.Empty (empty textbox)
}
else if (object.ReferenceEquals(ctrControl.GetType(), typeof(System.Windows.Forms.RichTextBox)))
{
//If its a RichTextBox clear the text
((System.Windows.Forms.RichTextBox)ctrControl).Text = string.Empty;
}
else if (object.ReferenceEquals(ctrControl.GetType(), typeof(System.Windows.Forms.ComboBox)))
{
//Next check if it's a dropdown list
((System.Windows.Forms.ComboBox)ctrControl).SelectedIndex = -1;
//If it is then set its SelectedIndex to 0
}
else if (object.ReferenceEquals(ctrControl.GetType(), typeof(System.Windows.Forms.CheckBox)))
{
//Next uncheck all checkboxes
((System.Windows.Forms.CheckBox)ctrControl).Checked = false;
}
else if (object.ReferenceEquals(ctrControl.GetType(), typeof(System.Windows.Forms.RadioButton)))
{
//Unselect all RadioButtons
((System.Windows.Forms.RadioButton)ctrControl).Checked = false;
}
if (ctrControl.Controls.Count > 0)
{
//Call itself to get all other controls in other containers
ClearForm(ctrControl);
}
}
}

Saturday, September 26, 2009

Convert TIF file to JPG(s) - ASP.NET

Sometimes showing a buch of JPG images is easier than a TIF file on your site, or sometimes you want to show the first page of a TIF file to give the better sense of the contain of TIF file, so you see this Conversion help you for more suitable designing your asp.net applicaion.
For creating a jpg file ftom a multiple page tif file you shouldn't go though While loop and just convert the first page.

Note: In this example I could'nt use "<" or ">" tage and use "/" instead :)
public class ConvertImages
{
public ConvertImages()
{
}
///
/// This function return list of images which is converted from a TIF file
/// for using this function,the best way to itarate on returned list is using for each statement
/// within the iteration you should Dispose each image.
///

///


Full path of TIF file such as :\Temp\MyFile.tif
///


the path folder which the images should be create
///
public static List /Image/ ConvertTIFtoJPGs(string TIFFileFullName,string OutPutFolder)
{
System.Drawing.Image objImage,NewImage;
Guid objGuid;
System.Drawing.Imaging.FrameDimension objDimension;
List ImageList;
string OutputFileName;
int TotalFrames = 0;
int ItemIndex = 0;
objImage = Image.FromFile(TIFFileFullName);
objGuid = objImage.FrameDimensionsList[0];
objDimension = new System.Drawing.Imaging.FrameDimension(objGuid);
TotalFrames = objImage.GetFrameCount(objDimension);
ImageList = new List / image/ (TotalFrames);
while (ItemIndex < TotalFrames) { objImage.SelectActiveFrame(objDimension, ItemIndex); OutputFileName = OutPutFolder + @"\" + Guid.NewGuid().ToString() + ".JPG"; objImage.Save(OutputFileName, System.Drawing.Imaging.ImageFormat.Jpeg); NewImage = Image.FromFile(OutputFileName); ImageList.Add(NewImage); ItemIndex++; } objImage.Dispose(); return ImageList; } } //Here I write a test procedure in another class to test above class
private void Test_TIF2JPGConversion()
{

List/Image/ imageList;
imageList =ConvertImages.ConvertTIFtoJPGs(@"C:\Temp\MyTIF.JPG", C:\Temp\Images"); foreach (Image imageItem in imageList)
{

//Do something with images, such as storing or anything else

//Remember to dispose each image
imageItem.Dispose();
}

Friday, September 25, 2009

Storing Application Message Staticly - ASP.NET - C#

Having a list of messages is always required within application, there are many ways to implement a message list. First of all you should categorized the messages such as Info ,Warnings , Errors , ... . may be you think the best way is saving messages in database but what if the database is down ,so we couldnt access to our messages, or saving all messages in XML file, what if the XML file is deleted , so you see we should prepare a general solution to satisfy all of the situations, here I'm going to implement a list of messages in the application staticly to store a critical messages ,in this case we could sure the list is always available. later I will implement a general solution which consists Database/XML Message list and types and Static message list in the application.

First of all we should prepare SystemMessage Class which contains messages, then we you should prepare the EntityBase class which inherits from Web.UI.page class and has a private SystemMessage member, then all of the other classes and pages should be inherited from BaseEntityClass. Here is the sample Class Diagram and Code :

Class Diagram for Message Listpublic class BaseEntity: System.Web.UI.Page
{
private SystemMessage sm;
protected BaseEntity()
{
sm = new SystemMessage();
}
///


/// Define Message by index
///
public string Message(int MessageIndex)
{
return sm[MessageIndex];
}
}

//--------------------------------------------------

public class SystemMessage
{
private static System.Collections.Generic.Dictionary _MessageList=null;
public SystemMessage()
{
_MessageList = new System.Collections.Generic.Dictionary();
_MessageList.Add(1, "Error #16576");
_MessageList.Add(2, "Add record to database");
_MessageList.Add(3, "Warning , this field already exist in database");
_MessageList.Add(4, "Try later!");
}

//Define Readonly indexer for this class
public string this[int index]
{
get
{
if (_MessageList.ContainsKey(index) == true)
return _MessageList[index];
return index.ToString() + " does not exist in the message list";
}
}
}

//-----------------------------------------------
//Now we are in Default.aspx.cs class can access our message list by typing just Message( MessageIndex )

public partial class _Default : BaseEntity
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Message(2));
}
}

Then you should see "Add record to database" text in your page.

In the EntityBase class you could add other methods which are required in the application such as check user access or Logging methods.

Authenticate user via Active Directory - ASP.NET - C#

Authentication is one of most important process of asp.net application ,there are four modes which can be defined in web.config file, "Passport", "Windows", "Forms" and "None".
many applications use Forms Mode which means you should design a login.aspx page and user enter username and password , however many useres suffer to memorize many user name and password for working with applications, one of the most suitable way to release from this problem is used the same user name and password which users use to logon to his/her computer , I mean the same user name and password in Active Directory. using this class provides this facility for the application. just create an instance of the class and call IsExistedDomainUser function.

using System;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.DirectoryServices;


///
/// User can be authenticated with existing User Name and password in Active Directory
/// LdapPath such as LDAP://ServerName/DC=MyCompany,DC=COM
///
public class LDAPAuthentication
{
string _LdapPath;
string _FilterAttribute;


public LDAPAuthentication(string LdapPath)
{
_LdapPath = LdapPath;

}

public bool IsExistedDomainUser(System.Web.HttpResponse Response, string strUsername, string strDomain, string strPassword, bool isCookiePersistent)
{

if (IsAuthenticated(strDomain, strUsername, strPassword) == true)
{

//Create the ticket, and add the groups.
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, strUsername, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, FormsAuthentication.FormsCookiePath);

//Encrypt the ticket.
string strEncryptedTicket = FormsAuthentication.Encrypt(authTicket);

//Create a cookie, and then add the encrypted ticket to the cookie as data.
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEncryptedTicket);

if (isCookiePersistent == true)
authCookie.Expires = authTicket.Expiration;

//Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie);

//If user registerd in Doamin
return true;
}
else
//If user does not registerd in Doamin
return false;

}

private bool IsAuthenticated(string domain, string username, string pwd)
{
string domainAndUsername = domain + "\\" + username;
DirectoryEntry entry = new DirectoryEntry(_LdapPath, domainAndUsername, pwd);
try
{
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if ((result == null))
{
return false;
}
_LdapPath = result.Path;
_FilterAttribute = ((string)result.Properties["cn"][0]);
}
catch
{
throw new Exception("Incorrect User name or passowrd, try again!");
}
return true;
}
}
//-----------------------------------------------------------------
changing Web.Config and set your logon form name with the following syntax
Logon page in this example is Logon.aspx in the
authentication tag
forms name="AuthCookie" loginUrl="Logon.aspx"

Add CopyRight Label to the Images - ASP.NET

Add CopyRight label to the images in the site sometimes is mandatory, you can change all images and add copyright label on some programs such as microsoft paint /adobe photoshop and ... and you should always do the same thing in this way, there is another way in .NET which help you not to do this fraustraiting job and use the following class in your project ,add specific Copyright label to the image, and everytime the user requests an image call the following function whithin a class. This sample is my favorite one :-)
Sample Image :



Adding copyright label to the image

public class ChangeImage
{
public System.Drawing.Image AddCopyRightToImage(System.Drawing.Image img)
{

// Define the Bitmap, Graphics, Font, and Brush for copyright logo
Graphics g = Graphics.FromImage(img);
Font f = new Font("Arial", 9);

// Create the foreground text brush
Brush b = new SolidBrush(Color.White);

// Create the backround text brush
Brush bb = new SolidBrush(Color.White);

// Add the copyright text background
string ct = "Copyright 2009, Company Name , Inc.";

//Set Label Alighnment
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;

// Add the copyright text foreground
g.DrawString(ct, f, b, img.Width / 2, 20, sf);

g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);

return img;

}
}

Thursday, September 24, 2009

Impersonate User in Active Directory - ASP.NET

Via the following class you can athenticate s specific user to specific domain and after that you access the resources (such as Doc or anything else) , and finally call UndoImpersotae function to disconnect athenticated user.

For inctance your application is installed on AppServer.WemDomain.local and you need to access some resources on FileServer.FileDomain.local , so you should have a user in FileDomain.local and then authenticate it and access to the resources and then close athentication proccess all these thing is happened in background and the user could not understand where the file come from.

public class ImpersonateUser_ActiveDirectory
{

public const int LOGON32_LOGON_INTERACTIVE = 9;
public const int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext impersonationContext;
[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);

//Athenticate specific user in Active Directory
public bool impersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}

//Undo authentication for authenticated user
private void undoImpersonation()
{
impersonationContext.Undo();
}
}

--------------------------------------------------------

you can save user info and domain info in Web.config and read these information with the following syntax

string UserName = ConfigurationSettings.AppSettings["UserName"];

Changing Image Scale And Resolution - ASP.NET

Storing image on a optimized size and resolution(network administrator sense it) or transfering optimized images on a limited network capacity allways affect the application performace(Network administrator and all Users sense it).


using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace ChangingImage
{
public class ImageResize
{
private ImageResize() { }
//Scale the image to a percentage of its actual size.
public static Image ScaleByPercentage(Image img, double percent)
{
double fractionalPercentage = (percent / 100.0);
int outputWidth = (int)(img.Width * fractionalPercentage);
int outputHeight = (int)(img.Height * fractionalPercentage);
return ImageResize.ScaleImage(img, outputWidth, outputHeight);
}
//Scale down the image till it fits the given size.
public static Image ScaleDownTillFits(Image img, Size size)
{
Image ret = img;
bool bFound = false;
if ((img.Width > size.Width) (img.Height > size.Height))
{
for (double percent = 100; percent > 0; percent--)
{
double fractionalPercentage = (percent / 100.0);
int outputWidth = (int)(img.Width * fractionalPercentage);
int outputHeight = (int)(img.Height * fractionalPercentage);
if ((outputWidth < bfound =" true;" ret =" ImageResize.ScaleImage(img," ret =" ImageResize.ScaleImage(img," color="#33cc00">//Scale an image by a set width. The height will be set proportionally.
public static Image ScaleByWidth(Image img, int width)
{
double fractionalPercentage = ((double)width / (double)img.Width);
int outputWidth = width;
int outputHeight = (int)(img.Height * fractionalPercentage);
return ImageResize.ScaleImage(img, outputWidth, outputHeight);
}
//Scale an image by a set height. The width will be set proportionally.
public static Image ScaleByHeight(Image img, int height)
{
double fractionalPercentage = ((double)height / (double)img.Height);
int outputWidth = (int)(img.Width * fractionalPercentage);
int outputHeight = height;
return ImageResize.ScaleImage(img, outputWidth, outputHeight);
}
//Scale an image by a set Height and set Specific Resolution. The width will be set proportionally.
public static Image ScaleByHeightAndResolution(Image img, int height,float Resolution)
{
double fractionalPercentage = ((double)height / (double)img.Height);
int outputWidth = (int)(img.Width * fractionalPercentage);
int outputHeight = height;
return ImageResize.ScaleImageAndResolution(img, outputWidth, outputHeight,Resolution);
}
//Scale an image to a given width and height.
public static Image ScaleImage(Image img, int outputWidth, int outputHeight)
{
Bitmap outputImage = new Bitmap(outputWidth, outputHeight, img.PixelFormat);
outputImage.SetResolution(img.HorizontalResolution, img.VerticalResolution);
Graphics graphics = Graphics.FromImage(outputImage);
graphics.InterpolationMode = InterpolationMode.Bilinear;
graphics.DrawImage(img, new Rectangle(0, 0, outputWidth, outputHeight), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
graphics.Dispose();
return outputImage;
}

//Change image scale by Width and Height and Set New Resoltion too.
public static Image ScaleImageAndResolution(Image img, int outputWidth, int outputHeight,float Resolution)
{
Bitmap outputImage = new Bitmap(outputWidth, outputHeight, img.PixelFormat);
outputImage.SetResolution(Resolution, Resolution);
Graphics graphics = Graphics.FromImage(outputImage);
Graphics.InterpolationMode = InterpolationMode.Bilinear;
graphics.DrawImage(img, new Rectangle(0, 0, outputWidth, outputHeight), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
graphics.Dispose();
return outputImage;
}
}
}