enums with real world names

March 4, 2010 18:54 by bryan

Enums are a wonderful addition to .Net, but won't it be nice to have a real world description that you can display to the user interface? Well you can, and here is how define an attribute (or use existing DisplayNameAttribute) and annotate your enum with names as additional meta-data:

public enum Unit
{
    [DisplayName("Hz")] Hertz,
    [DisplayName("%V")] Volt
}


How do you retrieving the XmlEnumAttribute values for an Enum

January 8, 2010 06:27 by bryan

When you are playing with Web Services you quite often find information held in an Attribute, but how do you get it out?

e.g.

public enum Classification {

        [System.Xml.Serialization.XmlEnumAttribute("Test drive demonstrator")]
        Testdrivedemonstrator,

        [System.Xml.Serialization.XmlEnumAttribute("Showroom vehicle")]
        Showroomvehicle,

 

By using reflection you can gain access to the attribute, here is how:

Type enumType = typeof(velocityUom);

foreach (FieldInfo fi in enumType.GetFields())

{

object[] attrs = fi.GetCustomAttributes(typeof(XmlEnumAttribute), false);

if (attrs.Length > 0)

{

Console.WriteLine(((XmlEnumAttribute)attrs[0]).Name);

}

}

 


Culture Codes

June 19, 2009 11:07 by bryan

 

A comprehensive list of culture codes used for localising and in conjunction with the CultureInfo class.

The CultureInfo class specifies a unique name for each culture, based on RFC 4646 (Windows Vista and later). The name is a combination of an ISO 639 two-letter lowercase culture code associated with a language and an ISO 3166 two-letter uppercase subculture code associated with a country or region.

CodeLanguage - Country/RegionCodeLanguage - Country/Region
af Afrikaans hu-HU Hungarian - Hungary
af-ZA Afrikaans - South Africa is Icelandic
sq Albanian

 

is-IS Icelandic - Iceland
sq-AL Albanian - Albania id

 

Indonesian
ar Arabic id-ID Indonesian - Indonesia

 

ar-DZ Arabic - Algeria it Italian
ar-BH Arabic - Bahrain it-IT Italian - Italy
ar-EG Arabic - Egypt it-CH Italian - Switzerland
ar-IQ Arabic - Iraq ja Japanese
ar-JO Arabic - Jordan ja-JP Japanese - Japan
ar-KW Arabic - Kuwait kn Kannada
ar-LB Arabic - Lebanon kn-IN Kannada - India
ar-LY

 

Arabic - Libya kk Kazakh
ar-MA Arabic - Morocco

 

kk-KZ Kazakh - Kazakhstan
ar-OM Arabic - Oman kok

 

Konkani
ar-QA Arabic - Qatar kok-IN Konkani - India

 

ar-SA Arabic - Saudi Arabia ko Korean
ar-SY Arabic - Syria ko-KR Korean - Korea
ar-TN Arabic - Tunisia ky Kyrgyz
ar-AE Arabic - United Arab Emirates ky-KG Kyrgyz - Kyrgyzstan
ar-YE Arabic - Yemen lv Latvian
hy Armenian lv-LV Latvian - Latvia
hy-AM Armenian - Armenia lt Lithuanian
az

 

Azeri lt-LT Lithuanian - Lithuania
az-AZ-Cyrl Azeri (Cyrillic) - Azerbaijan

 

mk Macedonian
az-AZ-Latn Azeri (Latin) - Azerbaijan mk-MK

 

Macedonian - Former Yugoslav Republic of Macedonia
eu Basque ms Malay

 

eu-ES Basque - Basque ms-BN Malay - Brunei
be Belarusian ms-MY Malay - Malaysia
be-BY Belarusian - Belarus mr Marathi
bg Bulgarian mr-IN Marathi - India
bg-BG Bulgarian - Bulgaria mn Mongolian
ca Catalan mn-MN Mongolian - Mongolia
ca-ES Catalan - Catalan no Norwegian
zh-HK

 

Chinese - Hong Kong SAR nb-NO Norwegian (Bokm?l) - Norway
zh-MO Chinese - Macao SAR

 

nn-NO Norwegian (Nynorsk) - Norway
zh-CN Chinese - China pl

 

Polish
zh-CHS Chinese (Simplified) pl-PL Polish - Poland

 

zh-SG Chinese - Singapore pt Portuguese
zh-TW Chinese - Taiwan pt-BR Portuguese - Brazil
zh-CHT Chinese (Traditional) pt-PT Portuguese - Portugal
hr Croatian

 

pa Punjabi
hr-HR Croatian - Croatia pa-IN Punjabi - India
cs Czech ro Romanian
cs-CZ Czech - Czech Republic ro-RO Romanian - Romania
da

 

Danish ru Russian
da-DK Danish - Denmark

 

ru-RU Russian - Russia
div Dhivehi sa

 

Sanskrit
div-MV Dhivehi - Maldives sa-IN Sanskrit - India

 

nl Dutch sr-SP-Cyrl Serbian (Cyrillic) - Serbia
nl-BE Dutch - Belgium sr-SP-Latn Serbian (Latin) - Serbia
nl-NL Dutch - The Netherlands sk Slovak
en English sk-SK Slovak - Slovakia
en-AU English - Australia sl Slovenian
en-BZ English - Belize sl-SI Slovenian - Slovenia
en-CA English - Canada es Spanish
en-CB

 

English - Caribbean es-AR Spanish - Argentina
en-IE English - Ireland

 

es-BO Spanish - Bolivia
en-JM English - Jamaica es-CL

 

Spanish - Chile
en-NZ English - New Zealand es-CO Spanish - Colombia

 

en-PH English - Philippines es-CR Spanish - Costa Rica
en-ZA English - South Africa es-DO Spanish - Dominican Republic
en-TT English - Trinidad and Tobago es-EC Spanish - Ecuador
en-GB English - United Kingdom es-SV Spanish - El Salvador
en-US English - United States es-GT Spanish - Guatemala
en-ZW English - Zimbabwe es-HN Spanish - Honduras
et Estonian es-MX Spanish - Mexico
et-EE

 

Estonian - Estonia es-NI Spanish - Nicaragua
fo Faroese

 

es-PA Spanish - Panama
fo-FO Faroese - Faroe Islands es-PY

 

Spanish - Paraguay
fa Farsi es-PE Spanish - Peru

 

fa-IR Farsi - Iran es-PR Spanish - Puerto Rico
fi Finnish es-ES Spanish - Spain
fi-FI Finnish - Finland es-UY Spanish - Uruguay
fr French es-VE Spanish - Venezuela
fr-BE French - Belgium sw Swahili
fr-CA French - Canada sw-KE Swahili - Kenya
fr-FR French - France sv Swedish
fr-LU

 

French - Luxembourg sv-FI Swedish - Finland
fr-MC French - Monaco

 

sv-SE Swedish - Sweden
fr-CH French - Switzerland syr

 

Syriac
gl Galician syr-SY Syriac - Syria

 

gl-ES Galician - Galician ta Tamil
ka Georgian ta-IN Tamil - India
ka-GE Georgian - Georgia tt Tatar
de German tt-RU Tatar - Russia
de-AT German - Austria te Telugu
de-DE German - Germany te-IN Telugu - India
de-LI German - Liechtenstein th Thai
de-LU

 

German - Luxembourg th-TH Thai - Thailand
de-CH German - Switzerland

 

tr Turkish
el Greek tr-TR

 

Turkish - Turkey
el-GR Greek - Greece uk Ukrainian

 

gu Gujarati uk-UA Ukrainian - Ukraine
gu-IN Gujarati - India ur Urdu
he Hebrew ur-PK Urdu - Pakistan
he-IL Hebrew - Israel uz Uzbek
hi Hindi uz-UZ-Cyrl Uzbek (Cyrillic) - Uzbekistan
hi-IN Hindi - India uz-UZ-Latn Uzbek (Latin) - Uzbekistan
hu Hungarian vi Vietnamese

 


How to sort a generic List

May 19, 2009 09:34 by bryan

I came across a little issue today, in that I had an Interface object and I needed to be able to sort the list, I would normally implement the IComparable interface on the concreate type, but I don't have access to the concreate type in my case.

I tried several different methods in the end I ended up with using a delegate, and found in SimoneB Blog, which I have extracted the content below:

Sorting a generic List<T> is pretty straightforward if you know how to do it. With C# 2.0, anonymous methods come at hand, as well as the little known Comparison<T> delegate (check out this post for more information about this class as well as other useful classes new to C# 2.0).

Ok, let's suppose we have a product class (let me save some space by using C# 3.0 syntax).

 

class Product

{

    public int ProductID { get; set; }

    public string ProductName { get; set; }

    public decimal UnitPrice { get; set; }

}

When we have a list of products we may want to sort it on the ProductName property before displaying it to the user. This can be accomplished with the Sort method of the List<T> class, which defines several overloads. The most handy in this case is the Sort(Comparison<Product>) method and the result is easily achieved with a couple lines of code.

 

List<Product> products = new List<Product>();

 

products.Sort(delegate(Product p1, Product p2)

              {

                  return p1.ProductName.CompareTo(p2.ProductName);

              });

So far so good, but what if we need to sort our list in several places during the execution of our program? Do we have to write that code each time? Actually no, since we can use the parameterless Sort() method of our list class. What this method does is use the "default comparer" to sort the list. So what's this default comparer? It's the comparer that's automatically created if we implement the IComparable<T> interface. This way we can centralize the sorting logic into our class, and just call the parameterless Sort() method on it whenever we need it sorted on the ProductName property.

 

public class Product : IComparable<Product>

{

    [...]

 

    public int CompareTo(Product other)

    {

        return ProductName.CompareTo(other.ProductName);

    }

}

Ok, now what if we want to be able to sort it on the other two properties, ProductID and UnitPrice? Do we have to write an anonymous method each time as we did in the beginning? Of course no, since there's a useful trick which prevents us from needing to do that. We can define two static Comparer<Product> properties in our product class, and supply them as parameters to the Sort(Comparer<T>) method of our list whenever we need it sorted on something which is not the default sorting logic.

 

public class Product : IComparable<Product>

{

    [...]

 

    public static Comparison<Product> PriceComparison =

        delegate(Product p1, Product p2)

        {

            return p1.Price.CompareTo(p2.Price);

        };

 

    public static Comparison<Product> IDComparison =

        delegate(Product p1, Product p2)

        {

            return p1.ProductID.CompareTo(p2.ProductID);

        };

 

    [...]

}

Since they are static they can be used simply like so: products.Sort(Product.PriceComparison) or products.Sort(Product.IDComparison), which will respectively sort the list by price and id.

 

Below is the full code of the Product class.

 

public class Product : IComparable<Product>

{

    private int id;

    private string prodName;

    private decimal price;

 

    public static Comparison<Product> PriceComparison = delegate(Product p1, Product p2)

                                                        {

                                                            return p1.price.CompareTo(p2.price);

                                                        };

 

    public static Comparison<Product> IDComparison = delegate(Product p1, Product p2)

                                                     {

                                                         return p1.id.CompareTo(p2.id);

                                                     };

 

    public int ProductID

    {

        get { return id; }

        set { id = value; }

    }

 

    public string ProductName

    {

        get { return prodName; }

        set { prodName = value; }

    }

 

    public decimal UnitPrice

    {

        get { return price; }

        set { price = value; }

    }

 

    public Product(int id, string prodName, decimal price)

    {

        this.id = id;

        this.prodName = prodName;

        this.price = price;

    }

 

    #region IComparable<Product> Members

 

    public int CompareTo(Product other)

    {

        return ProductName.CompareTo(other.ProductName);

    }

 

    #endregion

 

    public override string ToString()

    {

        return string.Format("Id: {0} Name: {1} Price: {2}", id, prodName, price);

    }

}



Well all love a good Hack

May 18, 2009 09:53 by bryan

Been playing around with this hack for some time, it's fun, I can't remember where I first got the application from, but I've had some harmless fun with it in the office.

This small hack allows you to write information to most HP printers LCD screen.

HPHack.zip (6.49 kb)


Copy one object to another Object

May 15, 2009 13:43 by bryan

I was in need to copying one concreate object to another concreate object, but I needed the flexability that when a new property is added the method would not need to be changed, also I needed the ability for the method to take in any types.

So the first take was to generate a method that uses reflections to go over the obecjts properts and set the returning object properties.  That was quite simple, then to make the method more flexable I used generics to help with my method, to allow for any types to be used.

One thing to note is that you require the try catch, in case the GetValue or SetValue fails, such as if the object is null.

This is what I ended up with.

Here is the VB.NET method

Here is the C#

 


PDB, what and why?

May 14, 2009 13:17 by bryan

If you are like me when you are developing you create a Debug version of your application and in turn .NET provides you with .PDB files for debugging, that is as far as I know, want to know more about it then take a look at John Robbins' Blog on PDB files: what every developer must know


Only get the data that is needs to be displayed

May 12, 2009 09:58 by bryan

I have been on the look out for the ability to display and search a customers database, but having the ability to display millions of records if that what the end users wants.  But the trouble is that it can take a long time to return a million records from a data source.

I've talked about paging before in my article LINQ-to-SQL-and-Paging, which works fine for internet based paging, but what about WPF and WinForm Grids, well I came across Vitrual Mode for the Microsoft Data Grid, which can provide an answer.  What this allow you to do is, load the data you can see on the screen very quickly and as you scroll through the data is fetched when required.

By setting the VirtualMode = true for a data grid, it allows you to add a handler for deail with CellValueNeeded 

Here is the main body of the code

Each time the Data grid needs some values it will call the following:

And of course the NameListCache class

 

I have attached the source, you will also find a PopulateData project to populate the database with data.

 

DataGridViewVirtualModePaging.zip (19.43 kb)

PopulateData.zip (11.43 kb)

Here are a few of the database scripts that yu will need for the sample

Names.sql (581.00 bytes)

GetNames.sql (786.00 bytes)


Yeald

May 3, 2009 17:41 by bryan

Okay, I've learn't something new today, so I'd thought I would share it with you, it's the yeald keyword, the reason why I think I have not used or know about it before is that it is used for an IEnumerable collection, which has come more in to play with LINQ, here is a short example of how it can be used:

 

This generates the following output:

 

 

 

It just makes sense to do it this way, much cleaner and much more efficient.

For more details check of MSDN on yeald.

It's worth noting that Yield is not support with VB.NET

 

 


Caching from a non Web applications

February 6, 2009 08:30 by bryan

Okay you are developing a WinForm application and you are looking at performance, one area is Caching of information, but wait a minute I've been using caching in my web applications for sometime, but how do you do it from a WinForm application as you don't have a host to store your cache.

Would you know it you can use the web cache too, just you have to take a few extra steps to retain your cache, either in memory or in temporary files.

You can use the HttpRequest to store the System.Web.Cache objects in your application, and this works well.

I also came across any Blog, providing another method to Caching, however I have a little concern over this method of caching in files as you are likely to get file locking.

Using System.Web.Caching From The Console Or Windows Forms

I've written my own simple VB.NET application to show it working and just holding the Cache in memory for the life of the application.

WinFormCache.zip (17.73 kb)

Of course you could run a Windows Service which holds all the Cache information, this way it will be available to all your WinForm applications should you require it.