Afeef's profileAfeef Ahmed JanjuaPhotosBlogListsMore Tools Help
View Afeef Ahmed's profile on LinkedIn

Follow me on Twitter
 
Thanks for visiting!

Please wait...
Sorry, the comment you entered is too long. Please shorten it.
You didn't enter anything. Please try again.
Sorry, we can't add your comment right now. Please try again later.
To add a comment, you need permission from your parent. Ask for permission
Your parent has turned off comments.
Sorry, we can't delete your comment right now. Please try again later.
You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
Complete the security check below to finish leaving your comment.
The characters you type in the security check must match the characters in the picture or audio.

Quote of the Day

Loading...

Horoscopes

Loading...
Afeef Ahmad Janjua's Facebook Profile
May 09

Getting the USB Devices Information using WMI

One day at work i had a unique requirement. I wanted to list the usb devices attached with the client and then get their vendor or product id to store at the backend. I started search on google and found out that their was next to nothing on this subject. I also found out that many people were interested in the solution. Somehow after reading a awful amount of msdn documentation, it came to my understanding that i have to query two different Windows Management Instrumentation (WMI) classes to achieve the goal.

First of all i had to Enable Privilages on the ManagementScope object just to make sure that every thing works fine. Next came the QueryObject class that i used to create my first query using the “Win32_USBControllerDevice” WMI class. Using these ManagementScope and QueryObject instances i created an instance of ManagementObjectSearcher class and called its Get() method. This Get() method returned me an instance of ManagementObjectCollection class. I was interested in the Dependent property in each of the ManagementObject in this ManagementObjectCollection instance.

The Dependent property in each ManagementObject instance contains the DeviceId of a single usb device. So i extracted the DeviceId and created a second query based on this DeviceId. This time i queried “Win32_PnPEntity” WMI class. Which is a class for plug-n-play entities attached to the system. As you may guess there are all sorts of plug-n-play devices attached with the system. That’s precisely why we need the DeviceId in the query string. I again queried the hardware using the classes discussed above and got yet another a ManagementObjectCollection instance. For each ManagementObject instance i accessed my desired properties. I was mainly interested in the following properties

  • Device Description
  • Manufacturer (if any)
  • Device VendorId or ProductId
  • DeviceId (if any)

Following is a complete listing of the code

   1: protected void Page_Load(object sender, EventArgs e)
   2: {
   3:      ManagementScope scope = new ManagementScope("root\\CIMV2");
   4:     scope.Options.EnablePrivileges = true;
   5:     string Win32_USBControlerDevice = "Select * From Win32_USBControllerDevice";
   6:     ObjectQuery query = new ObjectQuery(Win32_USBControlerDevice);
   7:     ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
   8:     foreach (ManagementObject mgmtObj in searcher.Get())
   9:     {
  10:         string strDeviceName = mgmtObj["Dependent"].ToString();
  11:         string strQuotes = "'";
  12:         strDeviceName = strDeviceName.Replace("\"", strQuotes);
  13:         string[] arrDeviceName = strDeviceName.Split('=');
  14:         strDeviceName = arrDeviceName[1];
  15:         string Win32_PnPEntity = "Select * From Win32_PnPEntity "
  16:             + "Where DeviceID =" + strDeviceName;
  17:         ManagementObjectSearcher mySearcher = 
  18:             new ManagementObjectSearcher(Win32_PnPEntity);
  19:         foreach (ManagementObject mobj in mySearcher.Get())
  20:         {
  21:             string strDeviceID = mobj["DeviceID"].ToString();
  22:             string[] arrDeviceID = strDeviceID.Split('\\');
  23:             Response.Write("<br />");
  24:             Response.Write("<br />");
  25:             Response.Write("Device Description = " 
  26:                     + mobj["Description"].ToString());
  27:             Response.Write("<br />");
  28:             if (mobj["Manufacturer"] != null)
  29:             {
  30:                 Response.Write("Device Manufacturer = " 
  31:                     + mobj["Manufacturer"].ToString());
  32:                 Response.Write("<br />");
  33:             }
  34:             Response.Write("Device Version ID & Vendor ID = " + arrDeviceID[1]);
  35:             Response.Write("<br />");
  36:             Response.Write("Device ID = " + arrDeviceID[2].Trim('{', '}'));
  37:             Response.Write("<br />");
  38:         }
  39:     }
  40: }
Share this post :

Getting local and network printers information using WMI

In order to get the printers info installed on your local computer or on the network, you just need to query the “Win32_Printers” Windows Management Instrumentation (WMI) class by using the classes provided in the System.Management namespace. The process is fairly simple. First of all create an instance of ManagementObjectSearcher class and pass your query to the constructor of this class. The Get() method of the ManagementObjectSearcher class will return the an instance of ManagementObjectCollection class. Each ManagementObject instance in ManagementObjectCollection contains information about a single printer. Following is the code snippet to achieve this.

   1: protected void Page_Load(object sender, EventArgs e)
   2: {
   3:      ManagementObjectSearcher searcher;
   4:     string Win32_Printer = "SELECT * FROM Win32_Printer";
   5:     searcher = new ManagementObjectSearcher(Win32_Printer);
   6:  
   7:     foreach (ManagementObject mgmtObj in searcher.Get())
   8:     {
   9:         string Description = "Printer Name: " + mgmtObj["Name"].ToString()
  10:             + " System Name : " + mgmtObj["SystemName"].ToString()
  11:             + " Print Processor : " + mgmtObj["PrintProcessor"].ToString();
  12:         Response.Write("Description = " + Description);
  13:         Response.Write("Device ID = " +  mgmtObj["DeviceID"].ToString());
  14:     }
  15: }
Share this post :
May 01

Getting the network adaptor MAC & IP address with WMI

Recently i had a requirement at work to create an ASP.NET web page which can only be viewed by registered clients. Clients were registered using their network adapter’s MAC address. The solution was pretty simple and straight forward. One just needs to reference the System.Management namespace and query using the “Win32_NetworkAdapterConfiguration” Windows Management Instrumentation (WMI) Class. Following is the code snippet listing on how to achieve this.

   1: protected void Page_Load(object sender, EventArgs e)
   2: {
   3:     ManagementObjectSearcher searcher;
   4:     string ip = string.Empty;
   5:     string Win32_NetworkAdapterConfiguration = "Select * FROM  "
   6:     + "Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'";
   7:     searcher = new ManagementObjectSearcher(Win32_NetworkAdapterConfiguration);
   8:  
   9:     foreach (ManagementObject mgmtObj in searcher.Get())
  10:     {
  11:         Response.Write("Host IP Address = " + ((string[])mgmtObj["IPAddress"])[0]);
  12:         Response.Write("<br />");
  13:         Response.Write("Host MAC Address = " + mgmtObj["MACAddress"].ToString());
  14:     }
  15: }
Share this post :
March 15

Implement a custom RoleProvider for Role Permission and Security in ASP.NET

To implement a custom Role Provider, you will need to provide a concrete implementation of the RoleProvider class to ASP.NET, and plug it into the system through appropriate configuration settings.

The first step in implementing the custom provider is to derive a class from the RoleProvider abstract base class. To provide a complete implementation, you will need to provide overrides for all of the methods and properties of the RoleProvider class.

In this case I am going to create my own custom role provider class named MyRoleProvider.cs that derives from the RoleProvider class as shown in the following figure.

ClassDiagram1

The RoleProvider class resides in the System.Web.Security namespace and ProviderBase class from which RoleProvider class inherits, resides in namespace System.Configuration.Providers. Make sure you reference both of the namespaces in your project.

When you inherit from RoleProvider you have to implement all the methods and properties defined in that class because it’s an abstract class. In my case I’m going to implement only one method named GetRolesForUser() which takes a string parameter “username” and returns the Roles against that user. All the other methods through not implemented exception and hence are not shown. Here is the code

   1: public override string[] GetRolesForUser(string username) {
   2:  
   3:             string[] roleArray = null;
   4:  
   5:             RoleService roleService = new RoleService();
   6:  
   7:             Role[] roles = roleService.GetRolesForUser(username);
   8:  
   9:             roleArray = new string[roles.Length];
  10:  
  11:             for (int i = 0; i < roles.Length; i++) {
  12:                 roleArray[i] = roles[i].Name;
  13:             }
  14:             return roleArray;
  15:         }

Now, to use the newly created MyRoleProvider I have to enable and configure the RoleManager in the web.config. Here is how

   1: <roleManager enabled="true" defaultProvider="MyRoleProvider">
   2:    <providers>
   3:       <clear/>
   4:       <add name="MyRoleProvider" type="Afeef.Configuration.Providers.MyRoleProvider"/>
   5:    </providers>
   6: </roleManager>

I next need to add security to my application through authorization section in the web.config file.

   1: <authorization>        
   2:    <deny roles="Guest"/>
   3:    <allow roles="Administrator"/>
   4: </authorization>

Now only users with role of Administrator can view the pages in this application. Whenever a user tries to visit one of the pages in the application, the GetRolesForUser() method is called in our MyRoleProvider class to determine whether the user is in Administrator Role. If he is, the page is served. If not, a security exception is thrown, not allowing the page to be viewed.

This is it, you’re done!

Share this post :

March 12

How to create a simple Stack data structure using C++

Download the complete source code for this example

Stack is a FIFO (First in, First out) structure. In which the first item that comes in, leaves the stack in last. I’ll use the Node class from the  Linked List data structure created in an earlier post with some modifications. The modified Node class any object through the use of C++ templates. The Node class exposes getters and setters for the object it will hold and the pointer to the next node (the node right below this node in the stack).

   1: #include "Node.h"
   2:  
   3:     Node::Node(void){
   4:     }
   5:  
   6:     Node::~Node(void){
   7:     }
   8:     int   Node::get() { 
   9:         return   object; 
  10:     }
  11:  
  12:     void   Node::set(int   object) { 
  13:         this->object   =   object; 
  14:     }
  15:  
  16:     Node   * Node::getNext() { 
  17:         return   nextNode; 
  18:     }
  19:  
  20:     void   Node::setNext(Node   * nextNode) { 
  21:         this->nextNode   =   nextNode; 
  22:     }

The Stack class is

   1: template <class T>
   2: class Stack {
   3:      public:
   4:         Stack(void);
   5:         ~Stack(void);
   6:         int empty(void);         
   7:         int push(T &);             
   8:         T pop(void);
   9:         T peek(void);
  10:     private:
  11:         int top;
  12:         T* nodes;
  13: }; 

and the implementation of the class is

   1: #include <iostream>
   2: #include <stdlib.h>
   3: #include "Stack.h"
   4:  
   5: #define MAXSTACKSIZE 50
   6:  
   7: using namespace std;
   8: template <class T>
   9: Stack<T>::Stack(void){
  10:     this->top = -1;
  11:     this->nodes = new T[MAXSTACKSIZE];
  12: }
  13:  
  14: template <class T>
  15: Stack<T>::~Stack(void){
  16:     delete this->nodes;
  17: }
  18:  
  19: template <class T>
  20: int Stack<T>::empty(){
  21:     
  22:     if(this->top < 0)
  23:         return 1;
  24:     return 0;
  25: }
  26:  
  27: template <class T>
  28: int Stack<T>::push(T & x){
  29:     
  30:     if(this->top < MAXSTACKSIZE){
  31:         
  32:         this->nodes[++this->top] = x;
  33:         return 1;
  34:     }
  35:     cout << "stack overflow in push. \n" << endl;
  36:     return 0;
  37: }
  38:  
  39: template <class T>
  40: T Stack<T>::pop(){
  41:     
  42:     T x;
  43:     if(!this->empty()){
  44:     
  45:         x = this->nodes[this->top--];
  46:         return x;
  47:     }
  48:     cout << "stack underflow in pop.\n" << endl;
  49:     return x;
  50: }
  51:  
  52: template <class T>
  53: T Stack<T>::peek(){
  54:  
  55:     T x;
  56:     return x;
  57: }

there are two main methods namely push and pop. push() as the name implies pushes the the Object passed as parameter onto the stack. And the second method pop(), pops up the object at the top of the stack.

Now to test the Stack by creating a main method. Creating to Stacks. First one to hold integers and second for characters types. Push some elements onto the stacks. Then output them by popping off the stack

   1: #include <iostream>
   2: #include <stdlib.h>
   3: #include "Stack.h"
   4: #include "Stack.cpp"
   5:  
   6: using namespace std;
   7:  
   8: int main (int argc, char *argv[]){
   9:     
  10:     Stack<int> intStack;
  11:     Stack<char> charStack;
  12:  
  13:     int x = 10, y = 20;
  14:     char c = 'C', d = 'D';
  15:  
  16:     intStack.push(x);
  17:     intStack.push(y);
  18:  
  19:     cout << "intStack: " << intStack.pop() << ", " << intStack.pop() << endl;
  20:  
  21:     charStack.push(c);
  22:     charStack.push(d);
  23:  
  24:     cout << "charStack: " << charStack.pop() << ", " << charStack.pop() << endl;
  25:     return 0;
  26: }

 

Happy Programming…!!!

Share this post :
 

Afeef Ahmad Janjua

Occupation
Location
Interests
I've done BS CS from VU. I've plans of doing MBA first (from VU again i don't believe i've just said that ... daahhhh) and then MS CS (from ... aaahhhh ... i don't know). Currenty i'm doing a job as a Software Engineer in Accountancy Outsourcing Services (AOS) Lahore