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");

ReportViewer: Alternating color on rows

According to MSDN you do the following:

Creating a Green-Bar Report To apply a green-bar effect (alternating colors every other row) to a table in a report, use the following expression in the BackgroundColor property of each text box in the detail row:

=iif(RowNumber(Nothing) Mod 2, "PaleGreen", "White")

To alternate colors by row groupings:

=iif(RunningValue({Expression Being Grouped On}, CountDistinct, nothing) Mod 2, "WhiteSmoke", "White")

JavaScript Tips n Tricks: javascript:void(0)

Two options

<a href="#" onclick="myJsFunc(); return false;">Run JavaScript Code</a>

or

<a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>

Both options do almost the same thing.  By using the second one you will not need to remember to use the “return false;” that is in the first one.  When writing large amounts of complex code using this pattern saves on bugs and time.  One issue with it is accessibility, I will need to do more research on this when the time comes.

StackOverflow question : Href attribute for JavaScript links: “#” or “javascript:void(0)”?

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);
}

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();
      }
   }
}