Multiple Inner Joins using LINQ and Entity Framework 4.0

Suppose you have the following query that you want to create in LINQ using entity framework

SELECT  dbo.Activities.title, dbo.ActivityLogging.activityTime, 
        dbo.Users.userName
FROM dbo.Activities
INNER JOIN  dbo.ActivityLogging
ON dbo.Activities.id = dbo.ActivityLogging.activityId
INNER JOIN dbo.Users
ON dbo.ActivityLogging.userId = dbo.Users.id

This is the result

public IList<ActivityLog> Read () {
    var db = new YourEntities();

    var users = from a in db.Activities
            join al in db.ActivityLoggings on a.id equals al.Activity.id
            join u in db.Users on al.userId equals u.id
            select new ActivityLog
            {
                Title = a.title ,
                ActivityTime = al.activityTime ,
                UserName = u.userName
            };
 return users.ToList ();
}

Reverse Geo-coding the Address using Latitude and Longitude in ASP.NET using Google Geo-coder Kit

Download the google geocoder kit from here. Extract the archive on your hard drive. Create a folder named Geocoding in your App_Code folder and import all the Classes from the downloaded archive. Add a reference to the Newtonsoft.Json.dll assembly which is a dependency and can be downloaded from here. Create two textboxes on your page such as in this example

  1. longitude
  2. latitude

Now using the Geocoder class find the street address using reverse geocoding

var coder = new Geocoder();
    if (longitude != null && lattitude != null)
    {
        var info = new SpotInfo() {
              LatLng = new SpotLatLng(Convert.ToDouble(longitude.Text),
             Convert.ToDouble(lattitude.Text))
    };
    var result = coder.GetGeoResult(info, "json");

    if (GeoResultStatus.OK.Equals(result.Status))
    {
        foreach(var item in result.Results)
        {
            Response.Write(item.FormattedAddress + "<br>");
        }
    }
}

Extension method to replace multiple spaces with single space from a string of characters

A few days back I wrote this handy extension method for replacing multiple spaces with single space from a string of characters. Here is the code

public static string ToSingleSpaceString( this string value ) {

       const RegexOptions options = RegexOptions.None;
       Regex regex = new Regex( @"[ ]{2,}", options );

       return regex.Replace( value, @" " );
 }

Usage:

string output = somestring.ToSingleSpaceString();

Setting Sun’s Java as default java on openSUSE 11.2

This post is more of my personal reference for future. I downloaded and install the 32 bit rpm.bin file from Java SE downloads page. But the openSUSE 11.2 was showing the openJDK as the default java. So i put the following commands on the terminal to set the sun’s java as default one.

the following line will install sun’s java as second alternative

update-alternatives –install /usr/bin/java java /usr/java/jdk1.6.0_17/bin/java 2

then you can list down all the alternatives using the following line

update-alternatives –config java

following is the output of the above line

  Selection    Alternative
———————————————–
*+        1    /usr/lib/jvm/jre-1.6.0-openjdk/bin/java
          2    /usr/java/jdk1.6.0_17/bin/java

Press enter to keep the default[*], or type selection number: 2
Using ‘/usr/java/jdk1.6.0_17/bin/java’ to provide ‘java’.

i provided the number 2 and now it’s using the sun’s java as the default one.

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 SomeMethod()
   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: }

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

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