May 28, 2010

Send An Email Using Outlook

See KB Article 310263
Add a reference to Microsoft.Office.Interop.Outlook then use following code:
using Outlook = Microsoft.Office.Interop.Outlook;

public void SendPlainFormatEmail(
  string recipient, 
  string subject, 
  string body, 
  string filePath, 
  bool silently)
{
    try
    {
        //Check file exists before the method is called
        FileInfo fi = new FileInfo(filePath);

        bool exists = fi.Exists;
        if (!exists)
            return;

        string fileName = fi.Name;

        // Create the Outlook application by using inline initialization.
        Outlook.Application outlookApp = new Outlook.Application();

        //Create the new message by using the simplest approach.
        Outlook.MailItem msg = (Outlook.MailItem)outlookApp.CreateItem(
          Outlook.OlItemType.olMailItem);

        Outlook.Recipient outlookRecip = null;
        //Add a recipient.
        if (!string.IsNullOrEmpty(recipient))
        {
          outlookRecip = (Outlook.Recipient)msg.Recipients.Add(recipient);
          outlookRecip.Resolve();
        }

        //Set the basic properties.
        msg.Subject = subject;
        msg.Body = body;
        msg.BodyFormat = Microsoft.Office.Interop.Outlook.
             OlBodyFormat.olFormatPlain;

        //Add an attachment.
        long sizeKB = fi.Length / 1024;
        string sDisplayName = fileName + "(" + 
                     sizeKB.ToString() + " KB)";
        int position = (int)msg.Body.Length + 1;
        int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
        Outlook.Attachment attachment = msg.Attachments.Add(
          filePath, iAttachType, position, sDisplayName);

        //msg.Save();
        if (silently)
        {
            //Send the message.
            msg.Send();
        }
        else
        {
            msg.Display(true);  //modal
        }

        //Explicitly release objects.
        outlookRecip = null;
        attachment = null;
        msg = null;
        outlookApp = null;
    }

    // Simple error handler.
    catch (Exception e)
    {
        Console.WriteLine("{0} Exception caught: ", e);
    }
}
Following code uses the above method to email a file:
public void EmailFile(string recipient, string filePath)
{
    FileInfo fi = new FileInfo(filePath);
    bool exists = fi.Exists;
    if (!exists)
        return;

    string fileName = fi.Name;
    string subject = "Emailing: " + fileName;
    string body = "Your message is ready to be sent with the following "
           "file or link attachments:" + Environment.NewLine +
           Environment.NewLine +
           fileName + Environment.NewLine +
           Environment.NewLine +
           "Note: To protect against computer viruses, e-mail programs"
           " may prevent sending or receiving certain types of file "
           "attachments.  Check your e-mail security settings to determine"
           " how attachments are handled."; ;
    SendPlainFormatEmail(recipient, subject, body, filePath, false);
}

May 27, 2010

WPF MessageBox Dialog Examples

Copy and paste type samples
using System.Windows;
Suprise type dialog:
MessageBox.Show(this,
 "Specified root directory \'" + rootDir + "\'does not exist",
 "Find files",
 MessageBoxButton.OK,
 MessageBoxImage.Exclamation);
Question type dialog:
MessageBox.Show(this,
 "Are you sure you want to delete these files" + Environment.NewLine +
 fileListStr,
 "Delete selected files",
 MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) 

May 26, 2010

Beware of using anonymous delegates for event handlers

First found a description of this issue here
There is a problem unsubscribing to an event
Check out the following code:
EventHandler onXXX =
 delegate(object sender, XXXEventArgs e)
 {
  onXXXCallCount++;
  xxxs.Add(e.LastXXX);
 };
... 
m_YYY.OnXXX += onXXX;
...
// The anonymous event handler stays on the event handler until removed
// or the parent object is disposed of!
m_YYY.OnXXX -= onXXX;

May 20, 2010

Open Explorer At Some Directory in C#

Use the following code snippet:
// Open explorer in user temporary directory
OpenExplorerInDir(System.IO.Path.GetTempPath());
...
private void OpenExplorerInDir(string dir)
{
  string exe = "explorer.exe";

  //Driectory.Exists
  Process exeProcess = new Process();
  exeProcess.StartInfo.FileName = exe;
  exeProcess.StartInfo.Arguments = "/e,/root," + dir;
  exeProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
  exeProcess.Start();
}

C++ Pattern: Use pointer behind a reference

The advantage is in the header file the member variable is forward declared so the user of the class only needs the header file in their class source file (and not in their header) In header file declare the reference object:
...
namespace aaaa { namespace bbbb {
  class xxxx;
}}
...
  /// Reference member variable.
 aaaa::bbbb::xxxx& memberVar;
In source file assign reference using *new()
SomeClass::SomeClass(const SomeClass &time)
    // Here is the trick, new() and dereference (*) 
    // immediately into a reference object
  : memberVar(*new xxxx(time.memberVar)) {
}

SomeClass::~SomeClass() {
  delete &memberVar;
}

Null Pointers and Delete in C++

From here: Null Pointers and Delete C++ guarantees that delete operator checks its argument for null-ness. If the argument is 0, the delete expression has no effect. In other words, deleting a null pointer is a safe (yet useless) operation.
 
if (ptr == NULL) // useless, delete already checks for null value
{
  delete(ptr);
}
// but always set ptr = NULL after deleting it otherwise another 
// call to delete(ptr) will throw an exception
ptr = NULL; 

C++ Virtual Destructor

Look at this Why are destructors not virtual by default? Basic rule is if a class has at least one virtual function, it should have a virtual destructor
Example:
class Base 
{
...
  virtual ~Base();
...
};

class Derived : public Base 
{
 ...
  ~Derived();
};