Thursday 7 April 2011

Code behind Color List

Some users have requested the code I used to generate the Any Colur you like as long as its .NET post last week. The following is the c# function I used to extract the list of colours.
void ShowColours()
{
    // Get an array of all known colours
    KnownColor[] colours = (KnownColor[])Enum.GetValues(typeof(KnownColor));
    for (int i = 0; i < colours.Length; i++)
    {
        Color c = Color.FromName(colours[i].ToString());

        if (c.IsSystemColor)
        {
            Console.WriteLine(
                string.Format(
                "System Colour : {0} [Hex #{1}] [RGB {2}/{3}/{4}]",
                    c.Name, c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2"),
                    BitConverter.ToInt16(new byte[2] { c.R, byte.MinValue, }, 0),
                    BitConverter.ToInt16(new byte[2] { c.G, byte.MinValue, }, 0),
                    BitConverter.ToInt16(new byte[2] { c.B, byte.MinValue, }, 0)
                    ));
        }
        else
        {
            Console.WriteLine(
                string.Format(
                "Predefined Colour : {0} [Hex #{1}] [RGB {2}/{3}/{4}]",
                    c.Name, c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2"),
                    BitConverter.ToInt16(new byte[2] { c.R, byte.MinValue, }, 0),
                    BitConverter.ToInt16(new byte[2] { c.G, byte.MinValue, }, 0),
                    BitConverter.ToInt16(new byte[2] { c.B, byte.MinValue, }, 0)
                    ));
        }
    }
The following Extracts a list of all System.Drawing.KnownColor Enumeration values and assigns them to an array.
KnownColor[] colours = (KnownColor[])Enum.GetValues(typeof(KnownColor));

The following line converts the byte value for the colour, and converts it to a Hexadecimal value.
c.R.ToString("X2")

Converts a byte value to an Int16 value. The colour is represented by a single byte but the functon requires two bytes, so we add a second byte with value as byte.MinValue. The result is a value 0-255 inclusive representing the colour value.
BitConverter.ToInt16(new byte[2] { c.R, byte.MinValue, }, 0)
Hope this code helps!
Disclaimer: The content provided in this article is not warranted or guaranteed by rnddev. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts. As such it is inferred on to the reader to employ real-world tactics for security and implementation of best practices. I am not liable for any negative consequences that may result from implementing any information covered in this or other articles or blog posts.

Thursday 31 March 2011

Any Colour you like, as long as its .NET

In .NET applications you can make any colour you like be supplying the R, G, and B values into the System.Drawing.Color structure structure. However, the color structure in .NET has a set of predefined colors.

The Color structure contains quite a few color names, however, reading the names on some of these colors does not make it immediately apparent what the color looks like. As such, I have exported a list of all the colours that are defined in the System.Drawing.Color structure's enum System.Drawing.KnownColor.


    System Colours

  •  ActiveBorder[Hex #D4D0C8] [RGB 212/208/200]
  •  ActiveCaption[Hex #0A246A] [RGB 10/36/106]
  •  ActiveCaptionText[Hex #FFFFFF] [RGB 255/255/255]
  •  AppWorkspace[Hex #808080] [RGB 128/128/128]
  •  Control[Hex #D4D0C8] [RGB 212/208/200]
  •  ControlDark[Hex #808080] [RGB 128/128/128]
  •  ControlDarkDark[Hex #404040] [RGB 64/64/64]
  •  ControlLight[Hex #D4D0C8] [RGB 212/208/200]
  •  ControlLightLight[Hex #FFFFFF] [RGB 255/255/255]
  •  ControlText[Hex #000000] [RGB 0/0/0]
  •  Desktop[Hex #3A6EA5] [RGB 58/110/165]
  •  GrayText[Hex #808080] [RGB 128/128/128]
  •  Highlight[Hex #0A246A] [RGB 10/36/106]
  •  HighlightText[Hex #FFFFFF] [RGB 255/255/255]
  •  HotTrack[Hex #000080] [RGB 0/0/128]
  •  InactiveBorder[Hex #D4D0C8] [RGB 212/208/200]
  •  InactiveCaption[Hex #808080] [RGB 128/128/128]
  •  InactiveCaptionText[Hex #D4D0C8] [RGB 212/208/200]
  •  Info[Hex #FFFFE1] [RGB 255/255/225]
  •  InfoText[Hex #000000] [RGB 0/0/0]
  •  Menu[Hex #D4D0C8] [RGB 212/208/200]
  •  MenuText[Hex #000000] [RGB 0/0/0]
  •  ScrollBar[Hex #D4D0C8] [RGB 212/208/200]
  •  Window[Hex #FFFFFF] [RGB 255/255/255]
  •  WindowFrame[Hex #000000] [RGB 0/0/0]
  •  WindowText[Hex #000000] [RGB 0/0/0]
  •  ButtonFace[Hex #D4D0C8] [RGB 212/208/200]
  •  ButtonHighlight[Hex #FFFFFF] [RGB 255/255/255]
  •  ButtonShadow[Hex #808080] [RGB 128/128/128]
  •  GradientActiveCaption[Hex #A6CAF0] [RGB 166/202/240]
  •  GradientInactiveCaption[Hex #C0C0C0] [RGB 192/192/192]
  •  MenuBar[Hex #ECE9D8] [RGB 236/233/216]
  •  MenuHighlight[Hex #316AC5] [RGB 49/106/197]

     

    Predefined Colours

  •  Transparent[Hex #FFFFFF] [RGB 255/255/255]
  •  AliceBlue[Hex #F0F8FF] [RGB 240/248/255]
  •  AntiqueWhite[Hex #FAEBD7] [RGB 250/235/215]
  •  Aqua[Hex #00FFFF] [RGB 0/255/255]
  •  Aquamarine[Hex #7FFFD4] [RGB 127/255/212]
  •  Azure[Hex #F0FFFF] [RGB 240/255/255]
  •  Beige[Hex #F5F5DC] [RGB 245/245/220]
  •  Bisque[Hex #FFE4C4] [RGB 255/228/196]
  •  Black[Hex #000000] [RGB 0/0/0]
  •  BlanchedAlmond[Hex #FFEBCD] [RGB 255/235/205]
  •  Blue[Hex #0000FF] [RGB 0/0/255]
  •  BlueViolet[Hex #8A2BE2] [RGB 138/43/226]
  •  Brown[Hex #A52A2A] [RGB 165/42/42]
  •  BurlyWood[Hex #DEB887] [RGB 222/184/135]
  •  CadetBlue[Hex #5F9EA0] [RGB 95/158/160]
  •  Chartreuse[Hex #7FFF00] [RGB 127/255/0]
  •  Chocolate[Hex #D2691E] [RGB 210/105/30]
  •  Coral[Hex #FF7F50] [RGB 255/127/80]
  •  CornflowerBlue[Hex #6495ED] [RGB 100/149/237]
  •  Cornsilk[Hex #FFF8DC] [RGB 255/248/220]
  •  Crimson[Hex #DC143C] [RGB 220/20/60]
  •  Cyan[Hex #00FFFF] [RGB 0/255/255]
  •  DarkBlue[Hex #00008B] [RGB 0/0/139]
  •  DarkCyan[Hex #008B8B] [RGB 0/139/139]
  •  DarkGoldenrod[Hex #B8860B] [RGB 184/134/11]
  •  DarkGray[Hex #A9A9A9] [RGB 169/169/169]
  •  DarkGreen[Hex #006400] [RGB 0/100/0]
  •  DarkKhaki[Hex #BDB76B] [RGB 189/183/107]
  •  DarkMagenta[Hex #8B008B] [RGB 139/0/139]
  •  DarkOliveGreen[Hex #556B2F] [RGB 85/107/47]
  •  DarkOrange[Hex #FF8C00] [RGB 255/140/0]
  •  DarkOrchid[Hex #9932CC] [RGB 153/50/204]
  •  DarkRed[Hex #8B0000] [RGB 139/0/0]
  •  DarkSalmon[Hex #E9967A] [RGB 233/150/122]
  •  DarkSeaGreen[Hex #8FBC8B] [RGB 143/188/139]
  •  DarkSlateBlue[Hex #483D8B] [RGB 72/61/139]
  •  DarkSlateGray[Hex #2F4F4F] [RGB 47/79/79]
  •  DarkTurquoise[Hex #00CED1] [RGB 0/206/209]
  •  DarkViolet[Hex #9400D3] [RGB 148/0/211]
  •  DeepPink[Hex #FF1493] [RGB 255/20/147]
  •  DeepSkyBlue[Hex #00BFFF] [RGB 0/191/255]
  •  DimGray[Hex #696969] [RGB 105/105/105]
  •  DodgerBlue[Hex #1E90FF] [RGB 30/144/255]
  •  Firebrick[Hex #B22222] [RGB 178/34/34]
  •  FloralWhite[Hex #FFFAF0] [RGB 255/250/240]
  •  ForestGreen[Hex #228B22] [RGB 34/139/34]
  •  Fuchsia[Hex #FF00FF] [RGB 255/0/255]
  •  Gainsboro[Hex #DCDCDC] [RGB 220/220/220]
  •  GhostWhite[Hex #F8F8FF] [RGB 248/248/255]
  •  Gold[Hex #FFD700] [RGB 255/215/0]
  •  Goldenrod[Hex #DAA520] [RGB 218/165/32]
  •  Gray[Hex #808080] [RGB 128/128/128]
  •  Green[Hex #008000] [RGB 0/128/0]
  •  GreenYellow[Hex #ADFF2F] [RGB 173/255/47]
  •  Honeydew[Hex #F0FFF0] [RGB 240/255/240]
  •  HotPink[Hex #FF69B4] [RGB 255/105/180]
  •  IndianRed[Hex #CD5C5C] [RGB 205/92/92]
  •  Indigo[Hex #4B0082] [RGB 75/0/130]
  •  Ivory[Hex #FFFFF0] [RGB 255/255/240]
  •  Khaki[Hex #F0E68C] [RGB 240/230/140]
  •  Lavender[Hex #E6E6FA] [RGB 230/230/250]
  •  LavenderBlush[Hex #FFF0F5] [RGB 255/240/245]
  •  LawnGreen[Hex #7CFC00] [RGB 124/252/0]
  •  LemonChiffon[Hex #FFFACD] [RGB 255/250/205]
  •  LightBlue[Hex #ADD8E6] [RGB 173/216/230]
  •  LightCoral[Hex #F08080] [RGB 240/128/128]
  •  LightCyan[Hex #E0FFFF] [RGB 224/255/255]
  •  LightGoldenrodYellow[Hex #FAFAD2] [RGB 250/250/210]
  •  LightGray[Hex #D3D3D3] [RGB 211/211/211]
  •  LightGreen[Hex #90EE90] [RGB 144/238/144]
  •  LightPink[Hex #FFB6C1] [RGB 255/182/193]
  •  LightSalmon[Hex #FFA07A] [RGB 255/160/122]
  •  LightSeaGreen[Hex #20B2AA] [RGB 32/178/170]
  •  LightSkyBlue[Hex #87CEFA] [RGB 135/206/250]
  •  LightSlateGray[Hex #778899] [RGB 119/136/153]
  •  LightSteelBlue[Hex #B0C4DE] [RGB 176/196/222]
  •  LightYellow[Hex #FFFFE0] [RGB 255/255/224]
  •  Lime[Hex #00FF00] [RGB 0/255/0]
  •  LimeGreen[Hex #32CD32] [RGB 50/205/50]
  •  Linen[Hex #FAF0E6] [RGB 250/240/230]
  •  Magenta[Hex #FF00FF] [RGB 255/0/255]
  •  Maroon[Hex #800000] [RGB 128/0/0]
  •  MediumAquamarine[Hex #66CDAA] [RGB 102/205/170]
  •  MediumBlue[Hex #0000CD] [RGB 0/0/205]
  •  MediumOrchid[Hex #BA55D3] [RGB 186/85/211]
  •  MediumPurple[Hex #9370DB] [RGB 147/112/219]
  •  MediumSeaGreen[Hex #3CB371] [RGB 60/179/113]
  •  MediumSlateBlue[Hex #7B68EE] [RGB 123/104/238]
  •  MediumSpringGreen[Hex #00FA9A] [RGB 0/250/154]
  •  MediumTurquoise[Hex #48D1CC] [RGB 72/209/204]
  •  MediumVioletRed[Hex #C71585] [RGB 199/21/133]
  •  MidnightBlue[Hex #191970] [RGB 25/25/112]
  •  MintCream[Hex #F5FFFA] [RGB 245/255/250]
  •  MistyRose[Hex #FFE4E1] [RGB 255/228/225]
  •  Moccasin[Hex #FFE4B5] [RGB 255/228/181]
  •  NavajoWhite[Hex #FFDEAD] [RGB 255/222/173]
  •  Navy[Hex #000080] [RGB 0/0/128]
  •  OldLace[Hex #FDF5E6] [RGB 253/245/230]
  •  Olive[Hex #808000] [RGB 128/128/0]
  •  OliveDrab[Hex #6B8E23] [RGB 107/142/35]
  •  Orange[Hex #FFA500] [RGB 255/165/0]
  •  OrangeRed[Hex #FF4500] [RGB 255/69/0]
  •  Orchid[Hex #DA70D6] [RGB 218/112/214]
  •  PaleGoldenrod[Hex #EEE8AA] [RGB 238/232/170]
  •  PaleGreen[Hex #98FB98] [RGB 152/251/152]
  •  PaleTurquoise[Hex #AFEEEE] [RGB 175/238/238]
  •  PaleVioletRed[Hex #DB7093] [RGB 219/112/147]
  •  PapayaWhip[Hex #FFEFD5] [RGB 255/239/213]
  •  PeachPuff[Hex #FFDAB9] [RGB 255/218/185]
  •  Peru[Hex #CD853F] [RGB 205/133/63]
  •  Pink[Hex #FFC0CB] [RGB 255/192/203]
  •  Plum[Hex #DDA0DD] [RGB 221/160/221]
  •  PowderBlue[Hex #B0E0E6] [RGB 176/224/230]
  •  Purple[Hex #800080] [RGB 128/0/128]
  •  Red[Hex #FF0000] [RGB 255/0/0]
  •  RosyBrown[Hex #BC8F8F] [RGB 188/143/143]
  •  RoyalBlue[Hex #4169E1] [RGB 65/105/225]
  •  SaddleBrown[Hex #8B4513] [RGB 139/69/19]
  •  Salmon[Hex #FA8072] [RGB 250/128/114]
  •  SandyBrown[Hex #F4A460] [RGB 244/164/96]
  •  SeaGreen[Hex #2E8B57] [RGB 46/139/87]
  •  SeaShell[Hex #FFF5EE] [RGB 255/245/238]
  •  Sienna[Hex #A0522D] [RGB 160/82/45]
  •  Silver[Hex #C0C0C0] [RGB 192/192/192]
  •  SkyBlue[Hex #87CEEB] [RGB 135/206/235]
  •  SlateBlue[Hex #6A5ACD] [RGB 106/90/205]
  •  SlateGray[Hex #708090] [RGB 112/128/144]
  •  Snow[Hex #FFFAFA] [RGB 255/250/250]
  •  SpringGreen[Hex #00FF7F] [RGB 0/255/127]
  •  SteelBlue[Hex #4682B4] [RGB 70/130/180]
  •  Tan[Hex #D2B48C] [RGB 210/180/140]
  •  Teal[Hex #008080] [RGB 0/128/128]
  •  Thistle[Hex #D8BFD8] [RGB 216/191/216]
  •  Tomato[Hex #FF6347] [RGB 255/99/71]
  •  Turquoise[Hex #40E0D0] [RGB 64/224/208]
  •  Violet[Hex #EE82EE] [RGB 238/130/238]
  •  Wheat[Hex #F5DEB3] [RGB 245/222/179]
  •  White[Hex #FFFFFF] [RGB 255/255/255]
  •  WhiteSmoke[Hex #F5F5F5] [RGB 245/245/245]
  •  Yellow[Hex #FFFF00] [RGB 255/255/0]
  •  YellowGreen[Hex #9ACD32] [RGB 154/205/50]
Disclaimer: The content provided in this article is not warranted or guaranteed by rnddev. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts. As such it is inferred on to the reader to employ real-world tactics for security and implementation of best practices. I am not liable for any negative consequences that may result from implementing any information covered in this or other articles or blog posts.

Tuesday 15 March 2011

Sql Database Wrapper

I often find myself repeating same processes in .NET over the course of several projects. One of these repeating tasks in writing code to access database data. .NET goes a long way towards assisting developers in simplifying their work and automating tasks. At times you need to query data in your application code to perform some logic. This can quickly become tedious, and to assist I created a C# class that provides some basic functionality for access an SQL database.

The source file is available to download in the form of a zip file at the bottom of the page. The source was developed with C#.NET in Visual Studio 2010 for the .NET framework version 4. It should work with other versions of .NET but may require minor tweaks. If you have problems using it in your code, leave a message below and I will try to assist.
  1. Initialising the wrapper

    Include the .cs file from the zip in your project. Firstly you will need to provide a connection string, this can be loaded from application configuration file or supplied directly.
    // Assuming GetConnectionstring() returns a valid connection string
    SqlDbManager.ConnectionString = GetConnectionstring();
    The connection string property can only be initialised once. I added this requirement as my projects are dependant on one database or databases that are accessible from this database.
  2. Creating a connection

    Once the wrapper has been initialised with a connection string, it can be used by calling the GetConnection() static method to retrieve a connection. The wrapper is designed to keep a number of connections to hand and provide them on demand. If there are no available connections, then a new connection is spawned. Also, the connection retrieval process has been developed with multi threading in mind.
    To retrieve a connection use :
        SqlDbManger connection = SqlDbManager.GetNewConnection();
        
  3. Working with SqlDbManager

    once a new connection has been established it can be used to retrieve data in various ways. I have allowed for the most common scenarios of, update, insert, retrieve a single value, retrieve a record, or retrieve a set of data.
    1. Passing Parameters

      Any sql command can have parameters and the SqlDbManager will accept any number of parameters supplied to it.
      The parameters must be supplied in the form of a list, ie, List<SqlParameter>. List is generic type, and used to load SqlParameters to the command.
      List <SqlParameter> parameters = new List<SqlParameter>();
      parameters.add(new SqlParameter("@employeeName", "Joe Bloggs"));
    2. ExecuteNonQuery

      ExecuteNonQuery() works in a similar way to the SqlCommand.ExecuteNonQuery() method. It will carry out the requested command against the connection and return the number of rows affected. It is most effective for update or insert commands, where no data is returned.
      // Assuming there is a data table emplyee with columns id, and name already present
      int rowsAffected = connection.ExecuteNonQuery("INSERT INTO employee (id, name) VALUES (1, N'a')", CommandType.Text, null);
    3. ExecuteScalar

      ExecuteScalar() works in a similar way to SqlCommand.ExecuteScalar() method. It will carry out the requested command against the connection and return the first column of the first row.
      // Assuming there is a stored procedure sp_GetEmployeeID already present that returns an employee ID for a supplied employee name
      List <SqlParameter> parameters = new List<SqlParameter>();
      parameters.add(new SqlParameter("@employeeName", "Joe Bloggs"));
      int employeeID = (int)connection.ExecuteScalar("sp_GetEmployeeID", CommandType.StoredProcedure, parameters);
    4. ExecuteRetrieve

      ExecuteRetrieve() will get a datatable of the results returned from the database. This is most effective for instances where a Sql command will return multiple rows.
      // Assuming there is a stored procedure sp_GetAllEmployees already present that returns all employees
      DataTable employees= connection.ExecuteRetrieve("sp_GetEmployeeID", CommandType.StoredProcedure, null);
    5. ExecuteRetrieveRow

      ExecuteRetrieveRow() will return the first row from the results returned by the sq query. This is most effective for instances where a Sql command will return just one record or when only the first record is wanted.
      // Assuming there is a stored procedure sp_GetEmployee already present that returns information about one employee
      List <SqlParameter> parameters = new List<SqlParameter>();
      parameters.add(new SqlParameter("@employeeName", "Joe Bloggs"));
      DataRow employee = connection.ExecuteRetrieve("sp_GetEmployee", CommandType.StoredProcedure, parameters);
  4. Summary

    The SqlDbManager class is a basic wrapper for accessing Sql data. It allows querying of the sql database in various ways, with different adaptations of the data.
Article Files : SqlDbManager.zip
Disclaimer: The content provided in this article is not warranted or guaranteed by rnddev. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts. As such it is inferred on to the reader to employ real-world tactics for security and implementation of best practices. I am not liable for any negative consequences that may result from implementing any information covered in this or other articles or blog posts.

Thursday 10 March 2011

Assigning key value pairs to a combo box

Assigning key value pairs to a combo box Recently someone asked me how to assign values to a combo box in .NET. The request seemed simple enough, but it can often confuse someone new to the .NET framework. To help them, and others following is a quick rundown on some of the options available.
  1. Loop values

    You can for loop through a list of values and add each item individually.
    string[] colours = new string[] 
        {
            "Red",
            "Green",
            "Yellow"
        };
    foreach(string colour in colours)
    {
        combobox1.Items.Add(colour);
    }        
    This will assign colours "Red", "Green", "Yellow" to a combo box named combobox1.
  2. Object Properties

    You can utilise the combobox's datasource property to load an array of objects.
    string[] colours = new string[] 
        {
            "Red",
            "Green",
            "Yellow"
        };
    combobox1.DataSource = colours;        
    Again, this will assign colours "Red", "Green", "Yellow" to a combo box named combobox1, but its much simpler. This method uses the object's ToString() function to determine the display text for each item.
  3. Object without ToString()

    Method two above will work in situations where the object's value returns a human readable ToString() value. However, this is not always the case, to work around this, we can utilise the combobox's DisplayMember property. Take a look at the below example, I am creating a new class 'Employee' which has two properties - ID and Name.
    class Employee
    {
        private int _id;
        private string _name;
        public Employee(int id, string name)
        {
            _id = id;
            _name = name;
        }
        public int ID
        {
            get
            {
                return _id;
            }
        }
    
        public string Name
        {
            get
            {
                return _name;
            }
        }
    }
    
    When an array of employees is assigned to a combo box object, it will only display the object type not Employee Name.
    Employee[] employees = new Employee[2];
    employees[0] = new Employee(1, "Jane Smith");
    employees[1] = new Employee(2, "John Smith");
    combobox1.DataSource = employees;
    To overcome this we can set the DisplayMember property of the combobox to the property of the object which I want to show in the combobox, in this case 'Name'.
    combobox1.DisplayMember = "Name";        
    This will show 'Jane Smith' and 'John Smith' in the combobox drop down list.
  4. Different value and display items

    In example 3, I was able to display 'Jane Smith' and 'John Smith' in the combo box. However, the ID value is the primary key for the Employee data and as such we need to utilise it in other code, and need easy access to it. In this case we can use the ValueMember property load the value for each entry. Taking the Employee class from example 3 we can create
    Employee[] employees = new Employee[2];
    employees[0] = new Employee(1, "Jane Smith");
    employees[1] = new Employee(2, "John Smith");
            
    combobox1.DataSource = employees;
    combobox1.DisplayMember = "Name";
    combobox1.ValueMember = "ID";        
    This will result in the property "ID" being paired with each combo box item, and available as 'combobox1.SelectedValue' property.
  5. Linking directly to tables

    At times it is necessary to load data to a combobox from a database. We can either convert the returned data into an array or object and assign it to the combobox via the datasource property. However, you can use the same principal to map a data table to a combobox object. If we have a data table 'dt' that is filled from the database with the employee values.
    ID Name
    1 Jane Smith
    2 John Smith
    We can assign the table directly to the combobox and use the principals from example 4 to assign values.
    SqlDataAdapter da = new SqlDataAdapter(
        new SqlCommand("GetEmployees"),
        "datbaseconnection");
    DataTable dt = new DataTable();
    da.Fill(dt);
    combobox1.DataSource = dt;
    combobox1.DisplayMember = "Name";
    combobox1.ValueMember = "ID";
    This will produce the same results as example 4, but it will be loaded dynamically from the database.
Enjoy!
Disclaimer: The content provided in this article is not warranted or guaranteed by rnddev. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts. As such it is inferred on to the reader to employ real-world tactics for security and implementation of best practices. I am not liable for any negative consequences that may result from implementing any information covered in this or other articles or blog posts.