Pages

Monday, May 25, 2009

Sending emails in .Net using C# and SMTP

Recently I bumped into forum thread that asked how to send emails in .Net using C#, so I decided to take a look of that.
I will demonstrate how to send email by using SMTP and Google's GMail account.

First we need to have a few prerequisites fulfilled.
  1. The SMTP host server that you use to send e-mail. We'll use GMail, and its host address is "smtp.gmail.com", and port 587.
  2. Do we need to enable SSL? In this case, yes we are required to use SSL, because GMail uses it.
  3. Credentials for authentication, if required by the SMTP server. GMail needs to have those, so we need to pass our username and password.
  4. The e-mail address of the sender. This is what goes to From-field.
  5. The e-mail address or addresses of the recipients. This is what goes to To-field.
  6. The message content, whatever you want to send.
Below is a working, simple code example of how to send email using C# and SMTP.
Basically the flow of code goes like this:
  • First, we create a simple email message using System.Net.Mail.MailMessage.
  • You can set messge type to HTML if you want, in this sample it is commented out.
  • Also you can add attachments, there's a commented line in the code that does it.
  • Then we initialize SMTP-client using GMail SMTP address and port 587.
  • GMail uses SSL, so we need to enable it. Also we need to authenticate to our account, and we need to set NetworkCredentials for that.
  • Then we just send message and that's it (hopefully) :)
  • Possible exceptions are caught and we can use that information to take a look what went wrong.
That's it!

If you want further reading, check out MSDN's SmtpClient Class


    1 using System;
    2 using System.Net.Mail;
    3 using System.Net;
    4 
    5 namespace SmtpTest
    6 {
    7   class Program
    8   {
    9     static void Main(string[] args)
   10     {
   11       Console.WriteLine("Sending test message...");
   12       CreateTestMessage("smtp.gmail.com", 587);
   13       Console.WriteLine("OK");
   14       Console.ReadLine();
   15     }
   16 
   17     public static void CreateTestMessage(string server, int port)
   18     {
   19       // message info
   20       string to = "*****.*****@gmail.com"; // put recipient
   21       string from = "*****.*****@gmail.com"; // put sender email here
   22       string subject = "SMTP client using GMail."; // message subject
   23       string body = "This is our test message, w00t!"; // message body
   24 
   25       MailMessage message = new MailMessage(from, to, subject, body);
   26 
   27       // Uncomment rows below if you want to send attachment 
   28       //message.Attachments.Add(
   29       //  new Attachment(@"C:\AttachmentFolder\AttachmentFile.txt"));
   30 
   31       // Uncomment row below if you want to send HTML-message
   32       //message.IsBodyHtml = true;
   33 
   34       // Initialize SMTP client
   35       SmtpClient client = new SmtpClient(server, port);
   36 
   37       // enable SSL
   38       client.EnableSsl = true;
   39 
   40       // Credentials are necessary if the server requires the client 
   41       // to authenticate before it will send e-mail on the client's behalf.
   42       //client.Credentials = CredentialCache.DefaultNetworkCredentials;
   43       // Here we define our network credetials (username and password)
   44       NetworkCredential SmtpUserInfo = 
   45         new NetworkCredential("your.username@gmail.com", "password");
   46 
   47       // Set the credentials
   48       client.Credentials = SmtpUserInfo;
   49 
   50       try
   51       {
   52         // send message
   53         client.Send(message);
   54       }
   55       // catch possible exceptions
   56       catch (SmtpException se)
   57       {
   58         Console.WriteLine(
   59           "SmtpException caught in CreateTestMessage(): {0}", se.ToString());
   60       }
   61       catch (Exception e)
   62       {
   63         Console.WriteLine(
   64           "Exception caught in CreateTestMessage(): {0}", e.ToString());
   65       }
   66     }
   67 
   68   }
   69 }

Sunday, April 26, 2009

Nullable types in C#

Nullable types in C# can represent all the values of an underlying type, and an additional null value. For example, nullable integer can have values like 10, 333, and null.

Nullable types have also a ?? -operator, that defines a default value that is returned when a nullable type is assigned to a non-nullable type. For example, you can use it to form a following operation: "a = b, unless b is null, in which case a=c". Or you can think it to be similar to SQL's NVL()-function.

Below is a code sample how to use nullable types and ??-operator.


    1 using System;
    2 
    3 namespace NullableTest
    4 {
    5   class Tester
    6   {
    7     static void Main(string[] args)
    8     {
    9       int? i = null;
   10       int? k = 5;
   11 
   12       // d = c, unless c is null, in which case d = -1.
   13       int a = i ?? -1;
   14 
   15       Console.WriteLine("Value of a is {0}", a);      
   16 
   17       // check if i has value
   18       if(i.HasValue)
   19         Console.WriteLine("Value of i is {0}", i.Value);
   20       else
   21         Console.WriteLine("i is null");
   22 
   23       // check if k has value
   24       if (k.HasValue)
   25         Console.WriteLine("Value of k is {0}", k.Value);
   26       else
   27         Console.WriteLine("k is null");
   28 
   29       Console.ReadLine();
   30     }
   31   }
   32 }

Further reading at MSDN:

Using Nullable Types (C# Programming Guide)

Nullable Types (C# Programming Guide)

Friday, April 24, 2009

Enum in C#

MSDN says:
An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable.

You create a bit flags enum by applying the System.FlagsAttribute attribute and defining the values appropriately. That way you can use the bitwise operations like AND, OR and NOT on them.

In the following code example I've shown how to get Enum names and values, and how to use bitwise operations with enums.



    1 using System;
    2 
    3 namespace EnumTest
    4 {
    5   class Program
    6   {
    7     enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
    8 
    9     [Flags] // Enables bitwise operations
   10     public enum WaffleOptions
   11     {
   12       Cherries = 0x01,
   13       IceCream = 0x02,
   14       MapleSyrup = 0x04,
   15       WhippedCream = 0x08,
   16       Strawberries = 0x16
   17     }
   18 
   19 
   20     static void Main(string[] args)
   21     {
   22       int x = (int)Days.Monday;
   23       int y = (int)Days.Friday;
   24       Console.WriteLine("Monday = {0}", x);
   25       Console.WriteLine("Friday = {0}", y);
   26 
   27       // Output:
   28       // Monday = 0
   29       // Friday = 4
   30 
   31       WaffleOptions waffleFillings = WaffleOptions.Cherries | WaffleOptions.WhippedCream;
   32 
   33       Console.WriteLine("Waffle options are {0}", waffleFillings);
   34 
   35       // Output:
   36       // Waffle options are Cherries, WhippedCream
   37 
   38       // gets the string value of Days-enum at index 4, 
   39       // which is Friday (Monday=0, .. Sunday=6)
   40       string s = Enum.GetName(typeof(Days), 4);
   41       Console.WriteLine(s);
   42 
   43       // Output:
   44       // Friday
   45 
   46       // gets all the values of Days enum
   47       Console.WriteLine("The values of the Days Enum are: ");
   48       foreach (int i in Enum.GetValues(typeof(Days)))
   49         Console.Write("{0} ", i);
   50 
   51       // Output:
   52       // 0 1 2 3 4 5 6 7
   53 
   54       // gets all the names of Days enum
   55       Console.WriteLine("\nThe names of the Days Enum are:");
   56       foreach (string str in Enum.GetNames(typeof(Days)))
   57         Console.Write("{0} ", str);
   58 
   59       Console.ReadLine();
   60 
   61     }
   62   }
   63 }

When you have for example a string value that you want to parse or check if it is an enum, you need to use Parse method. Parse method convert strings to their corresponding enumeration values. However, that's not enough. If your value is for example 1234, Parse-method thinks it is a valid enum value, because it's an integer value. You need to check if that integer value is represented in the enum list, by using IsDefined method. Following example describes how to use those.

    1 using System;
    2 
    3 namespace EnumParseTest
    4 {
    5   class Tester
    6   {
    7     
    8     // here's some enums. As you can see, we don't have to assign integer value to enum (Yellow)
    9     enum Colors { Red = 1, Green = 2, Yellow };
   10 
   11     static void Main(string[] args)
   12     {
   13       Console.WriteLine();
   14 
   15       // here's string values that are later parsed & checked if they are in Colors-enum
   16       string[] colorStrings = { "Red", "Yellow", "Gray", "2", "12345"};
   17 
   18       foreach (string colorString in colorStrings)
   19       {
   20         try
   21         {
   22           Colors colorValue = (Colors)Enum.Parse(typeof(Colors), colorString);
   23           // We need to check if parsed value is a member of Colors enum
   24           // If we just parse the value, then value '12345' is assumed enum value.
   25           if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
   26             Console.WriteLine("Converted string '{0}' to Enum value {1}.", colorString, colorValue.ToString());
   27           else
   28             Console.WriteLine("{0} is not a value of the Colors enumeration.", colorString);
   29         }
   30         catch (ArgumentException)
   31         {
   32           Console.WriteLine("'{0}' is not a member of the Colors enumeration.", colorString);
   33         }
   34       }
   35 
   36       /*
   37           Output:
   38           Converted string 'Red' to Enum value Red.
   39           Converted string 'Yellow' to Enum value Yellow.
   40           'Gray' is not a member of the Colors enumeration.
   41           Converted string '2' to Enum value Green.
   42           12345 is not a value of the Colors enumeration.              
   43        */
   44 
   45       Console.ReadLine();
   46     }
   47   }
   48 }

Enums in MSDN:

enum (C# Reference)

Enumeration Types (C# Programming Guide)

Thursday, April 23, 2009

Disposing objects in C#

Have you ever been confused of object disposing, when object is garbage collected and what does the Using-block do? Below is a code sample that shows what happends to an object when it loses its references and is garbage collected, and what happends to object after using-block.

Basically, when you use the using block, when the code is done the object's Dispose-method gets called. And you need to implement the IDisposable interface for that. When you're not using the using-block and object gets garbage collected, object's destructor/finalizer gets called.


    1 using System;
    2 
    3 namespace DisposeTest
    4 {
    5   class Tester
    6   {
    7     static void Main(string[] args)
    8     {      
    9       // Note: we create objects in separate method, because if we 
   10       // create instances and call GC in same method, objects would 
   11       // technically still be associated with running code and would 
   12       // therefore not be eligible for garbage collection
   13       InitializeObjects();
   14 
   15       // suggest GC that now would be a lovely time to pick up the trash
   16       GC.Collect();
   17 
   18       Console.ReadLine();
   19     }
   20 
   21     private static void InitializeObjects()
   22     {
   23       // Create an object, and then set its value to null.
   24       // object's Dispose()-method is not called
   25       DisposableObject object1 = new DisposableObject { ObjectID = 1 };
   26       object1 = null;
   27 
   28       // Object's Dispose()-method is called right after we exit the using block
   29       using (DisposableObject object2 = new DisposableObject { ObjectID = 2 })
   30       {
   31 
   32       }      
   33     }
   34   }
   35 }

Here's the class that implements the IDisposable interface, and shows the use of Dispose()-method and destructor.

    1 using System;
    2 
    3 namespace DisposeTest
    4 {
    5   public class DisposableObject : IDisposable
    6   {
    7     public int ObjectID { get; set; }
    8 
    9 
   10     // this method is called when object is disposed, 
   11     // like after using-block
   12     public void Dispose()
   13     {
   14       Console.WriteLine(
   15         "Object {0} says: I've been disposed!", ObjectID);
   16     }
   17 
   18     // this method gets called when object is garbage collected
   19     ~DisposableObject()
   20     {
   21       Console.WriteLine(
   22         "Object {0} says: Argh, garbage collector got me!", ObjectID);
   23     }
   24   }
   25 }


Further reading in MSDN: IDisposable.Dispose Method

Delegates in C#

A delegate in C# is like a function pointer in C/C++, except in C# they are type-safe.
Delegate is a type that wraps a method call. Delegate instance can be passed between methods like a type and it can be invoked like a method.

There's a three way how to create and use a delegate.
  1. Create an instance of a delegate by explicitly initializing it with a method that is defined somewhere in the code. This way is used in .Net Framework version 1.0.
  2. Create an anonymous method for initializing delegate. This way is used in .Net Framework version 2.0.
  3. Use lambda expressions. This way is used in .Net Framework version 3.0 (and above).

Below is a source code you can use to see how to use delegates.

    1 using System;
    2 
    3 namespace DelegateTest
    4 {
    5   class Tester
    6   {
    7     // Create a delegate instance. This one takes one parameter, which is a string type
    8     delegate void TestDelegate(string s);
    9 
   10     // The method associated with the named delegate
   11     // (same signature as delegate has)
   12     static void DelegateMethod(string s)
   13     {
   14       Console.WriteLine(s);
   15     }
   16 
   17     static void Main(string[] args)
   18     {
   19       // 'Original way' of using delegates 
   20       TestDelegate firstTest = new TestDelegate(DelegateMethod);
   21 
   22       // Using .Net 2.0 anonymous method for initializing delegate
   23       TestDelegate secondTest = delegate(string s) { Console.WriteLine(s); };
   24 
   25       // .Net 3.0 gives us lambda expressions
   26       // The type of s is inferred by the compiler
   27       TestDelegate thirdTest = (s) => { Console.WriteLine(s); };
   28 
   29       // Invoke delegates
   30       firstTest("Hello, I'm the first delegate");
   31       secondTest("And I'm second delegate, .Net 2.0 style");
   32       secondTest("Greetings from delegate number three, with some lambda expression goodness");
   33 
   34       Console.WriteLine();
   35 
   36       Console.ReadLine();
   37     }
   38   }
   39 }

For more information, check link below:
The Evolution of Delegates in C# in MSDN

Wednesday, April 22, 2009

Using Reflection in C#

One neat purpose for reflection is to see what assemblies the application loads, and also see
information of them. It can be useful for debugging and error reporting purposes.

Below is an example how to use it:

    1 using System;
    2 using System.Reflection;
    3 
    4 namespace ReflectionTest
    5 {
    6   class ReflectionTester
    7   {
    8     static void Main(string[] args)
    9     {
   10       GetAssemblies();
   11       Console.ReadLine();
   12     }
   13 
   14     public static void GetAssemblies()
   15     {
   16       Assembly[] appAssemblies =
   17         System.AppDomain.CurrentDomain.GetAssemblies();
   18 
   19       foreach (Assembly assembly in appAssemblies)
   20       {
   21         Console.WriteLine(assembly.FullName);
   22       }
   23     }
   24   }
   25 }

Code outputs used assemblies and various information about them, like:

mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Microsoft.VisualStudio.HostingProcess.Utilities, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a


Further reading:
MSDN Reflection (C# Programming Guide)

Tuesday, April 21, 2009

C# and Yield operation

Are you confused how to use Yield in C#? MSDN says: "Yield is used in an iterator
block to provide a value to the enumerator object or to signal the end of iteration."
However, I found the concept of yield quite confusing, so I decided to make a code
sample how yield is used, so you can see how it operates and how it may benefit you.


    1 using System;
    2 using System.Collections;
    3 using System.Collections.Generic;
    4 
    5 namespace YieldTest
    6 {
    7   public class Tester
    8   {
    9     public static IEnumerable Power(int number, int exponent)
   10     {
   11       int counter = 0;
   12       int result = 1;
   13       while (counter++ <> 
   14       {
   15         result = result * number;
   16         yield return result;
   17       }
   18     }
   19 
   20     public static IEnumerable<string> GetEnumerator()
   21     {
   22       yield return "one";
   23       yield return "two";
   24       yield return "three";
   25     }
   26 
   27 
   28     static void Main(string[] args)
   29     {
   30       // Display powers of 2 up to the exponent 8:
   31       // 2 4 8 16 32 64 128 256
   32       foreach (int i in Power(2, 8))
   33       {
   34         Console.Write("{0} ", i);
   35       }
   36       Console.Write("\n");
   37 
   38       // Displays following:
   39       // one two three
   40       foreach(string s in GetEnumerator())
   41         Console.Write("{0} ", s);
   42 
   43       Console.ReadLine();
   44     }
   45   }
   46 }

Further reading in MSDN: yield (C# Reference)