Categories
.NET C#.NET Programming

Extensions Method in .NET

Recently I use extension method in C# project. I knew those for years, but really never get a chance to use them where they are most effect. I have couple of extension method in my project, such as ToInteger(), for a string to convert a String to Integer, which I used more frequently in my project. But that doesn’t seems a good use of technology to me.

But I now found a perfect use for extension method. i.e. I was upgrade my code from old ASP.NET project to MVC and for this I am making a class library of all objects. Now, this scenario need me to make a conversion from old enum to new enum  which are now part of namespace of my class library, rather than sitting around in App_Code folder. Here I make a extension method that convert a OLD enum to new name space base. This ease lot of my works.

Method goes like:


public static NewType GetSaleType(this OldType s)
{
	NewType r = NewType.Regular;
	switch (s)
	{
		case OldType.BK: r = NewType.BK; break;
		case OldType.IL: r = NewType.IL; break;
		case OldType.MM: r = NewType.MM; break;
		case OldType.PC: r = NewType.PC;break;
		case OldType.Regular: r = NewType.Regular; break;
		case OldType.Trigger:r = NewType.Trigger; break;
	}
	return r;
}
Categories
C#.NET Concept/algorithm Operating System

Refreshing USB ports using C#

Finished a project in which I need to refresh the USB ports by just before we start some particular benchmarking application my client has. Seems pretty easy job, if you know to gain access of system resource. But, it become fun job, when I found that knowledge of system is not even necessary for this job. Thanks to Microsoft’s `Devcon` utility, that already take care of it. So, in all what I have to do is just pass the correct parameter to it. The parameter is pretty easy, just pass the Hardware ID of USB port to refresh.

Yeah, that’s pretty easy. But …

Yes, but how we get the hardware id of USB port? Do we still need access to system resource for that? Well, it seems so. So we are back to square one. Well not really. I found a solution on web that points to `System.Management` namespace in .NET. What it does is it give you the list of all resources that are otherwise available through Computer management or such system resources. Here is main piece of code from article

public static List GetUSBDevices()
{
	List devices = new List();

	ManagementObjectCollection collection;
	//Win32_PnPEntity
	//Win32_USBControllerDevice
	using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
		collection = searcher.Get();

	foreach (var device in collection)
	{
		devices.Add(new USBDeviceInfo(
		(string)device.GetPropertyValue("DeviceID"),
		(string)device.GetPropertyValue("PNPDeviceID"),
		(string)device.GetPropertyValue("Description"),
		device.ToString()
		));
	}

	collection.Dispose();
	return devices;
}

This provide the list of all USB port in system, and then you can pass the “DeviceID” to devcon and we are done.

For further clarification:

Categories
.NET C#.NET

C#: Code to load Object from Database

It is often when managing old project that do not use ORM coding, we need to load object from database. In such scenarios it is quite boring to code all 30-40 property to load from DB. So, I wrote this simple code which does it quite well for me, the only catch is you need to define object property same as their DB column name. So, here is the quick code for the same.

public void LoadRS(DataRow rs)
    {
        foreach (PropertyInfo propertyInfo in this.GetType().GetProperties())
        {
            try
            {
                if (propertyInfo.CanRead)
                {
                    if (rs.Table.Columns.Contains(propertyInfo.Name))
                    {
                        
                        switch (propertyInfo.PropertyType.Name)
                        {
                            case "String":
                                propertyInfo.SetValue(this, Convert.ToString(rs[propertyInfo.Name]), null);
                                break;
                            case "Int64":
                                propertyInfo.SetValue(this, long.Parse(Convert.ToString(rs[propertyInfo.Name])), null);
                                break;
                            case "Int32":
                                propertyInfo.SetValue(this, int.Parse(Convert.ToString(rs[propertyInfo.Name])), null);
                                break;
                            default:
                                propertyInfo.SetValue(this, Convert.ChangeType(Convert.ToString(rs[propertyInfo.Name]), propertyInfo.PropertyType), null);
                                break;
                        }
                    }
                }
            }
            catch { }
        }
    }

  The code use the System.Reflection and then it read the Object property [see this.GetType().GetProperties() in foreach], iterate over properties and then checking if DataRow contain the same name column, if so, it load them. Basically the Default statement in Switch is enough for most cases, but I still leave it as is insight that in future I might need to cast some particular DB field to other field here. Oh, yes that one condition is boolean field. 

There are lot of upgradation coming in my mind as I write this blog entry, but currently no time to upgrade it and will add this function in my class library for future use. 

Categories
.NET C#.NET VB.NET/VB WPF

Self Hosted Web Service: WebServiceHost

So today I learn about WebServiceHost. Just a normal class but it does a lot for me today. This host the web service within you Desktop/Windows Service application. i.e. you don’t need to install any Web server or other stuff, just create a Service Contract Class and use WebServiceHost to host it within your application. 

I need this as part of my project, because I have to pass some server information to my application. I initially create a Seperete web application for this, but why maintain another application and increase setup time when I can host it within. I need it for just one particular value to be pass in JSON format to my client side. However one thing I must tell here is that the Host server application must be running as Administrative privilege or the service won’t start. For Windows Service run application as “LocalSystem” rather than default LocalService to keep it working.

It solve lot of problem and architectural issue I had in my project.  

Categories
.NET C#.NET VB.NET/VB WPF

WPF ComboBox: DataBinding with DataTable

Well it seems easy thing, but it took a while for me to get it working. Frankly I still don’t know why it works this way, but at least it works. With WPF I was expecting something as easy as giving DataTable object to ComboBox by it’s property and define the Data Field and Value field as in ASP.NET dropdownlist and it will bind, but this was not the case or at least the syntax is little different. So it goes like

ComboBox cb = new ComboBox(); /// You might already have object of it, so I just create it for sake of understanding here.
cb.ItemSource = MyDataTable.Rows; /// Yup, DataTable will not bind but it's rows collection will.
cb.DisplayMemberPath = ".[" + YourColumnNameVariable + "]"; ///in other other ".[columnname]" is what is expected;
cb.SelectedValuePath = ".[" + YourColumnNameVariable2 + "]"; ///in other other ".[columnname]" is what is expected;

This is all we need to do to get it working.

Categories
C#.NET Concept/algorithm Programming VB.NET/VB

MDI Window: C# way

So how can we make MDI Parent and Child Window in C#. The answer I found was that there is nothing inbuilt for it. So, I have two choice, either I modify the Window class and add MDI [Multiple Document Interface] coding in them or I found a alternative interface. 

It took less than 5 minute to decide that I can go with alternative interface after googling, the interface is TAB. Yup, much like your browser, they use TABs too, we create tab in  web portal, browser and lot of other things. So, they are perfect replacement for MDI window needs. The logic is as simple as, 

1. Create a TabControl on Main window.

2. Add couple of function, that search for TabItem in Tabcontrol if they exists or not, if exists focus them or add a new Tab Dynamically. Same logic on deletion of tab.

3. Create User Control from your Common custom Interface class and default UserControl object. Add these user control on Tab content when adding new tab.

I again didn’t keep the URL, but there is good example on it is available on MSDN and few other tutorial site. I try to post main component of logic below

namespace MyCommonLibrary
{
    /// 
    /// Deletgate for Tab Closing
    /// 
    /// 
    /// 
    public delegate void CloseTab(ITabbedWindow sender, EventArgs e);

    /// 
    /// Delegate to reload Tab Data.
    /// 
    /// 
    /// 
    public delegate void ReloadTabData(ITabbedWindow sender, EventArgs e);

    /// 
    /// Interface for Tabbed Windows Style MDI.
    /// 
    public interface ITabbedWindow
    {
        /// 
        /// Event for Closing Tab handle
        /// 
        event CloseTab CloseInitiated;

        /// 
        /// Event to reload Tab Data
        /// 
        event ReloadTabData Reload;

        /// 
        /// Name of the Tab Window
        /// 
        string TabName { get; set; }

        /// 
        /// Title of the Tab Window
        /// 
        string TabTitle { get; set; }

        /// 
        /// If Tab is loaded fully.
        /// 
        bool IsAllowRefresh { get; set; }


        void ReloadData();
    }
}

Above one is my common Interface which I use to implement in my User Control. After this all I have to do is add below function in my Parent window which has TabControl added to it.

#region Tab Functions
 #region Tab Functions

        public void AddChildWindow(ITabbedWindow childWndow)
        {
            if (childWindows.ContainsKey(childWndow.TabName))
            {
                foreach (TabItem tabItem in MDIContainer.Items)
                {
                    if (tabItem.Name == childWndow.TabName)
                    {                        
                        tabItem.Focus();
                        if (childWndow.IsAllowRefresh)
                        {
                            childWndow.CloseInitiated += new CloseTab(childWndow_CloseInitiated);
                            tabItem.Content = childWndow;
                        }
                        ITabbedWindow uc = tabItem.Content as ITabbedWindow;
                        try
                        {
                            if (uc != null )
                            {
                                uc.ReloadData();
                            }
                        }
                        catch { }
                        break;
                    }
                }
            }
            else
            {
                TabItem tabItem = new TabItem();
                tabItem.Name = childWndow.TabName;
                tabItem.Header = childWndow.TabTitle;
                tabItem.Content = childWndow;

                childWndow.CloseInitiated += new CloseTab(childWndow_CloseInitiated);

                MDIContainer.Items.Add(tabItem);
                MDIContainer.SelectedItem = tabItem;
                ITabbedWindow uc = tabItem.Content as ITabbedWindow;
                try
                {
                    if (uc != null)
                    {
                        uc.ReloadData();
                    }
                }
                catch { }
                
                childWindows.Add(childWndow.TabName, childWndow.TabTitle);
            }
        }

        public void RefreshTabContent(string mTabName)
        {
            foreach (TabItem tabItem in MDIContainer.Items)
            {
                if (tabItem.Name == mTabName)
                {
                    tabItem.Focus();
                    ITabbedWindow uc = tabItem.Content as ITabbedWindow;
                    try
                    {
                        if (uc != null)
                        {
                            uc.ReloadData();
                        }
                    }
                    catch { }
                    break;
                }
            }
        }

        void childWndow_CloseInitiated(ITabbedWindow sender, EventArgs e)
        {
            foreach (TabItem tabItem in MDIContainer.Items)
            {
                if (tabItem.Name == sender.TabName)
                {
                    MDIContainer.Items.Remove(tabItem);
                    childWindows.Remove(sender.TabName);
                    break;
                }
            }
        }
        #endregion

I just paste the portion where I control Tab, but it goes to code behind of mainwindow.xaml. One thing to note here is I use a SortedDictionary object to store the name of Tab in it for searching and retrieval of it. Rest is clear I guess.

 

Categories
.NET ASP.NET C#.NET VB.NET/VB

ASP.NET: Why my cookie is not saving

Funny, today after years I thought to finally use Cookies in one of my project. It is probably my first attempt to use Cookie in ASP.NET in last 5 yrs. WOW, that is amazing. Anyways, I just notice one thing and thought it might help any first timer, so here is the key note I want to share. In ASP.NET if you want to read Cookie, use REQUEST.Cookies, but if you want to add new Cookie use RESPONSE.Cookies. This is very minor difference and I really waste 30 minutes before I release I was using Request.Cookies to add new cookie, but it won’t get added that way.