January 28, 2015

Sending EMail Using SMTP in .NET

Here was the old way of sending email using an SMTP email service
using System.Web.Mail; // OLD WAY
...
private void SendEMail()
{
    Common.ResponseHelper rh = new Common.ResponseHelper();
    MailMessage email = new MailMessage();
    email.To = _TargetEMail;
    email.Cc = _CcTargetEMail;
    email.From = _txtFromEMail;
    email.Subject = "EMail Subject";
    email.Body = _txtComments;
    email.Priority = MailPriority.Normal;
    email.BodyFormat = MailFormat.Text; 
    SmtpMail.SmtpServer = "localhost";

    try
    {
        SmtpMail.Send(email);
        rh.WriteComment("Email has been sent successfully");
        Response.Redirect("emailsent.aspx"); // Redirect to an email sent web-page
    }
    catch (Exception ex)
    {
        rh.WriteComment("Send failure: " + ex.ToString());
    }
}
Had to convert this to using the new form
using System.Net.Mail;
...
private void TrySendEMail()
{
    Common.ResponseHelper rh = new Common.ResponseHelper();
    try
    {
        using (MailMessage email = new MailMessage())
        {               
            email.To.Add(_targetEMail);
            email.CC.Add(_ccTargetEMail);
            email.From = new MailAddress(_fromEMailAddress);

            email.Subject = "EMail Subject";
            email.Body = _txtComments;
            email.Priority = MailPriority.Normal;
            email.IsBodyHtml = false;

            using (SmtpClient smtp = new SmtpClient())
            {
                smtp.Host = "localhost";
                smtp.Port = 25;
                smtp.EnableSsl = false;
                NetworkCredential networkCred = new NetworkCredential(
                   _fromEMailAddress, UnmashPassword("oX9iioW7eTX5LS7T"));
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = networkCred;

                smtp.Send(email);
                rh.WriteComment("Email has been sent successfully");
                Response.Redirect("emailsent.aspx");
            }                
        }
    }
    catch (Exception exc)
    {
        rh.WriteComment("Send failure: " + exc.ToString());
    }
}
Had some problems sending email to my googlemail account:
  1. Had to ensure that the email sender address was one that existed
  2. Had to ensure that the "MailMessage.From" property matched the EMail address used for the "NetworkCredentials" constructor.
Without these changes Google rejected my emails (silently).

January 25, 2015

MS-Test Unit Test Template

Here is a template class for an MS-Test unit test class. Pay careful attention to the order of the various test method calls.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject
{
    [TestClass]
    public sealed class VSUnitTestTemplate
    {
        // Invoked after AssemblyInitialize
        public VSUnitTestTemplate()
        {

        }

        // Invoked before all tests in an assembly have run
        [AssemblyInitialize]
        public static void AssemblyInitialize(TestContext testContext)
        {
            
        }

        // Invoked after all tests in an assembly have run
        [AssemblyCleanup]
        public static void AssemblyCleanup()
        {

        }

        // Executed before running any tests (but after the constructor)
        [ClassInitialize()]
        public static void ClassInitialize(TestContext context) 
        {

        }

        // Executed after running all the class tests
        [ClassCleanup()]
        public static void ClassCleanup() 
        {

        }

        // Executed before each individual Test
        [TestInitialize]
        public void TestInitialize() 
        {

        }

        // Executed after each individual Test
        [TestCleanup]
        public void TestCleanup() 
        {

        }
   
        // A single test
        [TestMethod]
        public void MyUnitTest()
        {
            // Setup

            // Perform test steps

            // Verify the results
            
        }
    }
}
From what I have seen in various blogs (see here and MS-Test versus NUnit here) most people recommend sticking to NUnit or some other open-source framework. The reasons are that MS-Test has:
  • Dependence on a test Metadata file.
  • A framework that in itself is quite slow.
  • A dependence on Visual Studio being installed for continous integration testing whereas something like NUnit only needs the NUnit assemblies installed.

January 21, 2015

ASP.NET Web API

According to http://rest.elkstein.org/ : REST stands for Representational State Transfer. (It is sometimes spelled "ReST".) It relies on a stateless, client-server, cacheable communications protocol -- and in virtually all cases, the HTTP protocol is used. REST is an architecture style for designing networked applications.

ASP.NET Web API is a framework for building HTTP based services and is ideal for creating RESTful services over HTTP. The best place to start looking for information/tutorials etc. is http://www.asp.net/web-api

Here is how the operations map to HTTP methods:
Operation HTTP Method Relative URI
Get all members GET /api/members
Create a new member POST /api/members
Get member GET /api/members/{username}
Update member PUT /api/members/{username}
Delete member DELETE /api/members/{username}
In general terms then, one could say that the mapping between REST and CRUD is (loosely)
HTTP POST maps to Create
HTTP GET maps to Read
HTTP PUT maps to Update
HTTP DELETE maps to Delete

MVVM/MVC/MVP Explained

There is a nice explanation here

The represent several ways to manage and coordinate the GUI but the important thing is that the model is always segregated from the GUI. Usually the model is described as some database classes but the Model can contain threads and timers and event publishers so this overly simplistic view does not do it any justice. I prefer to view the model as an API on the business logic. A good way to create a model is using test classes from a test framework (such as NUnit or MS-Test). Using a GUI framework is a dangerous approach because it encourages the use of GUI objects within the model, even a simple message dialog within some model code can throw a spanner in the works so to speak.

The View represents the UI components such as CSS, jQuery, html, WinForms, WPF, Silverlight, XAML

January 13, 2015

Reactive Extensions

Here is a good introduction to the main interfaces: http://introtorx.com/Content/v1.0.10621.0/02_KeyTypes.html
IObserver<T> - Reader/Consumer/Observer
IObservable<T> - Writer/Publisher/Observable sequence. [I find this interface name confusing.]
ISubject<in TSource, out TResult> - Represents an object that is both an observable sequence as well as an observer. Used in (non-reactive) samples but not in real situations.
In comparison to IEnumerable<T> where items are pulled out, in an IObservable<T> items are pushed in
A simple sample: Consider an image processing system in a factory that scans parts for results. The outcome of the scan could be one of three states
public enum ImageProcessingSystemResult
{
    Failed, // failed image processing check
    Passed, // succeeded  image processing check
    Indeterminate
}
Here is the publisher of the image processing system results:
// Publishes a sequence of ImageProcessingSystemResult to the observer
public class ImageProcessingSystemPublisher : IObservable<ImageProcessingSystemResult>
{
    public IDisposable Subscribe(IObserver<ImageProcessingSystemResult> observer)
    {
        // These results in this case are just published one after another
        observer.OnNext(ImageProcessingSystemResult.Passed); 
        observer.OnNext(ImageProcessingSystemResult.Passed);
        observer.OnNext(ImageProcessingSystemResult.Failed);
        observer.OnNext(ImageProcessingSystemResult.Passed);
        observer.OnCompleted();
        return Disposable.Empty;
    }
}
Here is a generic results observer:
// Reads/Observes a sequence of T and decides what to do with it
// Basically, what you want to do when you receive some data
public class MyObserver<T> : IObserver<T>
{
    public void OnNext(T value)
    {
        string output = value != null ? value.ToString() : "null";
        Console.WriteLine("Received value: {0}", output);
    }
    public void OnError(Exception error)
    {
        Console.WriteLine("Sequence faulted with exception: {0}", error.ToString());
    }
    public void OnCompleted()
    {
        Console.WriteLine("Sequence terminated");
    }
}
Here is how it all goes together:
public void UnreactiveSimpleTest()
{
    var imageProcessingSystemPublisher = new ImageProcessingSystemPublisher();
    var observer = new MyObserver<ImageProcessingSystemResult>();
    // Here is how the observer subscribes to the publisher
    using (imageProcessingSystemPublisher.Subscribe(observer))
    { }
}
Here is the output:
Received value: Passed
Received value: Passed
Received value: Failed
Received value: Passed
Sequence terminated

Press any key to continue ...

Hot and Cold Observables (i.e. publishers)


Cold - Sequences that start producing notifications on request (when subscribed to), and each subscriber gets a copy of the same notification stream from the beginning.
Hot - Sequences that are active and produce notifications regardless of subscriptions (just like c# events).

A 'Cold' Observable can be converted to a 'Hot' Observable by using the Publish() extension method. With a hot Observable it is necessary to use "Connect()" to connect to the published sequence. This returns an IDisposable which must be disposed of when the Observable sequence is finished with.

January 7, 2015

Reading Xml Using XDocument

The ideas behind this blog are revealed here
Wanted to read some objects in using XDocument.

Found that the best was to use the explicit cast operators exposed by XDocument. These can be used to protect against attributes and elements that are missing

Also found that the XDocument.Parse() method was an excellent way to use raw XML strings to test the parsing
Consider this class:
internal class Base 
{
 public int Id { get; set; }
 public string Name { get; set; }
 public string Faction { get; set; }
}
Here is some small test XML to parse:
string rawTestXml = @"
<Bases>
  <Base ID=""1""><NAME>Freeport 2</NAME><FACTION>Zoners</FACTION></Base>
  <Base ><NAME>Pacifica</NAME></Base>
</Bases>";
Here is a method to test parsing this XML:
public void TestXDocumentParseUnprotected()
{
    FreelancerData freelancerData = new FreelancerData();

    var xmlDoc = XDocument.Parse(rawTestXml);
    var basesTableRaw = new Dictionary<int, Base>();

    foreach (var bas in xmlDoc.Descendants("Base"))
    {
        var b = new Base()
        {
            Id = Convert.ToInt32(bas.Attribute("ID").Value),
            Name = bas.Element("NAME").Value,
            Faction = bas.Element("FACTION").Value,
        };

        basesTableRaw.Add(b.Id, b);
    }

    Debug.Assert(basesTableRaw.Count == 2);

}
This will throw an exception when parsing the second "Base" element in the Xml string, as this second object is missing an "ID" attribute a NullReferenceException will be thrown by the line to extract it. If the XML data can be guaranteed then this is not a problem. A more robust way to read in the XML is to use the XElement/Xattribute explicit conversion operators:
public void TestXDocumentParseProtected()
{
  var xmlDoc = XDocument.Parse(rawTestXml);
  var basesTableRaw = new Dictionary<int, Base>();

  foreach (var bas in xmlDoc.Descendants("Base"))
  {
    var b = new Base()
    {
      Id = (int?)bas.Attribute("ID") ?? 0,  // 0 when the attribute "ID" is not present
      Name = (string)bas.Element("NAME") ?? "",  // "" when the element "NAME" is not present
      Faction = (string)bas.Element("FACTION"), // null when the element "FACTION" is not present
    };

    basesTableRaw.Add(b.Id, b);
  }

  Debug.Assert(basesTableRaw.Count == 2);
}
However this is allowing malformed objects to be allowed as input. The developer must detect these and decide what to do with them.

Note that the XDocument.Load() method can be used to load a document from a local file system file or from a Url. So this method
public void LoadBases(string rootPath)
{
  string xmlFileName = "Bases.xml";
  string basesPath = Path.Combine(rootPath, xmlFileName);
  var xmlDoc = XDocument.Load(basesPath);
  
  ...
}
can work with a local file:
LoadBases(@"X:\Backup\Documents\flasp\");
or a url:
LoadBases(@"http://www.somewebserver.com/flasp/");