Afeef さんのプロフィールAfeef Ahmed Janjuaフォトブログリストその他 ツール ヘルプ
5月9日

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 :
5月1日

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 :
3月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 :

3月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 :
3月4日

Creating a simple Linked List Data Structure using C++ – Part I

In this post i am going to show you how to implement a simple Linked List data structure in C++ using Visual Studio 2008. However, you can use your favorite IDE to build this example.

In simplistic view Linked List is a collection of individual List Nodes interconnected with each Node pointing to the Node ahead of it. So to get us started, we need List Nodes first and then we’ll build Linked List data structure using those.

Fire up your favorite IDE and create a new project and add a header file named Node.h. This header file contains the interface of the Node class. Following is the code for this header file.

   1: #pragma once
   2:  
   3: class Node
   4: {
   5:     public:
   6:         Node(void);
   7:         ~Node(void);
   8:  
   9:         int   get();
  10:         void   set(int   object);
  11:  
  12:         Node   * getNext();
  13:         void   setNext(Node   * nextNode);
  14:  
  15:     private:
  16:         int   object;
  17:         Node   * nextNode;
  18: };    

In the code snippet above, first data member is an integer type that will hold the node value and the second data member is a pointer to the next node in the list (Null if this is the last node in the list). Getter and Setter methods for the data members are also defined.

Now create a new class and name it Node.cpp. This will implement the interface defined in the Node.h header file. Following is the code for the Node.cpp.

   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:     }

To create a linked list of Nodes we have to create a List class. For that create a new header file named List.h and copy the following code snippet into it. Include the Node.h header file created earlier.

   1: #pragma once
   2: #include "Node.h"
   3: class List
   4: {
   5:     public:
   6:         List(void);
   7:         ~List(void);
   8:         void   add (int   addObject);
   9:         int    get();
  10:         bool   next();
  11:         friend void  traverse(List list);
  12:         friend List   addNodes();
  13:         void start();
  14:         void remove();
  15:         int length();
  16:  
  17:     private:
  18:         int      size;
  19:         Node *   headNode;
  20:         Node *   currentNode;
  21:         Node *   lastCurrentNode;
  22: };

In this code snippet there is one data member named size. It will hold the current size of the linked list. A part from that three Node pointer are declared pointing to the Head Node, Current Node and the Last Current Node as their names suggest. Two friend functions are declared namely traverse() and addnodes().

Share this post :

Creating a simple Linked List Data Structure using C++ – Part II

Implement the List class interface by creating a new file named List.cpp. Add the following code to the newly created file.

   1: #include "List.h"
   2: #include <iostream>
   3:  
   4: using namespace std;
   5: List::List(void){
   6:     headNode   =   new Node();
   7:     headNode->setNext(0);
   8:     currentNode   =   0;
   9:     lastCurrentNode  =   0;
  10:     size   =   0;
  11: }
  12:  
  13: List::~List(void)
  14: {
  15: }
  16:  
  17: void   List::add (int  addObject) 
  18: {
  19:     Node *   newNode   =   new   Node();
  20:     newNode->set(addObject);
  21:     if( currentNode   !=   0 )
  22:     {
  23:         newNode->setNext(currentNode->getNext());
  24:         currentNode->setNext( newNode );
  25:         lastCurrentNode   =   currentNode;
  26:         currentNode   =   newNode;
  27:     }
  28:      else
  29:     {
  30:  
  31:         newNode->setNext(0);
  32:         headNode->setNext(newNode);
  33:         lastCurrentNode   =   headNode;
  34:         currentNode   =   newNode;
  35:     }
  36:     size ++;
  37: }
  38:  
  39: /* get() class method */
  40: int   List::get() 
  41: { 
  42:     if (currentNode  !=  0) 
  43:      return   currentNode->get(); 
  44: }
  45:  
  46: /* next() class method */
  47: bool   List::next() 
  48: {
  49:     if (currentNode  ==  0)   
  50:         return  false;
  51:  
  52:     lastCurrentNode  =  currentNode;
  53:     currentNode  =  currentNode->getNext();
  54:     if (currentNode == 0 || size == 0) 
  55:         return  false;
  56:     else
  57:         return  true;
  58: }
  59:  
  60: /* Friend function to traverse linked list */
  61: void traverse(List list)
  62: {
  63:     Node* savedCurrentNode  =  list.currentNode;
  64:     list.currentNode  =  list.headNode;
  65:     
  66:     for(int i = 1; list.next(); i++)
  67:     {
  68:         cout << "\n Element " << i << "   " << list.get();
  69:     }
  70:     list.currentNode  =  savedCurrentNode;
  71: }
  72:  
  73: /* Friend function to add Nodes into the list */ 
  74: List addNodes()
  75: {
  76:     List   list;
  77:     list.add(2);
  78:     list.add(6);
  79:     list.add(8); 
  80:     list.add(7);   
  81:     list.add(1);
  82:     cout  <<  "\n List size = "  <<  list.size  <<'\n';         
  83:     return  list;
  84: }
  85:  
  86: void List::start() {
  87:     lastCurrentNode = headNode;
  88:     currentNode = headNode;
  89: }
  90:  
  91: void List::remove() {
  92:      if( currentNode != NULL && currentNode != headNode) {
  93:          lastCurrentNode->setNext(currentNode->getNext());
  94:          delete currentNode;
  95:          currentNode = lastCurrentNode->getNext();
  96:          size--;
  97:      }
  98: }
  99:  
 100: int List::length() 
 101: { 
 102:     return size; 
 103: }

The traverse() friend function traverses the list from start to finish and output the elements contained in the list. The addnodes() friend fuction adds the Nodes to the List. the start() method sets the currentNode pointer to the start of the List. remove() method removes the currentNode from the list. The length() method returns the current size of the Linked list.

Create a main.cpp file to test the Linked List data structure we have created.

   1: #include<iostream>
   2: #include "List.h"
   3:  
   4: using namespace std;
   5:  
   6: int main(){
   7:  
   8:     List list;  // creating a list object
   9:     
  10:     // adding values to the list
  11:     list.add(5); 
  12:     list.add(13); 
  13:     list.add(4);
  14:     list.add(8); 
  15:     list.add(24); 
  16:     list.add(48); 
  17:     list.add(12);
  18:  
  19:     // calling the start method of the list
  20:     list.start();
  21:  
  22:     // printing all the elements of the list
  23:     while (list.next()) 
  24:         cout << "List Element: "<< list.get()<<endl;
  25:  
  26:     return 0;
  27:  
  28: }

Happy programming …!!!

12月28日

IT430 e-commerce

During the course of the last two days, I have designed simple templates using XHTML/CSS for the MBA students of my university. The URLs of the hosted templates are listed here but in no particular order

  1. bc060400493.freehostia.com
  2. bc070200254.freehostia.com
  3. bc070200417.freehostia.com
  4. bc070200654.freehostia.com
  5. mc070404441.freehostia.com
  6. mc070404015.freehostia.com

I have not hosted the remaining two templates my self so i don’t know their URLs at the moment. The hosting provider VU mentioned in the docs were not ad free so I have hosted these to the “www.freehostia.com” hosting provider, which is ad free hosting service.

Share this post :
12月10日

How to install and debug Apache, MySql and PHP applications using NetBeans 6.5 on Ubuntu 8.10 desktop

I have recently downloaded the newly released ubuntu 8.10 desktop and I was curious about how to do php development in it using NetBeans 6.5. I've used netbeans before but am new to php. The setup steps that are required for installation of AMP and Netbeans are stated below. I will finish this post with debugging a "hello world" php script using Netbeans. If you are interested in how to setup Netbeans along with AMP (apache, php and mysql) on the newly released Ubuntu 8.10 Desktop, follow along

First of all,

1. Open the terminal and type

sudo bash

If you don't know how to open it, do this

Applications –> Accessories -> Terminal

2. Create a directory named Java under your home directory using the following command at the terminal

mkdir Java

This is the directory where all of the java software will be downloaded and installed

3. Download the latest release of Java SE Development Kit (JDK) for ubuntu linux from http://java.sun.com/javase/downloads/

4. Download the latest release of NetBeans IDE bundled with php technology support from here http://www.netbeans.org/downloads/index.html

I have downloaded the NetBeans IDE with support for all the supported technologies and will follow that in this blog. Also, the versions of jdk and netbeans i’ve used are

jdk-6u11-linux-i586.bin

netbeans-6.5-ml-linux.sh

be sure to replace these with your own downloaded filenames

5. Back at the terminal type the following command

cd Java

6. Install the jdk

./jdk-6u11-linux-i586.bin

Or

sudo ./jdk-6u11-linux-i586.bin

7. type 'yes' to accept the license agreement and start the installation

you should now see a folder named jdk1.6.0_11 under your the Java directory

8. To install netbeans type

./netbeans-6.5-ml-linux.sh –javahome ~/Java/jdk1.6.0_11

The '—javahome' command line argument tells the installer where jdk is installed. If you've already setup the '—javahome' environment variable you don't have to mention that here

Now netbeans installer GUI will appear on the desktop

9. Click the customize button and select the technologies to install and click next

Screenshot1

10. Accept the license agreement and click next

11. Install the Netbeans IDE 6.5, Glassfish V2 UR2, Glassfish v3 Prelude and Apache Tomcal 6.0.18 in the Java directory

Screenshot7

12. Finish the installation

13. Install Apache web server

apt-get install apache2

14. Install MySQL server
apt-get install mysql-server
After the installation type a password for 'root'.

15.Install PHP runtime
apt-get install php5

16.Install MySQL extension for PHP
apt-get install php5-mysql

17. Install 'xDebug' debugging extension for PHP runtime.
apt-get install php5-xdebug

18. Setup the Apache web server to use PHP runtime for web sites
Now the apache web server must be running. Type http://localhost/ in Firefox's address bar you should see "it works!" page.

Screenshot10

19. But when you try to access websites that are located in your home folder it displays the "404 not found" page as shown in the picture. Replace 'afeef' with your username.

Screenshot11

20. For this to work you have to tell the apache web server to enable the user module

a2enmod userdir

21. Create a directory named 'public_html' in your home directory
mkdir public_html

22. Restart Apache web server
/etc/init.d/apache2 restart
Click refresh on Firefox you should see the directory listing if you've done it correctly.

Screenshot12

23. Now create a file 'Default.php' under the 'public_html' directory

24. Open 'Default.php' and write following line in it and save the file

<?php phpinfo(); ?>

Again hit refresh on firefox and u should see the following

Screenshot13

25. To enable remote debugging for 'php' in 'xdebug' type

gedit /etc/php5/conf.d/xdebug.ini

Or

sudo gedit /etc/php5/conf.d/xdebug.ini

26. Add the following line at the end of the file and save

xdebug.remote_enable=on

hit refresh on firefox to see the result immediately

Screenshot15

27. Restart the apache web server

/etc/init.d/apache2 restart

28. Start netbeans and Create a new project, select php application and click next

Screenshot16

29. Name the project and in the sources folder select the 'public_html' directory (the IDE should do it for you). Click next

Screenshot17

30. Accept the default run configuration and click finish

Screenshot18

31. Add the line 'echo "hello world";' in the php tags of the newly opened 'index.php' file. Set a breakpoint at this line

32. Right click the project name in the projects pane and select debut from the context menu

Screenshot26

33. At the debut 'project dialog' choose debugging options and click debug

Screenshot19

34. The IDE will ask for an add-on, click on to install the extension

Screenshot20

35. You'll see the following window in browser

Screenshot22

36. Back in the IDE you'll see that the debugger is attached. Step through the breakpoint

Screenshot24

37. In the browser you'll see the output

Screenshot25

That's all. You're done!

Share this post :