A personal repository of technical notes. - CSC

Showing posts with label Code Sample. Show all posts
Showing posts with label Code Sample. Show all posts

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

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

HashSet to Comma Delimited String

HashSet Coding Example: A HashSet is a collection that contains no duplicate elements.

Note: Tested in .NET 4.0.

       HashSet<string> myHashSet = new HashSet<string>();
       myHashSet.Add("A");
       myHashSet.Add("B");
       myHashSet.Add("B");
       myHashSet.Add("B");
       myHashSet.Add("B");
       myHashSet.Add("X");
       myHashSet.Add("Z");
       myHashSet.Add("B");
       myHashSet.Add("A");
       string commaDelimitedString = String.Join<string>(",", myHashSet);
       // commaDelimitedString is equal to "A,B,X,Z"

References
"HashSet(T) Class (System.Collections.Generic)." MSDN – the Microsoft Developer Network. N.p., n.d. Web. 16 Oct. 2013. <http://msdn.microsoft.com/en-us/library/bb359438(v=vs.100).aspx>.

FULL OUTER JOIN Not Working

Problem

FULL OUTER JOIN not returning all records from right table when left table has a Search Condition in the WHERE clause.

-- Full outer join with where clause at bottom
-- Returns all records from MyTable1 where Category is 23.
-- Does not return all records from MyTable2. Only matches with MyTable1.
SELECT t1.[Code],t2.[Code]
FROM [MyTable1] t1
FULL OUTER JOIN [MyTable2] t2
      ON t2.[Code] = t1.[Code]
WHERE t1.[Category] = 23

Solution

Use a Derived Table for the left table. The Search Condition is moved from the WHERE clause to the Derived Table query.

-- Full outer join with derived table, no where clause at bottom
-- Returns all records from MyTable1 where Category is 23.
-- Returns all records from MyTable2.
SELECT t1.[Code],t2.[Code]
FROM ( SELECT * FROM [MyTable1] WHERE [Category] = 23 ) t1
FULL OUTER JOIN [MyTable2] t2
      ON t2.[Code] = t1.[Code]

References

See also SQL Join Types

Windows Event Viewer Filter XML

Windows 7 XML Sample

<QueryList>
       <Query Id="0" Path="Security">
              <Select Path="Security">
                     *[System[(
                           EventID=4624
                           or EventID=4625
                           or EventID=4634
                     )]]
                     and
                     *[EventData[(
                           (
                                  Data[@Name='TargetDomainName'] = 'Abcd'
                                  or Data[@Name='AccountDomain'] = 'XYZ'
                           )
                           and
                           (
                                  Data[@Name='TargetUserName'] != 'U123'
                           )
                     )]]
              </Select>
       </Query>
</QueryList>

References

"Event Viewer - Wikipedia, the free encyclopedia." Wikipedia, the free encyclopedia. N.p., n.d. Web. 19 Oct. 2011.
<http://en.wikipedia.org/wiki/Event_Viewer#Filtering_using_XPath_1.0>.

"Windows Event Viewer CUSTOM XML FILTER | Jamin Quimby Installation & Development Notes." Jamin Quimby .com | Jamin Quimby Installation & Development Notes. N.p., n.d. Web. 19 Oct. 2011.
<http://jaminquimby.com/index.php/microsoft-windows-2008/129-windows-event-viewer-custom-xml-filter>.

"Event Log Hell (finding user logon & logoff) - Ars Technica OpenForum." Ars Technica. N.p., n.d. Web. 19 Oct. 2011.
<http://arstechnica.com/civis/viewtopic.php?f=17&t=1139356>.

SQL Concatenate Row Data into Variable

Problem

Need to generate a comma-delimited string list from data contained in rows of table

Solution

DECLARE @commaDelimitedList varchar(8000)
SET @commaDelimitedList = '' -- Must set to empty value

SELECT @commaDelimitedList = @commaDelimitedList + [MyColumn] + ','
FROM [MyTable]

-- Remove trailing comma from list
IF (@commaDelimitedList <> '')
BEGIN
      SET @commaDelimitedList = LEFT(@commaDelimitedList, LEN(@commaDelimitedList) - 1)
END

-- Return record set
SELECT @commaDelimitedList AS 'CommaDelimitedList'

Change GridView SortDirection Default

Problem
Need to change the default SortDirection in a GridView for certain columns from ascending to descending.

Solution
Note: This was tested and implemented in ASP.NET 2.0.
  

<asp:GridView DataSourceID="MySqlDataSource" AllowSorting="true" AutoGenerateColumns="false"

ID="MainGridView" runat="server" OnSorting="MainGridView_Sorting">

<Columns>

<asp:BoundField DataField="MyDataField01" SortExpression="MyDataField01" />

<asp:BoundField DataField="MyDataField02" SortExpression="MyDataField02" />

<asp:BoundField DataField="MyDataField03" SortExpression="MyDataField03" />

<asp:BoundField DataField="MyDataField04" SortExpression="MyDataField04" />

<asp:BoundField DataField="MyDataField05" SortExpression="MyDataField05" />

<asp:BoundField DataField="MyDataField06" SortExpression="MyDataField06" />

</Columns>

</asp:GridView>

protected void MainGridView_Sorting(object sender, GridViewSortEventArgs e)

{

// Change default sort order to Descending for certain columns.

switch (e.SortExpression)

{

case "MyDataField01":

case "MyDataField03":

case "MyDataField06":

// Current sort column is different than previous sort column

if (e.SortExpression != MainGridView.SortExpression)

{

e.SortDirection = SortDirection.Descending;

}

break;

default:

break;

}

}

How to Create .NET Object From String

Problem
Need to generate an instance of a class dynamically from a string value.

Solution
Use Assembly.CreateInstance Method to create an instance of a type name.
  

Assembly currentAssembly = Assembly.GetExecutingAssembly();

MyClass myClassObjectFromString = null;

try

{

myClassObjectFromString = currentAssembly.CreateInstance("MyNamespace.MyClass") as MyClass;

}

catch

{

}

if (myClassObjectFromString != null)

{

//

}

References
"Assembly.GetExecutingAssembly Method (System.Reflection)." MSDN: Microsoft Development, MSDN Subscriptions, Resources, and More. 23 June 2009 http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getexecutingassembly(VS.80).aspx.

"Assembly.CreateInstance Method (String) (System.Reflection)." MSDN: Microsoft Development, MSDN Subscriptions, Resources, and More. 23 June 2009 http://msdn.microsoft.com/en-us/library/dex1ss7c(VS.80).aspx.

See Also
"How to Convert an ASP.NET Control to String |." CSC - Technical Notes. 23 June 2009 http://csc-technicalnotes.blogspot.com/2009/03/how-to-convert-control-to-html-string.html.