Showing posts with label Visual Studio. Show all posts
Showing posts with label Visual Studio. Show all posts

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.

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.

Wednesday, 28 April 2010

Visual Studio 2010

A few days ago I received an email from Microsoft advertising the release of the new version of Visual Studio.  Now I work as a .NET developer, so Visual Studio is the most used application for me - next to firefox :o - so I took notice.

I had been pretty busy with new projects, so not had time to look at Visual Studio 2010 release candidates, so this was going to be my first attempt with Visual Studio.  Fortunately, I have an active MSDN subscription with a Visual Studio license, so I can get a copy for free.  Awesome I though, and fired up firefox to get myself a copy.

A length download later - 2+ Gb - and lots of grumbles from my co-workers as I took up the office bandwidth with my download, I had my copy of Visual Studio ready to go.

Now after a week or so of usage, I am not exactly impressed with the application, but it does have a few nice features.  Enough to dislodge Visual Studio 2008 from the most used application slot (not enough to out Firefox obviously).

Visual Studio 2010 brings in allot of new features, in addition to those publicised by Microsoft, I found the following interesting.

Usage Highlighting
When you put the caret on variable/function etc, all other occurrences of that particular item are highlighted also.  This is the feature I most loved about Netbeans and is a massive help when debugging code to track the usage of an item.

Multi-screen Support
Finally.  This has been a thorn to my side for a while now, when developing complex objects, I tend to have a few windows split horizontally, but I cant see all the code on both the panes easily.  Now I can simply drag out a window to my second screen and presto, all good!

Live Semantic Errors in C#
In the previous versions of visual studio, I loved working in Visual Basic because I could spot right away where I had mistyped something.  C# was not so kind, it would reveal the problems when compiling.  This happened more often than not with my light fingers and bad spelling skills.  Not any more, C# now provides the nagging red wavy underlines.

Auto-Code generation
Ability to generate method stubs of code based on their usage.  This allows me to flow with my codding and puts reminders for me to fill in the gaps later without the red wavy lines interfering with me spotting actual errors.

Threaded Add Reference box
In Visual Studio 2008 and prior, when adding reference for the first time in the instance of visual studio it would freeze while loading up the list of all the references available, only for me to click project and browse to the one I wanted.  Now that its on a separate thread, its much less of a nuisance.

Windows Presentation Foundation look and feel
This is a bit of a mix bag.  Though not fundamentally changed (like office 2003 -> office 2007), the looks have been dressed up a bit.  I think it does look nice without adding too much overhead in loading, others might disagree.

.Net 4
The next iteration of the .NET frame work.  There are some nice features in the new framework that I cant wait to get to grips with.

And I am sure other users have their own thoughts on what they like.