The meaning of reflection is to provide information on an assembly, type, a method, a constructor or an interface implemented. Every time you run the .NET Reflector, or simply use the dot syntax to explore the members of a class by Intellisense, you use reflection.
Reflection is particularly useful when you have no compile time knowledge of a given type (let’s say for example when you want to create an extendable application). To implement and load a snap-in, you’d create a method which checks for an assembly (the snap-in itself). You’d mark the classes with attributes, or even better, implement a predefined interface (which this time will really act as a contract). What you’d do is the following:
- Create a Class Library (e.g.: Commons.dll), and define your interface there.
- Create your main application, and set a reference on the Commons.dll
- Create a method which checks for the implemented contract interface in a given assembly (or in a group of assemblies, for example in the \\AppPath\SnapIns directory.
- Create some snap-ins, set a reference on the Commons.dll, and create classes which implements it.
- Run your application.
The .NET Framework provides functions for the sake of compatibility with unmanaged (COM or C) codes. In this section, I’ll introduce the technique of Platform Invoke (PInvoke).
Platform Invoke is the process of calling unmanaged functions which lives in DLLs from managed code. You need to take four steps:
- Identify functions in DLLs.
- Create a class to hold DLL functions.
- Create prototypes in managed code.
- Call the DLL functions.
To identify functions in DLLs, you should know at least the name of the DLL and of the function. Without it, you are doomed, there won’t be any platform invoke.
I think you can handle the brutal work of creating a class for holding the DLL functions, let’s concentrate on those prototypes. To create those prototypes, you’ll need to define a static extern method, and mark it with the DllImportAttribute. A quick example:
As no doubt you’ll love it, .NET comes with the support of sending e-mail messages by SMTP. Unfortunately, it can’t act as a mail receiver, but we should overcome the pain and examine how to send emails with it.
The key namespace is System.Net.Mail, and there are two important classes: MailMessage, which represents an e-mail message, and SmtpClient, which provides methods to send it.
First let’s build our message by using the MailMessage class!
MailMessage represents an email message eager to be sent. It has the following constructors:
- MailAddress from, MailAddress to
- String from, String to
- String from, String to, String subject, String body
Don’t worry about MailAddress, it just takes a string and verifies that it is a valid e-mail address. It also defines some useful properties such as DisplayName or User. Use it instead of just passing a string.