A personal repository of technical notes. - CSC

Excel Alternating Rows Conditional Formatting Example

Problem
Need to format groups of matching rows with alternating colors.

Solution
Use a formula with conditional formatting.

1) Decide which column will be the "key column".
2) Sort sheet by key column.
3) Define a new Conditional Formatting column
  • Put "1" in column header row
  • Put formula in second row. Example: "=IF(A2=A1,D1,D1*-1)" where "A" is key column and "D" is Conditional Formatting column.
  • Copy formula into each row of column.

4) Define Conditional Formatting for alternating rows
  • Select all active cells in sheet
  • Click Conditional Formatting/New Rule...
  • Select Rule Type "Use a formula to determine which cells to format".
  • In "Format values where this formula is true:", define the Conditional Formatting column where = 1: Example: "=$D1=1" where "D" is Conditional Formatting column.



  • Click Format...
  • Select Fill tab, pick color, click OK, click OK.


Array Sort C# Example

Example: How to sort an array of DirectoryInfo objects by Delegate and by Lambda Expression


// Get array of directories
DirectoryInfo tempTopDirectory = new DirectoryInfo("C:\\Temp1");
DirectoryInfo[] tempSubdirectories = tempTopDirectory.GetDirectories();

// Sort directories array by Name using delegate
Array.Sort(tempSubdirectories, delegate(DirectoryInfo x, DirectoryInfo y) { return x.Name.CompareTo(y.Name); });

// Sort directories array by Name using lambda expression
Array.Sort(tempSubdirectories, (x, y) => x.Name.CompareTo(y.Name));

How to sort directories in descending order


// Sort descending by comparing "y" to "x" instead of "x" to "y".
Array.Sort(tempSubdirectories, (x, y) => y.Name.CompareTo(x.Name));

How to sort directories by creation date


// Sort by creation date time
Array.Sort(tempSubdirectories, (x, y) => x.CreationTime.CompareTo(y.CreationTime));

References

Array.Sort(T) Method (T[], Comparison(T)) (System)
http://msdn.microsoft.com/en-us/library/cxt053xf(v=vs.110).aspx

Lambda Expressions (C# Programming Guide)
http://msdn.microsoft.com/en-us/library/bb397687.aspx

.NET Framework Cryptography Notes

.NET Framework Cryptography Model

http://msdn.microsoft.com/en-us/library/0ss79b2x(v=vs.110).aspx

Quotes from web page:

Choosing an Algorithm

You can select an algorithm for different reasons: for example, for data integrity, for data privacy, or to generate a key. Symmetric and hash algorithms are intended for protecting data for either integrity reasons (protect from change) or privacy reasons (protect from viewing). Hash algorithms are used primarily for data integrity.

Here is a list of recommended algorithms by application:

AesCryptoServiceProvider vs AesManaged

Aes is inherited by two classes: AesCryptoServiceProvider and AesManaged. The AesCryptoServiceProvider class is a wrapper around the Windows Cryptography API (CAPI) implementation of Aes, whereas the AesManaged class is written entirely in managed code. There is also a third type of implementation, Cryptography Next Generation (CNG), in addition to the managed and CAPI implementations. An example of a CNG algorithm is ECDiffieHellmanCng. CNG algorithms are available on Windows Vista and later.

You can choose which implementation is best for you. The managed implementations are available on all platforms that support the .NET Framework. The CAPI implementations are available on older operating systems, and are no longer being developed. CNG is the very latest implementation where new development will take place. However, the managed implementations are not certified by the Federal Information Processing Standards (FIPS), and may be slower than the wrapper classes.

Cryptographic Services

http://msdn.microsoft.com/en-us/library/92f9ye3s(v=vs.110).aspx

Transfer DataTable with HTTP Response

Problem
Need a simple way to transfer data with an HTTP web request/response.

Solution
Convert a DataTable to XML, transfer with HTTP, convert XML back to DataTable.

Note: This was tested with .NET 4

SimpleDataTableExport.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SimpleDataTableExport.aspx.cs" Inherits="SimpleDataTableExport" %>

SimpleDataTableExport.aspx.cs
using System;
using System.Data;
using System.Xml;

/// <summary>
/// Simple web page to export a DataTable through an HTTP response.
/// </summary>
public partial class SimpleDataTableExport : System.Web.UI.Page
{
       protected void Page_Load(object sender, EventArgs e)
       {
              // Start response
              Response.ClearHeaders();
              Response.ClearContent();

              DataTable dataTable = null;
              try
              {
                     dataTable = GetDataTable();
              }
              catch (Exception ex)
              {
                     dataTable = null;
                     Response.StatusCode = 500;
                     Response.StatusDescription = ex.Message;
                     Response.Write(String.Format("Error message: {0}", ex.Message));
              }
              finally
              {
                     if (dataTable != null)
                     {
                           // DataTable is converted to XML and sent to the output stream.
                           XmlWriter xmlWriter = XmlWriter.Create(Response.OutputStream);
                           dataTable.WriteXml(xmlWriter, XmlWriteMode.WriteSchema);
                     }
              }

              // Complete response
              Response.Flush();
              ApplicationInstance.CompleteRequest();
       }

       private DataTable GetDataTable()
       {
              // Validate input parameters passed in query string.
              if (String.IsNullOrEmpty(Request.QueryString["parm01"]))
              {
                     throw new ApplicationException("Required parameter 'parm01' is missing.");
              }

              // Generate DataTable
              DataTable table = new DataTable("MyDataTable");
              table.Columns.Add("Column01");
              table.Columns.Add("Column02");
              DataRow row = table.NewRow();
              row["Column01"] = String.Format("'parm01' is {0}", Request.QueryString["parm01"]);
              row["Column02"] = "Value for Column02";
              table.Rows.Add(row);

              return table;
       }
}

Console application to import DataTable

using System;
using System.Data;
using System.Net;
using System.Xml;

namespace SimpleDataTableImport
{
       /// <summary>
       /// Simple Console Application to import a DataTable through an HTTP request.
       /// </summary>
       class Program
       {
              static void Main(string[] args)
              {

                     DataTable dataTable = new DataTable();
                     string errorMessage = null;

                     HttpWebRequest httpWebRequest;
                     HttpWebResponse httpWebResponse = null;
                     try
                     {
                           httpWebRequest = WebRequest.Create("http://localhost/SimpleDataTableExport.aspx?parm01=helloworld") as HttpWebRequest;
                           httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
                           XmlReader xmlReader = XmlReader.Create(httpWebResponse.GetResponseStream());
                           dataTable.ReadXml(xmlReader);
                     }
                     catch (WebException webEx)
                     {
                           httpWebResponse = webEx.Response as HttpWebResponse;
                           errorMessage = String.Format("{0} - {1}", Convert.ToInt32(httpWebResponse.StatusCode).ToString(), httpWebResponse.StatusDescription);
                     }
                     catch (Exception ex)
                     {
                           errorMessage = ex.Message;
                     }
                     if (httpWebResponse != null)
                     {
                           httpWebResponse.Close();
                     }
                     if (errorMessage != null)
                     {
                           Console.WriteLine(errorMessage);
                     }

                     // Display DataTable
                     foreach (DataColumn column in dataTable.Columns)
                     {
                           Console.WriteLine(column.ColumnName);
                     }
                     foreach (DataRow row in dataTable.Rows)
                     {
                           Console.WriteLine(String.Format("{0},{1}", row["Column01"], row["Column02"]));
                     }

                     Console.ReadLine();
              }
       }
}

Results