Archive for May, 2008

How to send mail in C# ?

May 26, 2008

Often a c# programmer has to write code to send e-mails. This feature is required in many scenarios such as sending a mail once a scheduled job is over or sending a mail after the daily builds are done etc. Here is a sample code that can be used to send emails using C#.


using System.Net.Mail;

namespace EmailHelper
{
public static class EMail
{
public static void SendMail()
{
// Create mail message object
MailMessage mail = new MailMessage();
// Add the FROM address
mail.From = new MailAddress("sender@mail.com");
// Add TO address
mail.To.Add(new MailAddress("me@mail.com"));
// Enter the subject
mail.Subject = "This is a test Mail.";
// Enter body of email
mail.Body = "This is the body of the test mail.";
// Put smtp server you will use
SmtpClient smtpServer = new SmtpClient("SMTP Host");
// Send the mail
smtpServer.Send(mail);
}
}
}

In the above code we make use of System.Net.Mail namespace. In the SendMail method, we first create a mail message using the MailMessage class and then send it using the SmtpClient. A SMTP server is specified which is used to send mails.

Comments are Welcome !

Advertisements

How to secure .NET Remoting communication ?

May 26, 2008

Often we require securing the .NET remoting communication. Here is a fantastic article that will enable you to secure .net remoting communication using asymmetric encryption and decryption.

Visit: http://msdn.microsoft.com/en-us/magazine/cc300447.aspx

All New Microsoft Forums !!!

May 15, 2008

Microsoft has proposed to launch new MSDN forums : MSDN TechNet Expression Microsoft. The existing posts will be moved to the new forums in May. The points that are gained by the users will be preserved. A Sandbox forum, where you can create threads and try out functionality, and a suggestions forum where you can give your feedback.

How to get Printer Submitted Jobs in C# ?

May 14, 2008

Here is a handy method that gives you a collection of all the jobs submitted to the printer. This method uses the ManagementObjectSearcher and the ManagementObjectCollection classes from the .NET framework. The query “SELECT * FROM Win32_PrintJob” is used to get a collection of the submitted jobs. These jobs are added to a StringCollection and this collection is returned back.


#region GetPrintJobsCollection

/// <summary>
/// Returns the jobs in printer queue
/// </summary>
/// <param name="printerName">Printer Name.</param>
/// <returns>StringCollection</returns>
public StringCollection GetPrintJobsCollection(string printerName)
{
StringCollection printJobCollection = new StringCollection();
try
{
//Query the printer to get the files waiting to print.
string searchQuery = "SELECT * FROM Win32_PrintJob";

ManagementObjectSearcher searchPrintJobs = new ManagementObjectSearcher(searchQuery);
ManagementObjectCollection prntJobCollection = searchPrintJobs.Get();


foreach (ManagementObject prntJob in prntJobCollection)
{
String jobName = prntJob.Properties["Name"].Value.ToString();

//Job name would be of the format [Printer name], [Job ID]
char[] splitArr = new char[1];
splitArr[0] = Convert.ToChar(",");
string prnName = jobName.Split(splitArr)[0];
string documentName = prntJob.Properties["Document"].Value.ToString();
if (String.Compare(prnName, printerName, true) == 0)
{
printJobCollection.Add(documentName);
}
}
}
catch (Exception ex)
{
// Log the exception.
}
return printJobCollection;
}

#endregion GetPrintJobsCollection

How to Cancel Printing in C# ?

May 12, 2008

In the previous blog post we have seen How to print a file/string in C#. In this post we would be looking at how to cancel a print job submitted to the printer. These are some of the common functionalities required in most applications.

For cancellation of the printer job we will be using the System.Management namespace of the .NET framework. Using the ManagementObjectSearcher class we will get a list of all the queued printer jobs. Then using the ManagementObject we will delete the appropriate printer job. Please note that for Cancellation of a printer job, the JobName or JobID is required. Please find below the function that accepts a jobID and then deletes that job from the printer queue. A Boolean true value is returned if successful in deleting the job else a false value is returned.

Remember to Add a Reference to the System.Management .Net assembly.

#region CancelPrintJob

/// <summary>
/// Cancel the print job. This functions accepts the job number.
/// An exception will be thrown if access denied.
/// </summary>
/// <param name="printJobID">int: Job number to cancel printing for.</param>
/// <returns>bool: true if cancel successfull, else false.</returns>
public bool CancelPrintJob(int printJobID)
{
// Variable declarations.
bool isActionPerformed = false;
string searchQuery;
String jobName;
char[] splitArr;
int prntJobID;
ManagementObjectSearcher searchPrintJobs;
ManagementObjectCollection prntJobCollection;
try
{
// Query to get all the queued printer jobs.
searchQuery = "SELECT * FROM Win32_PrintJob";
// Create an object using the above query.
searchPrintJobs = new ManagementObjectSearcher(searchQuery);
// Fire the query to get the collection of the printer jobs.
prntJobCollection = searchPrintJobs.Get();

// Look for the job you want to delete/cancel.
foreach (ManagementObject prntJob in prntJobCollection)
{
jobName = prntJob.Properties["Name"].Value.ToString();
// Job name would be of the format [Printer name], [Job ID]
splitArr = new char[1];
splitArr[0] = Convert.ToChar(",");
// Get the job ID.
prntJobID = Convert.ToInt32(jobName.Split(splitArr)[1]);
// If the Job Id equals the input job Id, then cancel the job.
if (prntJobID == printJobID)
{
// Performs a action similar to the cancel
// operation of windows print console
prntJob.Delete();
isActionPerformed = true;
break;
}
}
return isActionPerformed;
}
catch (Exception sysException)
{
// Log the exception.
return false;
}
}

#endregion CancelPrintJob

What is hallucination?

May 9, 2008

A hallucination is the brain’s reception of a false sensory input. This essentially means that the person having a hallucination is experiencing an event through one of their senses that is not occurring in the real world. This can be through any of the senses. When auditory hallucinations are examined, the most common are hearing one’s own thoughts as if they were being spoken aloud, followed by hearing one’s name being called by a voice when alone.

Common hallucinations include:

  • Feeling a crawling sensation on the skin
  • Hearing voices when no one has spoken
  • Seeing patterns, lights, beings, or objects that aren’t there

Hallucinations related to smell or taste are rare.

There are many causes of hallucinations, including:

  • Being drunk or high, or coming down from such drugs as marijuana, LSD, cocaine or crack, heroin, and alcohol
  • Fever, especially in children and the elderly
  • Sensory problem, such as blindness or deafness
  • Severe illness, including liver failure, kidney failure, and brain cancer
  • Some psychiatric disorders, such as schizophrenia, psychotic depression, and post-traumatic stress disorder

All of us some time or the other experience hallucination in our life…

How to Format C#, VB Code for Blogger (HTML) ?

May 9, 2008

Hurrey !!! Here is a fantastic on-line tool that helps you format your C#, VB, XML code for your web site, blogs etc. This tool allows you to format your C#, VB, HTML, XML, T-SQL or MSH (code name Monad) code.
Thanks a ton to “manoli.net“!

Code Formatter: http://www.manoli.net/csharpformat

Great help to all on-line code contributors….

How to Print File/String in C# ?

May 9, 2008

A C# developer often requires developing an application or a feature in a product that will print the documents. Sometimes we require printing a single line using the printer, this situation may arise when we want to print some status on a pre-printed form. Here is a code which will print the file or print a string using the default printer installed on the machine.
Comments are added to each line of code so as to make it easy to understand !

========================CODE============================
#region Reference

using System;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
using System.Diagnostics;
// Add a reference to the System.Management dll.
using System.Management;

#endregion Reference

namespace PrinterHelper
{
/// <summary>
/// Contains common functions for accessing printer
/// </summary>
public class PrinterHelper
{
#region Member Variables & Method Signatures

// String data to be printed.
static string prnData = string.Empty;

//Add the printer connection for specified pName.
[DllImport("winspool.drv")]
public static extern bool AddPrinterConnection(string pName);

//Set the added printer as default printer.
[DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetDefaultPrinter(string Name);

#endregion Member Variables & Method Signatures

#region Public Methods
#region Print File
/// <summary>
/// Sends the file to the printer choosed.
/// </summary>
/// <param name="fileName">Name & path of the file to be printed.</param>
/// <param name="printerPath">The path of printer.</param>
/// <param name="numCopies">The number of copies send to printer.</param>
public bool PrintFile(string fileName, string printerPath, int numCopies)
{
// Check if the incomming strings are null or empty.
if (string.IsNullOrEmpty(fileName) string.IsNullOrEmpty(printerPath))
{
return false;
}

//Instantiate the object of ProcessStartInfo.
Process objProcess = new Process();
try
{
// Set the printer.
AddPrinterConnection(printerPath);
SetDefaultPrinter(printerPath);
//Print the file with number of copies sent.
for (int intCount = 0; intCount < numCopies; intCount++)
{
objProcess.StartInfo.FileName = fileName;
objProcess.StartInfo.Verb = "Print";
objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
objProcess.StartInfo.UseShellExecute = true;
objProcess.Start();
}
// Return true for success.
return true;
}
catch (Exception ex)
{
// Log the exception and return false as failure.
return false;
}
finally
{
// Close the process.
objProcess.Close();
}
}

#endregion Print File

#region SendStringToPrinter

/// <summary>
/// Sends a string to the printer.
/// </summary>
/// <param name="szString">String to be printed.</param>
/// <returns>Returns true on success, false on failure.</returns>
public bool SendStringToPrinter(string szString)
{
try
{
PrintDocument prnDocument;
string printername;
//Get the default printer name.
prnDocument = new PrintDocument();
printername = Convert.ToString(prnDocument.PrinterSettings.PrinterName);
if (string.IsNullOrEmpty(printername))
throw new Exception("No default printer is set.Printing failed!");
prnData = szString;
prnDocument.PrintPage += new PrintPageEventHandler(prnDoc_PrintPage);
prnDocument.Print();
return true;
}
catch (COMException comException)
{
//Log the exception
return false;
}
catch (Exception sysException)
{
//Log the exception
return false;
}
}

/// <summary>
/// Printes the page.
/// </summary>
/// <param name="sender">object : Sender event</param>
/// <param name="e">PrintPageEventArgs</param>
static void prnDoc_PrintPage(object sender, PrintPageEventArgs e)
{
System.Drawing.Font fnt = new System.Drawing.Font(System.Drawing.FontFamily.GenericSerif, 10);
e.Graphics.DrawString(prnData, fnt, System.Drawing.Brushes.Black, 0, 0);
}

#endregion SendStringToPrinter

#endregion Public Methods
}
}
Your comments are always welcome !