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
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 Concept/algorithm Database VB.NET/VB

Static Object in ASP.NET

Recently I found a problem in one of application we developed. Here my colleague use a Static SqlConnection object through a class in his code. He did that to save his effort of writing and Connection everytime. Everything works great during our development and online reviewing. However as soon as we lauch website in beta mode, it start creating problem which seems bit random in occurance and hence were hard to track. During this time I get involve in the project development and I was not very big fan on Static object and start to think against that code, which looks good to me at first. However for some reason I miss the basic of C# and ASP.NET and hence it took a while to recognize the problem was indeed the static code. So for those who did same mistake here is explanation of why Static object didn’t work in ASP.NET for connection.

When ASP.NET application is first called the complete code is loaded in Memory, specially the pages in App_Code folder and they act as part of web server and not as standard PHP site where they run and loaded on each request. Hence, once this happens all static object become static in memory for each and every request your server will get. This is indeed good way to share information between all User and all request, if that help your case. But in most general case you never want to share information between user in this dynamic method, which is not permanent. Anyways, for connection it really doesn’t make a difference if you share the object as you anyways want to open connection and close it as soon as you are done. In most case you have 1 simple insert or fetch query to run. And in a website with several users at a time it hardly make a difference as Sqlconnection are open and close in jiffy and took less than 1 second in most cases. For a shopping cart which has 100 -200 order per month this case will work just fine.

However, since connection is shared, there is every possible chance that if you fire a SQL query for say Reader, it get shared with some user on some other session and this is what you don’t want. It happens to our project when we have Bulk CSV upload which usually take 30-50 seconds, but if someone during this time fires and open other page of website they start to get random Database related errors. From SqlReader is close to field “Xyz” is not available, as they tend to share the connection with other requests.

Hope you avoid those problem. The colleague who did this in our project is not working with us anymore, but hey, where ever you are , please don’t punish us like this again !!!

Categories
Concept/algorithm HTML/CSS Javascript JQuery

Selecting menu item using Javascript

Okay, I create a pure CSS menu that use UL/LI structure to maintain the child relationship. All was great with this menu except that when you are on any of menu item page it doesn’t highlight that menu item explicitly. If you consider this it is not a big deal. What you can do is simply, iterate through the Menu Items which are probably in LI A tags. Once you iterate, find the URL in A tag and match the Page URL with the Menu ITEM link. If they match change the Class of respective LI or A as your liking.

try {
    var path = window.location.pathname.replace("/User/", "");
    if (path == "" )
        path="Userhome.aspx";
    $("#mainemnu a").each(function () {

        if ($(this).attr("href").toLowerCase() == path.toLowerCase() ) {
            if ($(this).parent().hasClass("submenuitem")) { //it is sub menu
                $(this).parent().parent().parent().addClass("selectedmenu");
            } else {
                $(this).parent().addClass("selectedmenu");
            }
        }
    });
} catch (err) { }

That was a simple Jquery Driven Javascript function that I call in Document ready function of Jquery.

Categories
Article Blog: My thoughts Concept/algorithm Programming

MVC : First Encounter

I have been reading about upcoming of MVC from quite few years, but I never feel the need of it. It is surprisingly but yes, I never feel of MVC in web development. I have created my own coding pattern which is good for most programming I have seen in my career. But still MVC always seems to attract me. So finally I decide to give it a try. I remember I try it with CodeIgnitor in PHP previously and was not very impressed with idea of MVC as I see it not quite upto the task as anyother framework it tend to load those load of script that are necessary to run MVC and the framework fine. Sometime you never need that many files. But still I was wondering why people look for something in that line? Well you never learn answer of such question unless you try yourself. So, I try it with .NET 4.0, when I got a chance to make a mobile website. I have to make a really small website and I feel it is best for to learn during this website development. I start it out with video tutorial and thanks to Scott Hanselman’s webcast I get my mind clear on MVC concepts in .NET and what is MVC in general.

Though MVC looks promising but I feel it is not probably not very mature or maybe not a good idea for big projects. I feel it little complex to make architecture of application with MVC as compare to transition event driven programming or procedural programming of old PHP. But yes it is way to dynamic and based on naming convection and assumption/concepts. Which make it cool. At first it looks good to me, but my second thought came in, if dynamic binding is that good then why we need Strong Data Type in applications? Why .NET or Java strats like that and why PHP is going for OOPS programming which again become strong data type somewhere? Isn’t it slow to use dynamic binding then to static binding?

MVC is good for Expertise in either programming, designing or database handling. This make it good choice for enterprise software but definiately for a Geek programmer I feel it is not upto the mark. BTW why a geek programmer care about what is buzz in market, he do his job perfect anyways.

I am confused about MVC , I am not sure if I will adopt it in my future programming yet or will wait for something better to come up. Any advice.

Categories
Concept/algorithm Networking Programming

PWNAT : Example

I am having trouble to run PwNAT successfully. The problem was created due to sample provided on official site. Here is how you should run it for case

Machine A (IP: 192.168.1.3) -> NAT A (IP: 122.x.x.x) -> Internet -> NAT B (IP: 59.x.x.x) -> Machine B (192.168.2.10)

Now if Machine A wants to connect to Machine B and want to access Machine B’s Webserver. Here is what you do

Machine B is a Server in our case so run server here:

#./pwnat.exe -s 192.168.2.10 2222

Now on Machine A run this

#./pwnat.exe -c 192.168.1.3 2222 59.x.x.x 2222 localhost 80

Let me explain which values came from what.

First for server:

If you do not define the local IP, and define something like 0.0.0.0 which is ANY IP for machine, then PwNAT do not send the correct IP through NAT A and hence NAT A never forward any incoming request to you. So server IP must be your machine main IP or LAN IP that is connected to NAT A router. IF you have multiple IP Only specific the IP that NAT A router can understand, otherwise it will fail for sure.

You can define any port by since pwnat use 2222 as default I use that

Now on client, I again define Local IP that is understand by NAT B, to avoid any confusion, but here it can be anything because it is used for Tunnel and hence it will not interact with NAT. Port is again any random port you want. Later we define the NAT B Server’ IP because we want to make sure we send Packet to that router. hence we use 59.x.x.x IP. Please note that while establishing connection PWNAT do not use any port. Now Proxy Port is 2222 this should be the same port that server is open. Otherwise connection won’t happen for obvious reason.

Localhost and port 80 is Domain or IP where you want to get connected through NAT traversal Proxy.

I will try to write a code in .NET library but for now. I will use my NMAKE complied copy of pwnat 0.3 beta version. Yes I compile it using NMAKE without Cygwin and it works superb on my windows 7 machine.

Categories
Concept/algorithm Operating System PHP

Linux User authentication using PHP

In one of my last post i try to define how linux store its password. Today I will be putting Complete PHP code for it.

Just run it on your local server(mind it your Http server must be running as root user in order to use this script )

Its a raw way of doing password matching and shouldn’t be used for commerical application or servers. its purely Learning script

So here goes the script

6 && CRYPT_MD5 == 1) {
$salts = explode(“$”,”$userlist[1]”);
$salt = “\$1\$”.$salts[2].”\$”;
$gen_password= crypt($password,$salt);
if ($gen_password == $userlist[1]) {
$UserMatch = true;
}
else
{
$UserMatch = false;
}
}
else {
$UserMatch = false;
}
break;
}
}
return $UserMatch ;
}

if (ReadUser(“sumit”) == true)
{
if (MatchPassword(“sumit”,”sumit”) == true )
{
echo “Login successful”;
}
else
{
echo “Login unsuccessful”;
}
}
?>

Hope that helps learn understanding linux passwd and shadow usage.

EDIT: I will update the script sometime sooner maybe!!!