Archive for category How To

Tribal Knowledge: Linq Entities To Do Your Bidding via the Partial Keyword in C#

TribalKnowledge2Having premade entities created during the Linq process in .Net really comes in handy. But did you know that one can extend those entities further outside of of the generated dbml file? By using the concept introduced in C# 2.0 of a partial class, where one can have business logic methods and other properties which are not generated but are none the less relevant in an Object Oriented fashion it can be achieved.

As mentioned the entities are generated and nothing is worse than having the generator throw away user code placed in the generated file after a regeneration. To allow for generated and user code to coexist hand in hand was accomplished by partial classes. That is where the partial keyword is appended to a class which allows for the class to have a subset of functionality in a different code file. The generated code file resides in one file and the user code lives elsewhere in a different file allowing them co-exist.

I have used this process to put validation logic on an entity. That logic was used to verify that the differing properties which the user had entered values against matched business rules. Those rules could not be entirely expressed in a database schema. It was very Handy!

Example

A user posted a question on the MSDN Forums as to how one could achieve indexing into a Linq generated class entity where each property represented a numerated indexed field. The below code shows the use of a partial class in a separate file which the user could  have an index-able entity.

public partial class Request
{
    public int this[int index]
    {
        get
        {
            int retValue;

            switch ( index )
            {
                case 0: retValue = Val1; break;
                case 1: retValue = Val2; break;
                case 2: retValue = Val3; break;
            }

            return retValue;
        }
        set
        {
            switch (index)
            {
                case 0: Val1 = value; break;
                case 1: Val2 = value; break;
                case 2: Val3 = value; break;
            }
        }
    }
}
Share

Tags: , , ,

C# 101: Extension Method Creation For Variables and Enums

Class101 With the advent of C# 3.0 in .Net 3.5 one can create extension methods for common tasks for any existing types and enums which one finds in their code. This is a quick how-to article which provides those two examples using an integer and a user defined enum.

Basic Extension Example

Sometimes one needs to know when an integer value is negative. Here is an extension method to do that and its usage example.

public static class MyExtensions
{
    public static bool IsNegative( this int value )
    {
        return (value < 0) ? true : false;
    }
}
  1. Step one create a static class.
  2. Create a static method return type can vary to suit the target operations needs.
  3. Use the this keyword in the input parameters of the type which the extension will be used by.

In the above case we want integers to report if they are negative or not. Here is the usage:

int value = 1;

Console.WriteLine( value + " is " + value.IsNegative() );
value = --value;

Console.WriteLine( value + " is " + value.IsNegative() );

value = --value;
Console.WriteLine( value + " is " + value.IsNegative() );

/* Output
1 is False
0 is False
-1 is True
*/

Enum Example

Enums can have extensions in C# as well and are very functional.

This example is similar to the previous but we will deal with software development states. The first two states are test related and we will create an extension to determine if the state is in test or not.

public enum States { Test, UserAcceptance, Development, Production, Maintainence };

public static class MyExtensions
{
    public static bool IsInTest( this States state )
    {
        return state < States.LastTestState;
    }

}

So every state before Development is considered a “Testing” state. Here is its usage:

States current = States.Test;
Console.WriteLine("State: " + current + " is " + current.IsInTest());

current = States.Development;
Console.WriteLine( "State: " + current + " is " + current.IsInTest() );

/* Output:
State: Test is True
State: Development is False
*/

HTH

HTH

Share

Tags: , , ,

Linq vs. DataReader; Visual Examples Showing That Linq Does it in Fewer Lines of Code

Bridges I recently replied to a post in the MSDN C# General forum (one of the best places to get help if you have C# question) where the user was getting data from a DataReader and needed help with null values being returned. What I ended up discovering was differences from old way of getting data from a database in .Net and the new way. Such as the highways above both go to the same location and essentially do the same thing, but the contrast is so much different. Same holds true for .Net Linq and the DataReader.

In the post I recommend the use of the null-coalescing operator to handle the null returned from the database. Erroneously I forgot that the DataReader returns a DBNull which cannot be handled by the null-coalescing operator. GRRR

My mistake was based in the fact that I have become used to the Linq Data Context returning a INullable<T> when dealing with null fields in a database. The the null-coalescing operator can handle that to a tee.

I created my test code and realized that it demonstrated the following

  1. Linq does so much for the developer that what previously took around six plus lines of code boils down to roughly three. It manages so much in the background for the user that it allows for quicker coding to get at data.
  2. The design of Linq handles Nulls differently, or at lease presents them to the end user from the old way processing. Using the null-coalescing operator as shown is a great help.

Here is the example code, first up is Linq and the target operation is to display values from a nullable field in the database called Description. When enumerating over the data rows, if that field happens to be null it reports it or shows the actual data. Next up is the older way of doing it and notice how the user has to handle reader. Note one could check for DBNull in that situation, so the example may not be what you are looking to do in a real system.

GTCDataContext gtc = new GTCDataContext();

var items = gtc.Location_US;

foreach ( var it in items )
   Console.WriteLine( it.Description ?? "not Defined" );

string queryString = "SELECT Description FROM dbo.Location_US;";

using ( SqlConnection connection = new SqlConnection( gtc.Connection.ConnectionString  ))
{
   SqlCommand command = new SqlCommand( queryString, connection );    connection.Open();

   SqlDataReader reader = command.ExecuteReader();

   // Call Read before accessing data.
   while ( reader.Read() )
   {
      Console.WriteLine( (string.IsNullOrEmpty(reader[0].ToString()) == false) ?  reader[0] : "not defined again" );
   }

    // Call Close when done reading.
    reader.Close();
}

Here is the result of the run:

Florida

not Defined

Colorado

California

not Defined

not Defined

not Defined

not Defined

—————————————–

Florida

not defined again

Colorado

California

not defined again

not defined again

not defined again

not defined again

Share

Tags: , , , , ,

C#: Splitting Data From a String and Extracting out Decimals and Integers into Separate Lists Using Extension Methods

Sometimes you have the need to extract text out of a string, once extracted you need to get the right data into lists. Say one list of integers and one list of decimals. Using the extension methods now found in .Net one can easily do those operations.

Example

Here is the data in a string, “12 34 56.1 18 19.25 41”. We want the integers separated out from the decimals into their own lists respectively as their native values (int/decimal) and not strings. Using Where, Select and a couple of Lambdas we can get to the intended  result.

string data =@"12 34 56.1 18 19.25 41";

string[] dataAsStrings = data.Split( ' ' );

List<decimal> decs = ( dataAsStrings.Where( itm => itm.Contains( '.' ) ) )
                  .Select( itm => Decimal.Parse( itm ) )
                  .ToList();

List<int> ints = ( dataAsStrings.Where( itm => itm.Contains( '.' ) == false ) ).Select( itm => int.Parse( itm ) ).ToList();

foreach ( decimal dc in decs )
    Console.WriteLine( dc );
/* Outputs 56.1 19.25 (on seperate lines)*/

foreach ( int it in ints)
    Console.WriteLine( it );
/* Outputs 12 34 18 41 (on seperate lines)*/
  • Step one is top split the string using string.Split.
  • Step 2 is take that split data and enumerate over it using the Where method.
  • Within the Where we use a lambda which basically says for each item in the list, if it contains a period select it and return it. Note the result of most Extension methods is deemed a projection which is really a list of the values. Where, Select and ToList all return projections.
  • Once the Where is done we call/chain the Select Extension. The select is saying take the projection from the Where and on each item parse out the value and return it in its native, non string format.
  • Using the ToList on the projection created by the Select we take the items and specify it to be in a List<> format.

We didn’t have to do the ToList and could have said something like this:

var decs = ( dataAsStrings.Where( itm => itm.Contains( '.' ) ) )
        .Select( itm => Decimal.Parse( itm ) );
foreach ( decimal dc in decs )
    Console.WriteLine( dc );
/* Outputs 56.1 19.25 (on seperate lines)*/

Which would have been just as vaild. At runtime the var would have been internally known as IEnumerable<decimal> under the covers and as you can see that is just a different type of list and works just the same.

Share

Tags: , , , , , ,

C# WMI Get Process Start Location

This question was asked in the forums, the user had two different autocads running. Each ran from a different location and the user needed to programmatically know where it was running from. The following code snippet provides that information to the user on all processes.

// Add System.Management reference to the project
using System.Management;
using System.Management.Instrumentation;

ManagementClass mc = new ManagementClass( "Win32_Process" );

ManagementObjectCollection mcol = mc.GetInstances();

foreach ( ManagementObject strt in mcol )
{
   Console.WriteLine( string.Format("\t-{0}-", strt["Name"]));
   Console.WriteLine( "Path:\t" + strt["ExecutablePath"] );
   Console.WriteLine( Environment.NewLine );
}

Here is an example output on my box while running Windows Live Writer:

        -WindowsLiveWriter.exe-

Path:   C:\Program Files\Windows Live\Writer\WindowsLiveWriter.exe

Share

Tags: , ,

Asp.Net DropDownList bound with Linq Data Example

I recently answered a post where the user was using ASP .Net 3.5 but not binding data to a DropDownList but instead using hard coded data to load the drop down in the HTML. So I created this quick example to show Linq-To-Xml (Linq) loading of an Asp.Net DropDownList and handling the automatic postback selection changes.

As mentioned example shows how to bind data to a dropdown list using Linq, specifically Linq-To-Xml, but you could use any other of the Linq methodologies because we are using the anonymous types to work with the needs of the DropDownList.

First we will place the Asp.Net DropDownListon our page along with a label which will used to show state changes.

<asp:DropDownList ID="ddlMain"
      runat="server"
      AutoPostBack="true"
      OnSelectedIndexChanged="SelectionMade" />

<asp:Label ID="lblWhat" runat="server"/>

Nothing earth shattering here, we have AutoPostBack because we want the control to tell our code behind on the server when a selection has been made. Following that we have the method which will be called for that event of SelectionMade.

The next thing is to load the DropDownList with values to choose from. We will use an XElement loaded dynamically to show how to do do this in Linq. The other thing of note is that we only want load this once, so we check the postback status. If its a postback, we do not reload.

protected void Page_Load( object sender, EventArgs e )
{

if ( Page.IsPostBack == false ) // Only do this once
{
   // Simulate an Linq-To-SQL call with an Linq-To-SQL
   // So anyone can use this demo.
   XElement dataForList
       = new XElement(
           "DropDownData",
             new XElement( "Node",
                 new XElement( "Text", "Selection 1"  ),
                 new XElement( "Data", "1Selection" ) ),
             new XElement( "Node",
                 new XElement( "Text", "Selection 2" ),
                 new XElement( "Data", "2Selection"  ) ));


   var toTheScreen = from x in dataForList.Descendants( "Node" )
                 select new
                 {
                     Text = x.Descendants( "Text" ).First().Value,
                     Value = x.Descendants( "Data" ).First().Value
                 };

    ddlMain.DataTextField = "Text";
    ddlMain.DataValueField = "Value";
    ddlMain.DataSource = toTheScreen;
    ddlMain.DataBind();
}

}

As shown above we work through all the elements named Node. For each of those nodes we will create a new entity with two properties Text and Value. Text will be shown to the user and value is what is associated with the selection. In the binding operations we specify the Text and Value field for the DropDownList to use and simply bind it to our anonymous projection.

Now all we have to do is handle the selection change event

protected void SelectionMade( object sender, EventArgs e )
{
    DropDownList target = sender as DropDownList;

    if ( target != null )
        lblWhat.Text =
            string.Format(
                "Item {0} selected with Value of {1}",
                target.SelectedItem.Text,
                target.SelectedValue );
}

Nothing magical here, we get the DropDownList from the sender argument, divine the selection and update the label. Here is what it should look like after a change:

ddl

Share

Tags: , , ,

C# XML Parsing Extracting Values and using XML to Linq with XDocument

On my blog the most accessed articles are the basic ones on XML which has suprised me. So In this article I will focus on the new kid on the block the Linq derived XDocument. In the following example I will load the Xml then enumerate over the child nodes, to extract specific values and then display them.

I am loading the xml directly, but you can load it from other locations using the Load option of XDocument.

string xml = @"<?xml version='1.0' encoding='UTF-8'?>
<widgets>
    <widget>
        <url>~/Portal/Widgets/ServicesList.ascx</url>
        <castAs>ServicesWidget</castAs>
        <urlType>ascx</urlType>
        <parameters>
            <PortalCategoryId>3</PortalCategoryId>
        </parameters>
    </widget>
    <widget>
        <url>www.omegacoder.com</url>
        <castAs>ServicesWidget</castAs>
        <urlType>htm</urlType>
        <parameters>
            <PortalCategoryId>41</PortalCategoryId>
        </parameters>
    </widget>
</widgets>";

XDocument loaded = XDocument.Parse( xml );

var widgets = from x in loaded.Descendants( "widget" )
              select new
              {
                  URL = x.Descendants( "url" ).First().Value,
                  Category = x.Descendants( "PortalCategoryId" ).First().Value
              };

foreach ( var wd in widgets )
    Console.WriteLine( "Widget at ({0}) has a category of {1}", wd.URL, wd.Category );

/* Outputs:

Widget at (~/Portal/Widgets/ServicesList.ascx) has a category of 3
Widget at (www.omegacoder.com) has a category of 41

*/
Share

Tags: , ,

C# Dictionary<T> Tricks

>(Post Updated 4/2/2011 : Added extra example)

This article demonstrates the Tribal Knowledge of using a Dictionary to do the things that the Swiss Army Knife Hashtable used to do.

For .Net 3 through .Net 4.

I love the generic Dictionary collection so much, I think that Microsoft might charge me usage on it. Here I present some of the things that I have learned which I call the tribal knowledge of the class.

The first use of the Dictionary was found in .Net 1 HashTable class. That class is a dictionary for storing lists with keys and has the ubiquitously Key Value Pair. With .Net 2 the generic class Dictionary was used, less upfront functionality, but same concepts; data in key value pairs.

While the old hash table could be sorted the dictionary cannot. So how does one sort? The Dictionary is just two lists under the covers. One is for keys and one is for values. Operations don’t go to the hash table but to the lists. Once you remember that and understand it, the obtuseness of the Dictionary goes away…

Sorting

Ok, so we can sort…but one complaint or question found in the MSDN forums that I have run into is that, the Hashtable could be sorted because it exposed IComparer and its cousin the Dictionary does not! How does one get around that?

As mentioned one must think of what a dictionary really is…just two lists. There are two properties exposed on the Dictionary and those are the Keys and Values. Those are shown to the world as ValueCollection and that my friends is the entry pass into the club. One of the interfaces that is exposed is the ValueCollection and it adheres to the ICollection. Bingo! With that we can do sorting! Here is the code snippet:

Dictionary<int, string> myDict = new Dictionary<int, string>()
            {
                { 2, "This" },
                { 1, "is" },
                { 5, "radio" },
                { 12, "clash" },
            };

List<string> song = new List<string>( myDict.Values );

song.Sort();

// This writes out: "clash is radio This"
Console.WriteLine( string.Join( " ", song.ToArray() ) );

We simply use the sorting which is found on the List<T>.

Enumerating over a Dictionary

Sometimes the need is there to run through a dictionary and show the keys and values. When enumerating over a Dictionary it returns a Key Value Pair object. That object holds the key and the value.

Dictionary<string, string> ColumnValuesHash = new Dictionary<string, string>()
// ... load with values...
foreach (KeyValuePair entry in ColumnValuesHash)
    Console.WriteLine("{0}: {1}", entry.Key, entry.Value);

Dictionary of Dictionaries

I have used this gem many times. Create a top level dictionary that will hold other dictionaries…its not as bad as it sounds.

Dictionary<int, string> myStringHash = new Dictionary<int, string>();

myStringHash.Add(41,      "Jabberwocky");
myStringHash.Add(8675309, "Jenny");

Dictionary< string, Dictionary<int, string>> myDicts = new Dictionary<string, Dictionary<int, string>>();

myDicts.Add("Test", myStringHash);

Console.WriteLine( myDicts["Test"][8675309] ); // Prints Jenny

Notice how easy it is to drill down via indexes off of each dictionary.

Dictionary Meets Linq and Gets Sorted

Here is how you can access the dictionary, sort it and enumerate it all in Linq. We will take our above example and do it

Dictionary<int, string> myDict = new Dictionary<int, string>()
                     {
                         { 2, "This" },
                         { 1, "is" },
                         { 5, "radio" },
                         { 12, "clash" },
                     };

var sorted = from item in myDict
             orderby item.Value ascending
             select item.Value;

// This writes out: "clash is radio This"
Console.WriteLine( string.Join( " ", sorted.ToArray() ) );

Extra Example (Loading on the fly and Linq extension Select Many)

Dictionary<string, Dictionary<int, string>> TopLevel = new Dictionary<string, Dictionary<int, string>>()
{
    {
        "Dictionary 1",
        new Dictionary<int, string>()
                                    { // Sub "dictionary 1" contains two objects
                                        {41, "The Meaning of Life" },
                                        {90125, "Owner of a Lonely Heart"}
                                    }
    },

    {

        "Dictionary 2",
        new Dictionary<int, string>()
                                    { // Sub "Dictionary 2" contains one object
                                        {8675309, "Jenny!" }
                                    }

    }

};

Console.WriteLine(TopLevel["Dictionary 1"][41]);      // Prints out "The Meaning of Life!"

//     Console.WriteLine(TopLevel["Dictionary 1"][8675309]); // Fails and would throw an exception! That is in Dictionary 2!

// Use selectmany to grab all sub objects
// (which are a Key value pair of KVP<string, Dictionary<int, string>)
// and return the value (the sub dictionaries) and combine
// all the those dictionaries from both sub dictionary into one IEnumerable KVP.
TopLevel.SelectMany( dict => dict.Value ) // Gets all the DIctionary<int, string> pairs between both dictionaries
        .ToList() // Convert from IEnumerable to list so we can do the for each below
        .ForEach( kvp => Console.WriteLine( "{0} is {1}", kvp.Key, kvp.Value ) ); // Outputs the lowest dictionaries.

/* above outputs
41 is The Meaning of Life
90125 is Owner of a Lonely Heart
8675309 is Jenny!
*/

Hope this helps!

Share

Tags: , ,