C# Tips n Tricks: Coalesce

I’ve been using SQL for many years and find COALESCE to be extremely useful.  Recently I realized that if I could do the same functionality in C# it would be helpful, so I started to look.

For basic Coalesce functionality all you need to do is use the ?? operator.

string name = nameA ?? nameB ?? nameC ?? string.Empty;

For more advanced functionality I am planning to use the logic I found in the “Extending the C# Coalesce Operator” post on StackOverflow  to create an extension method that will allow the following code to work.

public class Bar
{
  public Bar Child { get; set; }
  public Foo Foo { get; set; }
}

Bar bar=new Bar { Child=new Bar { Foo=new Foo("value") } };

// prints "value":
Console.WriteLine(Coalesce.UntilNull(bar, b => b.Child, b => b.Foo, f => f.Value) ?? "null");

// prints "null":
Console.WriteLine(Coalesce.UntilNull(bar, b => b.Foo, f => f.Value) ?? "null");

C# Tips and Tricks: Checking for empty strings

When checking to see if a string is empty I got tired of checking for null and then seeing if it was empty now I only use the following method.

public string StandardMethodName(string inputString)
{
 if(string.IsNullOrEmpty(inputString))
 {
  inputString = "Default value";
 }

 return inputString;
}

C# Tips and Tricks: Setting default DateTime values

Here is the standard way that I set default values for a DateTime field. I like to set defaults for my DateTime fields whenever it makes sense. In this example I am setting the values so that it will return all the data for the last month, including the current day.

public bool StandardMethodName(DateTime? startDate, DateTime? endDate)
{
     startDate = startDate.GetValueOrDefault(DateTime.Today.AddMonths(-1));
     endDate = endDate.GetValueOrDefault(DateTime.Now);

     return ProcessInfo(startDate, endDate);
}

Filter DDL items using javascript and a Dictionary<string, string> object in the ViewBag

I had a need to modify the options on a DDL based on different selections the user had made on the page.  I did this at runtime by passing in a list of menu items in the ViewBag and using javascript to add and remove items based on the users selections.

Step 1: Create a ViewBag Dictionary <string, string> object that contains the full list of possible menu items.

ViewBag.MenuItems = new Dictionary<string, string> {
     {"option1", "Option One"},
     {"option2", "Option Two"}, 
     {"option3", "Option Three"}, 
     {"optionShowMe", "Option Show Only Me"}, 
};

Step 2: Create a javascript function that will insert an item into the DDL

function AddItem(Text,Value)
{
    // Create an Option object
    var opt = document.createElement("option");
    
    // Add an Option object to Drop Down/List Box
    document.getElementById("DropDownList").options.add(opt);

    // Assign text and value to Option object
    opt.text = Text;
    opt.value = Value;
}

Step 3: Create a method that will filter the options based on the users selection

function FilterDropDownListItems() {
    var array = @(Html.Raw(Json.Encode(ViewBag.MenuItems)));
    var userSelectedOption = $('#UserDDL').val();
    $("#DropDownList").empty();

    if (userSelectedOption === '140') {
        for (var val in array) {
            if(val === 'optionShowMe')
                AddRequestTypeItem(array[val], val);
        }
        $('#DropDownList').val('optionShowMe');
    } else {
        AddRequestTypeItem('Please Select', '');
        for (var val in array) {
            if(val != 'optionShowMe')
                AddRequestTypeItem(array[val], val);
        }
        $('#DropDownList').val('');
    }
}

Learning Dependency Injection

I recently accepted a new job, its one of those jobs where everything matches your skillset, technical interests, personal home/work balance requirements, and ethical requirements. I am super excited to be working here. While I have many of the skills required for the position they are doing some things I have never done before. One of them is that they use Dependency Injection (DI) with Unity and nHibernate. I have heard of them but never looked into them before. Here is the approach I took to learning this new skill set, I had 2-3 days to figure it out before the work would start rolling in.

Step 1: Talk to my co-worker who is the project guru
First I spoke to my coworker who gave me a general overview of the system and how things are laid out, setup, and interwoven. During the overview he mentioned that it would be good if I knew more about DI before getting to deep into the code.

Step 2: Google
My next stop was Google where I found the following blog posts and websites that had some information that helped. It wasn’t enough. Because I don’t understand the basics I was completely confused.
Dependency Injection and Inversion of Control with ASP.NET MVC
ASP.NET MVC 3 Service Location, Part 1: Introduction
MSDN: Appendix A – Dependency Injection with Unity
Microsoft patterns & practices: Unity
Microsoft patterns & practices: Inject Some Life into Your Applications—Getting to Know the Unity Application Block

Step3: StackOverflow
Next I went to StackOverflow to try again.  I started looking at the posts in the dependency-injection tag and found the following gems. 
Learning inversion of control through dependency injection in MVC3
Dependency Injection book recommendations
How to explain dependency injection to a 5 year old

Step 4: Resorted to a Technical Book
In a StackOverflow post I finally found a reference to the book “Dependency Injection .NET” by Mark Seeman. Luckily the publisher has the first chapter of the book available for free on their website. Things are finally beginning to make sense. 

Step5: Book – Dependency Injection .NET
I finally just broke down and purchased the book and started to read it.  Some of it makes perfect sense and some just makes my head hurt.  I am glad I got it and find it to be very useful.  I like that it has great examples and a section on patterns. 

Step 6: Talk to my co-worker who is the project guru
Now that I have read and understood enough of the book to get the basics I will be having my coworker go over the whole thing again, in more depth this time.  Hopefully I can hit the ground running.

Dynamically generate XML based on Class Properties

I recently came across a problem where I needed to dynamically generate data for a PDF file created using Adobe Livecycle Designer. Here are the main methods that I used to loop through the relevant classes and pull out the data for the file. I created a table in the DB containing a list of all the fields from the 3 main classes that need to be included in the XML data. This is done so that in the future we can add additional fields without needing to do a release to add them.

This method will return properly formed XML data that will then be attached to the PDF file. It generates the XML by looping through the PDF, Student, and Security object and retrieving the relevant data.

internal static string GetPDFDocXMLData(int pdfTemplateId, string studentId, SSO sso)
{
   var supportedFields = PDFDocData.GetListSupportedFields();
   using (var sdc = new StudentDataClient())
   using (var db = new DatabaseContainer())
   {
      var pdf = db.PDFForms.Single(f => f.Id == pdfTemplateId);
   
      FillSupportedFields("PDFTemplate", pdf, typeof(PDFForm), supportedFields);
      if (studentId != string.Empty)
      {
         var student = sdc.GetStudentInfo(Int32.Parse(studentId));
         FillSupportedFields("StudentInfo", student, typeof(StudentInfo), supportedFields);
      }
      FillSupportedFields("SSO", sso, typeof(SSO), supportedFields);
      return CreateXML(supportedFields);
   }
}

This method loops through all the properties in the indicated class object and loads any that match the list of valid supported fields. It adds the value of the field to the PDFDocData item.

private static void FillSupportedFields(string cName, object obj, IReflect type, IEnumerable<pdfdocdata> supportedFields)
{
   var props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);

   foreach (var item in supportedFields.Where(sf => sf.ClassName == cName))
   {
      foreach (var propInfo in props.Where(f => f.Name == item.FieldName).ToList())
      {
         item.Value = propInfo.GetValue(obj, null).ToString();
      }
   }
}

This method generates the properly formed XML string that will be used.

private static string CreateXML(IEnumerable<pdfdocdata> supportedFields)
{
   var doc = new XmlDocument();

   var dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
   doc.AppendChild(dec);

   var root = doc.CreateElement("form1");
   doc.AppendChild(root);

   foreach (var item in supportedFields)
   {
      var element = doc.CreateElement(item.ClassName + item.FieldName);
      element.InnerText = item.Value;
      root.AppendChild(element);
   }
   return doc.OuterXml;
}

This class looks at the DataBase and pulls the list of supported fields and populates a list containing all the information about the fields except for the value which is populated in the FillSupportedFields method.

public class PDFDocData
{
   public string ClassName { get; set; }
   public string FieldName { get; set; }
   public string Description { get; set; }
   public string Value { get; set; }
   public static List<pdfdocdata> GetListSupportedFields()
   {
      using (var db = new DatabaseContainer())
      {
         return db.PDFSupportedFields.Select(s => new PDFDocData()
                                             {
                                                ClassName = s.ClassName,
                                                FieldName = s.FieldName,
                                                Description = s.Description
                                             }).ToList();
      }
   }
}