C# Resize an image by size of height

1. March 2011 22:06

The goal of this is simple. To resize an image to a certain maximum width or maximum height. For this i have created a couple of function's for dealing with image size. Of course the trick here is to maintain the aspect ratio of the image during the resize operation to make sure that the image will not appear squashed.

Here are the functions More...

E-mail Kick it! DZone it! del.icio.us Permalink


C# / MS SQL Get inserted value of NEWSEQUENTIALID()

23. February 2011 18:22

Here is a quick guide to get the new value of NEWSEQUENTIALID() when inserting a row into a table in ms sql. If you have attempted to use NEWSEQUENTIALID() before you will know that it is only possible to use as a generated value in the table when the row is being inserted. This is a guide to get this value from c# when inserting the row. More...

E-mail Kick it! DZone it! del.icio.us Permalink


C# Code Organization

18. February 2011 00:00

All the time i seem to come across example code on sites and various thing. Unfortunatly a large number of people tend to think that this is just how things are done in the real world. So time and time again i seem to come across projects where the same db connection code (as an example) is copied and pasted around all the pages in a project. This of course is just causing a mainantice problem for later.

A quick example of what i am talking about is below.

 

SqlConnection conDotNet = new SqlConnection(args);  

string sSQL = "Select sub_category_id, sub_category_text  
	from Sub_Category"; 

SqlCommand cmd = new SqlCommand(sSQL, conDotNet);  
conDotNet.Open();  
SqlDataReader dtrCat = cmd.ExecuteReader();  

catlist.DataSource = dtrCat;  
catlist.DataBind();

 

When i first started working in c# it was based around both windows forms and asp.net. On of the first steps that i did was to create a class lib that could be shared between the projects and all future projects for both windows forms and asp.net application. Later on it has also been applied to windows services and other automated systems that run automatically.

The very first thing I ended up creating because i knew that i was going to be using it *a lot* was a data base connection class called DBConn. It supports the following methods and properties.

 

interface IDBConn
    {
        void Dispose();
        int Execute(System.Data.IDbCommand Sql);
        int Execute(System.Data.SqlClient.SqlCommand Sql);
        int Execute(string sql);
        DataRow ExecuteDataRow(System.Data.IDbCommand Sql);
        DataRow ExecuteDataRow(System.Data.SqlClient.SqlCommand Sql);
        DataRow ExecuteDataRow(string Sql);
        DataSet ExecuteDataSet(System.Data.IDbCommand Sql);
        DataSet ExecuteDataSet(System.Data.SqlClient.SqlCommand Sql);
        DataSet ExecuteDataSet(string Sql);
        DataTable ExecuteDataTable(System.Data.IDbCommand Sql);
        DataTable ExecuteDataTable(System.Data.SqlClient.SqlCommand Sql);
        DataTable ExecuteDataTable(string Sql);
        IDataReader ExecuteReader(System.Data.IDbCommand Sql);
        SqlDataReader ExecuteReader(System.Data.SqlClient.SqlCommand Sql);
        object ExecuteScalar(System.Data.IDbCommand Sql);
        object ExecuteScalar(System.Data.SqlClient.SqlCommand Sql);
        object ExecuteScalar(string sql);
        System.Data.SqlClient.SqlConnection SqlConnection { get; }
    }

The implementation of the class is pretty straight forward. There is also some thread safe locking involved in the functions to make them work a little better in a mutli threaded enviroment. However the real trick is what todo with the class at the page level.

 

I use the current solution layout in asp.net c# for every project i work on.

  • The main web site project
  • A class lib specific to the web site project.
  • Multiple shared class lib's between projects.

The DBConn in this case is stored in the shared project lib. Along with some other treats to speed up development. It will also contine the a BasePage, BaseMasterPage, BaseUserControl, BaseHandler class's which are going to be inherited by App specific classes in the project class lib. Which are called AppPage, AppMasterPage etc.. Each type of page / component in the main project file then inherits the app specific classes.

So this forms a nice code layout in the following layer's. Using Default.aspx as a starting example.

Default -> AppPage -> BasePage -> System.Web.UI.Page

Each of these base classes contain a basic level of code for connecting to database's using a default connection string which is stored in the web config. The nice part about this is that the functionality can be changed in any of the layer's at any time. So as you get more page specific you can extend the functionality that you like per project.

This is where the likes of DBConn comes in. Since it's already setup and working at the most base class. We can access it at the page level while writting minimum code. So once a project is setup in this way i can simply render things onto a webpage in the following way all over my project (give that repList is a repeater control)

 

repList.DataSource = DBConn.Execute("SELECT * FROM TableX ORDER BY CreatedOn DESC");
repList.DataBind();

with this sort of setup you can imaging just how quickly it is possible to create new pages in you project to extend functionality. Allowing more time to focus on layout and functionality rather than fighting with lots and lots of the same code repeating all over your projects.

E-mail Kick it! DZone it! del.icio.us Permalink


C# Wake on Lan (WOL) Packet

10. February 2011 18:34

Sending a wake on lan packet from c# can actually be very easy.

Using the following class it make it even easyier. All you need to know is the mac address of the machine you are attempt to wakeup.

public static void WakeUp(string MAC_ADDRESS, IPAddress IPBCast)
        {
            UdpClient UDP = new UdpClient();

            try
            {
                UDP.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                
                int offset = 0;
                byte[] buffer = new byte[512];   // more than enough :-)

                //first 6 bytes should be 0xFF
                for (int y = 0; y < 6; y++)
                    buffer[offset++] = 0xFF;

                //now repeate MAC 16 times
                for (int y = 0; y < 16; y++)
                {
                    int i = 0;
                    for (int z = 0; z < 6; z++)
                    {
                        buffer[offset++] =
                            byte.Parse(MAC_ADDRESS.Substring(i, 2), NumberStyles.HexNumber);
                        i += 2;
                    }
                }

                UDP.EnableBroadcast = true;
                UDP.Send(buffer, 512, new IPEndPoint(IPBCast, 0x1));
            }
            catch (Exception ex)
            {
                UDP.Close();
                throw (ex);
            }
        }
    }

All you need todo is call the function with a valid MAC address and a broadcast ip address. In most cases 255.255.255.255 will work. However if you want to broadcast across a certain remote network on another subnet you may need to user X.X.255.255 for example. Otherwise the packet will not be routed to the correct network.

E-mail Kick it! DZone it! del.icio.us Permalink


C# Reboot or Shutdown windows

10. February 2011 18:22

Here a quick guide to show you how to reboot a windows computer from C#

Its actually reeally very simple.

With the following code you can create your own User32 class to call windows api directly.

 

public static class User32
    {
        [DllImport("user32.dll")]
        public static extern bool ExitWindowsEx(ExitWindowsFlags uFlag, UInt32 dwReserved);

        public static bool ExitWindowsEx(ExitWindowsFlags uFlag)
        {
            return ExitWindowsEx(uFlag, 0);
        }
    }

 

Note: you will also need 'using System.Runtime.InteropServices;' at the top of the C# file.

You will probably also want to define all the options that are avilable to use with the call.

 

[Flags]
    public enum ExitWindowsFlags {
        EWX_LOGOFF = 0,
        EWX_SHUTDOWN = 0x1,
        EWX_REBOOT = 0x2,
        EWX_FORCE = 0x4,
        EWX_POWEROFF = 0x8,
        EWX_FORCEIFHUNG = 0x10,
        EWX_RESTARTAPPS = 0x40
    }

 

The rest is now really simple.

 

static void Main(string[] args)
        {
            if (User32.ExitWindowsEx(ExitWindowsFlags.EWX_REBOOT) == false)
            {
                Console.WriteLine("FAILED!");
            }
            else
            {
                Console.WriteLine("SUCCESS!");
            }
        }

 

E-mail Kick it! DZone it! del.icio.us Permalink