September 4, 2015

Using Newtonsoft (Open Source) JSON Serializer

Here is how to serialize and deserialize a JSON object to and from a string
string json = JsonConvert.SerializeObject(target, Formatting.Indented); // Serialize to a string
var reconstituted = JsonConvert.DeserializeObject<ClassOfTarget>(json); // Deserialize from a string
Documentation is here: http://www.newtonsoft.com/json/help/html/Introduction.htm

Can use with attributes:
[DataContract] // ONLY 'marked' properties are serialized in this case
public class ClassOfTarget
{
...
[DataMember] // Use this attribute to 'mark' a property
public Dictionary<string, string> Mappings { get; set; }
...
}
Newtonsoft JSON serializer will recognise these Microsoft attributes and they also have a few of their own they will recognise as well.

Serializing/Deserializing to a file using some extension methods
using Newtonsoft.Json;

public static class JsonExtensions
{

  public static void WriteToJsonFile<T>(
    this T objectToWrite, 
    string filePath
    // This next parameter is optional but ensures that 
    // when you have types mixed with their derived types
    // they can be serialized as well
    bool derivedTypesPresent = false) 
      where T : new()
  {
    FileInfo file = new FileInfo(filePath);
    Debug.Assert(!file.Exists);
    try
    {
      // Serialize JSON directly to a file
      using (StreamWriter sw = new StreamWriter(file.FullName))
      {
        using (JsonWriter writer = new JsonTextWriter(sw))
        {
          JsonSerializer serializer = new JsonSerializer();
          serializer.Formatting = Formatting.Indented;
          if (derivedTypesPresent) // Store type info in JSON
            serializer.TypeNameHandling = TypeNameHandling.All; 

          // target is the object you want serialized
          serializer.Serialize(writer, objectToWrite); 
        }
      }
    }
    catch (JsonSerializationException ex)
    {
        Trace.WriteLine($"Json Serialization Exception occurred: {ex}");
    }
  }

  public static T ReadFromJsonFile<T>(
    this string filePath
    // This next parameter is optional but ensures that 
    // when you have types mixed with their derived types
    // they can be serialized as well
    bool derivedTypesPresent = false)
      where T : class, new()
  {
    FileInfo file = new FileInfo(filePath);
    Debug.Assert(file.Exists);
    T reconstituted = null;

    try
    {
      // deserialize JSON directly from a file
      using (var reader = file.OpenText())
      {
        var serializer = new JsonSerializer();
        if (derivedTypesPresent) // Store type info in JSON
          serializer.TypeNameHandling = TypeNameHandling.All; 
        reconstituted = (T)serializer.Deserialize(reader, typeof(T));
      }
    }
    catch (JsonSerializationException ex)
    {
        Trace.WriteLine($"Json Serialization Exception occurred: {ex}");
    }
    return reconstituted;
  }
  
  public static string WriteToJsonString<T>(
    this T objectToWrite,
    //This parameter is optional but ensures that 
    //when you have types mixed with their derived types
    // they can be serialized as well
    bool derivedTypesPresent = false)
    where T : new()
  {
    string json = "";
    Debug.Assert(objectToWrite != null);
    try
    {
        var serializerSettings = new JsonSerializerSettings();
        serializerSettings.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
        if (derivedTypesPresent) // Then store type info in JSON as well
            serializerSettings.TypeNameHandling = TypeNameHandling.All;

        // Serialize to a string  
        json = JsonConvert.SerializeObject(objectToWrite, Formatting.None); 
    }
    catch (JsonSerializationException ex)
    {
        Trace.WriteLine($"Json Serialization Exception occurred: {ex}");
    }
    return json.ToString();
  }

  public static T ReadFromJsonString<T>(
    this string json,
    bool derivedTypesPresent = false)
    where T : class, new()
  {
    Debug.Assert(!string.IsNullOrWhiteSpace(json));
    T reconstituted = null;

    try
    {
        var serializerSettings = new JsonSerializerSettings();
        serializerSettings.DefaultValueHandling = DefaultValueHandling.
            IgnoreAndPopulate;
        if (derivedTypesPresent) // Then store type info in JSON as well
            serializerSettings.TypeNameHandling = TypeNameHandling.All;

        reconstituted = JsonConvert.DeserializeObject<T>(json, 
            serializerSettings);
    }
    catch (JsonSerializationException ex)
    {
        Trace.WriteLine($"Json Serialization Exception occurred: {ex}");
    }
    return reconstituted;
  }

}
And to serialise and deserialise to and from a file:
StarSystem myObject = new StarSystem(...);
// To write an object to a json file
myObject.WriteToJsonFile<StarSystem>(filePath);
// To read an object from a jsonfile
myObject = filePath.ReadFromJsonFile<StarSystem>(); 
And to serialise and deserialise to and from a string:
StarSystem myObject = new StarSystem(...);
// To write an object to a json string
string json = myObject.WriteToJsonString<StarSystem>();
// To read an object from a json string
myObject = json.ReadFromJsonString<StarSystem>(); 
To convert the JSON to XML, use the JSON string like so
// To convert the JSON to XML
string json = ....
XNode node = JsonConvert.DeserializeXNode(json, "Title");
string xml = node.ToString();

Loading application settings from a custom configuration file

Here is a unit test to show how to load configuration data from a custom configuration file (useful in unit tests)
private string configContents =
 @"<?xml version='1.0' encoding='utf-8'?>" +
 @"<configuration>" +
 @"  <startup>" +
 @"    <supportedRuntime version='v4.0' sku='.NETFramework,Version=v4.5.2'/>" +
 @"  </startup>" +
 @"  <appSettings>" +
 @"" +
 @"    <add key='intValue' value='42' />" +
 @"    <add key='stringValue' value='blah, blah, blah' />" +
 @"" +
 @"  </appSettings>" +
 @"</configuration>";

[Test]
public void RawCustomConfigTest()
{
 // Write out the test config file
 string exeDir = System.IO.Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).LocalPath);
 string configPath = Path.Combine(exeDir, "Test.config");
 File.WriteAllText(configPath, configContents, Encoding.UTF8);

 // Read it in
 SysConfig.ExeConfigurationFileMap map = new SysConfig.ExeConfigurationFileMap { ExeConfigFilename = configPath };
 SysConfig.Configuration config = SysConfig.ConfigurationManager.OpenMappedExeConfiguration(map, SysConfig.ConfigurationUserLevel.None);
 var appSettings = config.AppSettings.Settings;

 // Read in the test entries
 string intValue = TryGetValue(appSettings, "intValue", "-1");
 string stringValue = TryGetValue(appSettings, "stringValue", "");
 string otherValue = TryGetValue(appSettings, "DoesNotExistInConfig", "not present"); // does not exist in the config file

 // Show that it worked
 Assert.That(intValue == "42");
 Assert.That(stringValue == "blah, blah, blah");
 Assert.That(otherValue == "not present");
}

private static string TryGetValue(SysConfig.KeyValueConfigurationCollection appSettings, string name, string defaultValue)
{
 try
 {
  return appSettings[name].Value;
 }
 catch (NullReferenceException)
 {
  return defaultValue;
 }
}

MemoryCache Extension

The MemoryCache class does not have a "Clear()" method.
Here is  an extension that does the job
// Extend MemoryCache functionality
public static class MemoryCacheExtensions
{
 // Clear the cache
 public static void Clear(this MemoryCache cache)
 {
  List<string> cacheKeys = cache.Select(kvp => kvp.Key).ToList();
  foreach (string cacheKey in cacheKeys)
  {
   cache.Remove(cacheKey);
  }
 }
}


February 12, 2015

Unity

Here are some helpful links: Here are some examples using the following simple classes:
interface ITextService
{
    string Text { get; set; }
}

internal class TextService : ITextService
{
    public string Text { get; set; }
}
With the simplest form of Unity registration, invoking 'Resolve' creates a new instance of the service each time
public void RegisterServiceNewInstanceEachTimeTest()
{
    IUnityContainer myContainer = new UnityContainer();

    myContainer.RegisterType<ITextService, TextService>();
    // Create a TestService instance
    ITextService svc1 = myContainer.Resolve<ITextService>();

    svc1.Text = "Doombar";
    // Creates a new TestService instance
    ITextService svc2 = myContainer.Resolve<ITextService>();
    Assert.AreNotEqual(svc1.Text, svc2.Text, false);
}
Resolve creates a new instance of the service each time however this time the service is registered against a string name or label that can be used to identify and retrieve it
public void RegisterNamedServiceNewInstanceEachTimeTest()
{
    IUnityContainer myContainer = new UnityContainer();

    myContainer.RegisterType<ITextService, TextService>("MyTextService");
    ITextService svc1 = myContainer.Resolve<ITextService>("MyTextService");
    svc1.Text = "Doombar";

    ITextService svc2 = myContainer.Resolve<ITextService>("MyTextService");
    Assert.AreNotEqual(svc1.Text, svc2.Text, false);
    Assert.IsFalse(ReferenceEquals(svc1, svc2));
}
A particular instance of a service object can be registered against the 'ITextService' type, this gives a way of registering singleton objects.
public void RegisterSpecificInstanceForServivceTest()
{
    IUnityContainer myContainer = new UnityContainer();
    TextService svc1 = new TextService();
    svc1.Text = "Doombar";

    myContainer.RegisterInstance<ITextService>(svc1);
    ITextService svc2 = myContainer.Resolve<ITextService>();

    Assert.AreEqual(svc1.Text, svc2.Text, false);
    Assert.IsTrue(ReferenceEquals(svc1, svc2));
}
Injection of service via a constructor First, define a demo class:
internal class ConstructorInjectedClass
{
    ITextService testSvc = null;

    public ConstructorInjectedClass(ITextService mysvc)
    {
        testSvc = mysvc;
        // work with the dependent instance
        testSvc.Text = "Yeehah!";
    }


    public ITextService TestService
    {
        get { return testSvc; }
    }
}
Now use Unity to perform the dependency injection:
public void ConstructorInjectionTest()
{
    IUnityContainer uContainer = new UnityContainer();
    uContainer.RegisterType<ITextService, TextService>();
    // Unity will look at all the objects required to construct the 'ConstructorInjectedClass'
    // object and automatically resolve them
    ConstructorInjectedClass myInstance = uContainer.Resolve<ConstructorInjectedClass>();
    Assert.IsNotNull(myInstance.TestService);
}
Multiple services can also be defined against a single type and retrieved:
public void ResolveAllTest()
{
    IUnityContainer uContainer = new UnityContainer();
    uContainer.RegisterType<ITextService, TextService>("textService1");
    uContainer.RegisterType<ITextService, DifferentTextService>("textService2");
    // Now there are 2 services registered as an ITextService
    // Use 'ResolveAll' to get all the services implementing the named type
    var textServices = uContainer.ResolveAll<ITextService>();
    int ix = 0;
    foreach (var ts in textServices)
    {
        ++ix;
        ts.Text = ix.ToString();
    }
    Assert.AreEqual(2, textServices.Count());
}
Perfect for the case when multiple logger services are used for logging, a debug output logger, a rolling file logger, and so on.

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 Class 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.
[TestClass]
public sealed class VSUnitTestTemplate
{
    // Invoked after AssemblyInitialize
    public VSUnitTestTemplate()
    {
    }

#region Setup/TearDown 
    // 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() 
    {

    }
#endregion Setup/TearDown        

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

        // act: Perform test steps

        // assert: Verify the results
        
    }
    
    // You can add test parameters to a test and use it to test multiple cases 
   [TestMethod]
   [DataRow(5.0d, 0.0d, 3)]
   [DataRow(5.0d, 1.0d, 3)]
   [DataRow(5.0d, 0.0d, 5)]
   public void SomeTest(
     double fullLengthSecs, double startTimeSecs, int expectedValue)
   {
   }
}
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