Sunday, March 31, 2013

Nhibernate Subquery using criteria API

If you ever worked with relational databases then higher chances are you already worked with sub queries. Some time while working with Nhibernate you get yourself into some situation where you need sub query to do some lifting for you. In NHibernate criteria API you can do the sub query using DetachedCriteria and Subqueries classes. As the name suggests DetachedCriteria helps you define your sub query criteria while Subqueries class help you create sub query criterion object using detached criteria object.

In order to demonstrate sub query implementation lets consider an example. Suppose we have three entities Order, OrderItem and Product where one order can more have more then one order items while one order item may be linked to a product. If we need to do a query where we need to list all those order items which are linked to products and have price greater then $100. Also the products must be the ones marked as special in system. The SQL for such query may be something like below

SELECT * FROM OrderItem AS OI 
WHERE OI.Price > 100 AND OI.ProductId IN ( SELECT P.ProductId FROM Product WHERE P.IsSpecial = 1 )

The same can be achieved by using NHibernate criteria API with the use of Subqueries and DetachedCriteria class. Above query can translated to follwoing NHibernate criteria query


ICriteria criteria = session.CreateCriteria<OrderItem>("OI")
                .Add(Restrictions.Gt("OI.Price", 100));

DetachedCriteria subQuery = DetachedCriteria.For<Product>("P")
                .Add(Restrictions.Eq("P.IsSpecial", true));

var items = criteria.Add(Subqueries.PropertyIn("OI.ProductId", subQuery))
                .List<OrderItem>();

That's it!

Tuesday, December 4, 2012

Extension methods and NVelocity

Recently I was asked to look into an interesting issue which we faced while we were improving our application. We were using NVelocity for formatting needs in our web application over last several years. I expect that you are already familiar with NVelocity but in case you'r not NVelocity  is ported version of Velocity for .NET. You can read more about it from Castle Project.

In our application written in ASP.NET(C#), we were using Active Record pattern so many business related behaviours were on same objects. It means if we have an object in NVelocity context we were able to call the methods through NVelocity directly on object. Some of these methods were on our collection objects which were specialized for each domain object. For example if we have an entity class OrderItem then we also have OrderItemCollection which provides strongly typed access on OrderItem objects. So we have certain utility method specific to such strongly typed collections right inside the collection objects for example in order to calculate the Total amount of all order items we may have a Total() method right inside OrderItemCollection. So far so good this was all working really good when formatting Emails through NVelocity. For instance NVelocity was able to understand , execute and print output for following code.

$order.Items.Total()

Now while we were improving the things we switched from specialized strongly typed collections to IList due to some requirements. Ideally we wanted to keep the API similar to the old one so best pick was to move the methods from specialized collections to IList extensions. This is where we broke the Emails. NVelocity had no clue of extension methods so calls like $order.Items.Total() were printing the same piece of code instead of calculated values. I been asked to figure out if there is any easy way out where ideally we would like to keep things similar to the old days. After doing some Google searches I figured out one possibility and that is the IDuck interface in NVelocity. This interface allows you to intercept the member calls on object implementing IDuck interface and gives your code a chance to locate and execute member method or property and return the output. Now in our case I have to make sure that we are able to handle following two cases
  • We can call any extension method from NVelocity context. This is more important for the cases where we have extensions defined on system types like decimal etc.
  • We can call extension methods on our generic collections like the old days for example $order.Items.Total()
In order to intercept extension methods calls I created a helper class that can intercept and translate extension methods by using nvelocity's IDuck interface.  IDuck interface requires you to implement following three members
  1. object GetInvoke(string propName) :- When implemented this will correspond to property getter and will be called when reading value from property.
  2. object Invoke(string method, params object[] args) :- When implemented this will be called against any method call in NVelocity context.
  3. void SetInvoke(string propName, object value):- When implemented this will correspond to property setter and will be called when setting value on a property within NVelocity context.

As its clear from above method signatures that in order to implement these methods one will be needing to use reflection to find and execute methods on corresponding classes so most of helper class was doing reflection. The process was like first load all extension classes, then when helper class gets the invoke call we need to find member method on available extension classes and finally if we found a match we invoke method by passing it input parameters passed by nvelocity.

This solved the first case where we needed the ability to call extension methods on system types like decimal. In order to do that all we needed was to add one more parameter to nvelocity context of type NVelocityHelper and then use that parameter to call extension methods on system types as below.

$helper.MyExtensionMethod(price)

This call will simply give NVelocityHelper class a chance to find MyExtensionMethod on available extension classes and if found it will execute and return the results.

The second part was more important where we needed to mend our broken nvelocity calls which we had on custom collection in past but now are extension methods. The only option to handle this case was to first extend generic List class into our custom generic list class let's say ExList and then by implementing the IDuck interface on it. This gave our custom generic list a chance to intercept the calls from nvelocity context on our collections which then we mapped to extension methods by using codes written in NVelocityHelper.

The solution was really amazing and handy. We were able to retain our existing Email formatting codes written around nvelocity while using extension methods instead of custom strongly typed collections. Hopefully this post may help some one else looking for something along the same lines.

Saturday, July 30, 2011

Exploring NHibernate Projections and Transformers

Its been a month since I am actively working with NHibernate queries using criteria API. Initially it was taking me long because I wasn't aware of many things but now I has started to prove its worth. I can feel that now I am more comfortable with NHibernate. As an attempt to preserve some of our legacy codes that contains SQL for reporting purposes I had an experience of writing some naughty queries around ICriteria API. During this porting work I was into a lot of NHibernate projections and Transformers.

In criteria API projections help you do the aggregation and grouping. For example if you need to do COUNT(), SUM(), AVG(), GROUP BY then you are going make use of Projections. They key to make use of projections in criteria API is SetProjection() method of ICriteria. Let's get to our first code example making use of Projections and see how it works. Suppose we have table called Product and we want to find number of products where product name contains word 'free' through criteria API. If we do it via standard SQL then our SQL is going to be something like this
SELECT COUNT(*)
FROM Product AS P
WHERE P.Name LIKE '%free%'
and with Nhibernate criteria API it will be
int count = NHibernateHelper.CreateCriteria<Product>("P")
            .Add(Restrictions.Like("P.Name", "free", MatchMode.Anywhere))
            .SetProjection(Projections.RowCount())
            .UniqueResult<int>();
If we look at the code what we have done is we used NHibernate fluent coding style to create a criteria object for Product entity. Then we added a restriction for name and finally for set the projection for RowCount. As the result of this query is going to be scaler value of integer type so we executed the query using UniqueResult generic method by asking to return us the scaler value as integer value.

So far we discussed very simple case of projection where we were needing number or rows. In real word queries are more complicated most of time then just having number of rows :). So before we go and discuss some complex cases of projections we need to have an idea of Nhibernate Transformers.

Probably you can understand from the name that they have to  do something with transforming stuff from one shape to another. Yes you are right transformers helps you transform the results. In order to set a transformer you need to make use SetResultTransformer() method of criteria API. For example let's say we have two table called Product and OrderItem where one product can belong to many order items. Suppose we need to get all distinct products that's been sold. The SQL to this going to be something like
SELECT DISTINCT P.*
FROM Product P JOIN OrderItems AS OI 
ON P.ProductId = OI.ProductId
Now we in order to do this with NHibernate criteria API we are going to make use of a Transformer to get distinct product objects.
IList products = NHibernateHelper.CreateCriteria<Product>("P")
                .CreateCriteria("P.OrderItems", "OI", NHibernate.SqlCommand.JoinType.InnerJoin)
                .SetResultTransformer(new NHibernate.Transform.DistinctRootEntityResultTransformer())
                .List<Product>();
In above code the line SetResultTransformer(new NHibernate.Transform.DistinctRootEntityResultTransformer()) is setting transformer on criteria object that will make sure to emit list of unique products.

Now that you have an idea of transformers we need to look at another and most probably the one that you are going to use a lot with projections is AliasToBeanResultTransformer. This is very powerful transformer and it lets you map your custom objects in NHibernate criteria API queries. For example you may came accross a situation where you will be needing a custom column set instead of just complete NHibernate entity object. You may find yourself in such situation quite often while doing reporting related stuff. For example let's say we need to do a report on our Order table where we have another table called Customer and one customer can have many orders. Suppose we want to find total number and amount of sales for every customer. The standard SQL to this is going to be something like this
SELECT COUNT(*)AS NumberOfSales, SUM(Charges) AS TotalSales, CustomerId AS CustomerId
FROM Order
GROUP BY CustomerId
Now when writing the corresponding NHibernate criteria query the challenge that we have is we got custom columns select clause. NHibernate doesn't allows to load unmapped data and in this case we have unmapped custom columns not NHibernate entities. So in order to get this done we are going to ask our new best friend AliasToBeanResultTransformer to help us out. So in order to use this transformer the first thing that we need to do is to create our custom wrapper class to hold the data. Its going to be something like
  public class SalesData 
        {
            public int NumberOfSales { get; set; }
            public decimal TotalSales { get; set; }
            public int CustomerId { get; set; }
        }
Now our Nhibernate query is going to be something like
IList<SalesData> sales = NHibernateHelper.CreateCriteria<Order>()
                .SetProjection(Projections.ProjectionList().Add(Projections.RowCount(), "NumberOfSales")
                .Add(Projections.Sum("Charges"), "TotalSales")
                .Add(Projections.Property("CustomerId"), "CustomerId")
                .Add(Projections.GroupProperty("CustomerId")))
                .SetResultTransformer(Transformers.AliasToBean(typeof(SalesData)))
                .List<SalesData>();
In above code the first thing that you will notice is Projections.ProjectionList(). ProjectionList let's you add multiple projections as in our case we need four projections. The next thing that you will notice will be Transformers.AliasToBean(typeof(SalesData)) where Transformers.AliasToBean is a quick way to get an instance of under lying AliasToBeanResultTransformer and secondly we are passing type of custom SalesData class. That's it. When executed this query will return list of SalesData objects filled with data from your custom unmapped columns.

Now that you have an idea of projections and transformers you will see that you will be able to do very complex reporting queries with these both awesome features of NHibernate criteria API.

Tuesday, June 21, 2011

NHibernate and select one column only

You can make use of Projections when it comes to selecting from specific columns. For example sometime you may need to select values only from Id column instead of loading complete matching rows.

Lets quickly take a look at an example. Suppose we have a table called Customer with columns Id, FirstName, LastName, Street, City, PostalCode, Country. Now when doing our query we only want to select all Ids less then value 10. We can accomplish this by doing something like this

IList<int> customerIds = session.CreateCriteria<Customer>()
                .Add(Restrictions.Lt("Id", 10))
                .SetProjection(Projections.Property("Id"))
                .List<int>();

Monday, June 20, 2011

Select by foreign key and NHibernate

Recently I  came across NHibernate. We were thinking to replace our home grown persistence code generator with an ORM. We had two options either Nhibernate or Entity Framework. After evaluating these two awesome frameworks we picked NHibernate.


So far we were using our custom written code generator which was emitting code modeled around Active Record pattern. During the development you will find yourself in a situation quite often where you will be needing to load some objects by some foreign key. This will be the case in many-to-one relation. For example load all products belonging to category with Id equal to 4. This is very easy when you are writing your custom query for example in our case before NHibernate we used to write text query. Then execute it as datareader, iterate over reader to create objects. Finally return collection of all  objects.


Now when defining NHibernate mappings you will map your foreign key columns to properties returning object/objects of that related entity instead of just an id value. The reason behind this is that Nhibernate wants to make sure that when you are relating to some object then that object must exist in database.


Anyway if you are reading this topic I am quite sure you are already aware of the case and are looking for solution. So let say we are making use of Northwind Database where we have two tables called Categories and Products. One category can have many products. We want to list all products belonging to category with id equal to 4. Here is how I managed to do it with Nhibernate.

 IList<Products> products = session.CreateCriteria<Products>("P")  
           .CreateCriteria("Category", "C", NHibernate.SqlCommand.JoinType.InnerJoin)  
           .Add(Restrictions.Eq("C.Id", 4))  
           .List<Products>();  
Here is the SQL generated by NHibernate
NHibernate: SELECT this_.ProductID as ProductID6_1_, this_.Discontinued as Disconti2_6_1_
, this_.ProductName as ProductN3_6_1_, this_.QuantityPerUnit as Quantity4_6_1_
, this_.ReorderLevel as ReorderL5_6_1_, this_.UnitPrice as UnitPrice6_1_
, this_.UnitsInStock as UnitsInS7_6_1_, this_.UnitsOnOrder as UnitsOnO8_6_1_
, this_.CategoryID as CategoryID6_1_, this_.SupplierID as SupplierID6_1_
, c1_.CategoryID as CategoryID10_0_, c1_.CategoryName as Category2_10_0_
, c1_.Description as Descript3_10_0_, c1_.Picture as Picture10_0_ 
FROM Products this_ inner join Categories c1_ on this_.CategoryID=c1_.CategoryID 
WHERE c1_.CategoryID = @p0;@p0 = 4

Friday, November 26, 2010

My few weeks in freelance coding

Its been a while since I posted anything to my blog. In recent months I had some experience of doing some freelancing at vworker.com formally known as rentacoder.com. So I thought may be it would be good to blog about this experience that possibly might help some one else. Although I done this for a short period of time, almost a month and moreover I worked only on weekends. But it was quite nice. I learned a lot about freelancing for example how to bid, how to communicate with people and keep them in touch. I was able to earn reasonable money for few days that I spent with vworker.com. So here are few things that I want to share. I am going to place these points in question and answer fashion.

1- Do I need to spend any money before I can go start looking for work on vworker.com?
No, signup is totally free and you don't need to spend anything in order to get your self an account. vworker.com will charge you from earnings that you will make at vworker. At the time when I worked with them they were charging 15% of what ever your quote is.

2- How do I collect payments from vworker.com?
Well they offer many methods which you can use in order to collect your payments. If you have PayPal account then its best because by default they charge you for PayPal. If you choose any other payment method then you may have to pay some extra charges. For example I used Western Union. The charges they mentioned for it was $10 USD but when I received the payment they turned to be around $20 USD. This was kind of thing I didn't liked :(. They provide you options to configure certain amount limit after which you want your earnings to be dispatched to you. So provided that if there are any charges involved for your payment method, choose this limit wisely because if its is too low then you have to pay more for payment charges.

3- How do I setup my profile?
You have to fill in your details in your profile, I mean your professional details like your work experience, any reference links etc. In my personal opinion try to be domain specific, I mean don't try to show that you are jack of all. For example if you are web developer having major work experience in ASP.NET then stay with it and don't try to put every other technology that you know in your profile. I believe customers do prefer experts of jack of all. Don't forget to put reference links for your previous work in your profile if you have any. That increases clients trust in your abilities.

4- How to get good rankings?
First of all go through posted projects and figure out projects that meets your work domain. Then initially try to pick the small projects. The reason is in small projects normally budgets tends to be low so there are higher chances that you can get the project without having no or low rankings due to sensation of low risk for employer. Secondly in small projects work boundaries are well defined so you will always certain about how to approach the work. This lowers the risk of getting stuck into the work. You will reach the deadline in time and hopefully get good rankings.

5- What is the best way to bid?
Try to understand work requirements by reading work details. Figure out all possible things that needs to be fixed and your approach to cater them. Then go and place your detailed bid/reply to employer. Don't hesitate to reformulate the things and be descriptive for example tell him that you understand what he is looking for, what will be your approach and what will be work output. Make employer feel that you are interested in his/her work. Don't get embraced with bid counter showing a lot of bids placed, most of them are placed by sales guys or bots with canned messages like we are blah blah company and we can do this etc. So if you placed reasonable comment, it will make difference and you will get employer's response :). Lastly if you are not sure about any thing don't place bid, instead send employer a private message querying about the points you are not clear.

6- How much I should quote for work?
Try to be fair. You may see maximum budget associated with work, but sometime that may not be correct. For example normally employers are not technical persons and are not aware of the work complexities. So sometime they are asking for something that is either too low or too high. In any case measure the work and get a fair estimate according to work.

7- Do I need to keep my employer updated with progress?
Yes, that is very important thing to do. Your employer is not sitting next to you. He doesn't know what's happening on your side. So if he sees long delays in response he may get nervous and can create some trouble for you. The best way is too post about your progress when ever you are about to close you work session. This will make your employer keep faith in your abilities and he will be confident that you are making progress in his project.

8- How much work I should try to take?
Don't get yourself overwhelmed with lot of work. This can make you fail to achieve deadlines for some projects which can I turn cost you as a cut in your rankings or loss of work. In either way that is not a good thing. Try to get amount of work that you can deliver in time.

9- What is the best way to communicate with client, through vworker.com or too take him out and talk in private?
Well there are different opinions and it really depends upon how you are comfortable. If you stay within vworker.com then there are some advantages for example your employer can't runaway. If you have any dispute with your employer then vworker.com representative can go through your communication log to resolve the conflict. So if there is no other intension involved like to take work from employer in private to save extra charges then using vworker.com for communication is better option.
Secondly if you are always grabbing the work through vworker.com then it means you are getting more and more success stories on your profile plus rankings. Lastly if you want to take employer out of vworker.com then you can do communication using allowed private messengers.

This is how I saw the things, its not necessary that every one of you agree with me. So if you have something to add feel free to place comment and share your thoughts. I welcome your thoughts and suggestions.

Tuesday, June 30, 2009

Find GEO location through IP address

Geo IP Tool is a free service that helps you find geographical location via IP. I was trying to find out some service through which I can found the GEO information of customers via IP address. Below is a small helper code that can query Geo IP Tool against an IP. All you need is to place following helper class some where in your website. As you can see helper class only contains a single method GetLocationByIp of return type string. In fact it returns HTML containing returned information from Geo Ip Tool. Once you get the Geo information against an IP, all you need is to put it some literal control to be rendered.

Here is the GeoIPTool class, you can place it in your App_Code folder of ASP.NET website. Once you are done with this change then you can use user control code posted in next code portion for demo purpose.

using System;

using System.Data;
using
System.Configuration;
using
System.Web;
using
System.Web.Security;
using
System.Web.UI;
using
System.Web.UI.HtmlControls;
using
System.Web.UI.WebControls;
using
System.Web.UI.WebControls.WebParts;
using
System.Net;
using
System.IO;

public static class GeoIPTool

{

public static string GetLocationByIP(string ipAddress)

{

string geoiptoolurl = "http://www.geoiptool.com/?IP={0}";

string gflag = "http://www.geoiptool.com/flags/";

string p1 = "<"+"table width=\"300\" height=\"300\"";

string p2 = " border=\"0\" cellpadding=\"4\"";

string p3 = " cellspacing=\"0\" class=\"tbl_style\">";

geoiptoolurl = string.Format(geoiptoolurl, ipAddress);

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(geoiptoolurl);

using (HttpWebResponse response = (HttpWebResponse)(request.GetResponse()))

{

using (StreamReader reader = new StreamReader(response.GetResponseStream()))

{

string htmlResult = reader.ReadToEnd();

if (!string.IsNullOrEmpty(htmlResult))

{

int sindex = htmlResult.IndexOf(p1+p2+p3);

htmlResult = htmlResult.Remove(0, sindex);

sindex = 0;

int eindex = htmlResult.IndexOf("");

string geoLocationTable = htmlResult.Substring(sindex, eindex + 8);

if (geoLocationTable.Contains("/flags/"))

geoLocationTable = geoLocationTable.Replace("/flags/",gflag);

return geoLocationTable;

}

}

}

return string.Empty;

}

}

Following is the demo user control, in order to use this code first you need to create a new user control file with name Sample.ascx in your website and then replace all its contents with following code. Finally replace Your IP Here text in GetLocationByIP call to your desired IP address.

<%@ Control Language="C#" ClassName="Sample" %>

<script runat="server">

protected void Page_Load(object sender, EventArgs e)

{

string geoLocation = GeoIPTool.GetLocationByIP("YOUR IP HERE");

if (!String.IsNullOrEmpty(geoLocation))

GeoLocationHolder.Controls.Add(new LiteralControl(geoLocation));

}

<asp:PlaceHolder ID="GeoLocationHolder" runat="server">asp:PlaceHolder>

Please feel free provide your feedback!

Jump to validation summary on large page

Validation summary is an awesome ASP.NET control that can list validation messages in a collective way. Some time if you have validation summary at bottom of a large page, in this case if some validation error occurs the user has to scroll down towards the bottom to view the pages.

You can enhance user experience with Validation Summary control by automatically jumping to the error messages area when some error occurred. I am just explaining the steps to accomplish this.

In ASP.NET there is a client side variable Page_IsValid that indicates whether the page is currently valid or not. The validation scripts keep this up to date at all times. So all you need is to wrap your validation summary within some div and place some anchor upon that. Finally write a small piece of javascript that checks Page_IsValid and if its set to false simply jump to that named anchor. You can found a very helpful topic about ASP.NET Validation available here

How to calculate column value as summation of all previouse values

This is the demonstration of how to calculate a column value that depends upon sum of all previous values in that column. For example check following two tables
Actual Data:
ProductIdNameQuantity
1Product A10
2Product B10
3Product C10
Required Output:
ProductIdNameCal Quantity
1Product A10
2Product B20
3Product C30

SQL Server Query:

SELECT P.ProductId, P.Name, SUM(PC.Quantity) AS Cal Quantity
FROM Products AS P LEFT OUTER JOIN Products AS PC
ON PC.ProductId <= P.ProductId
GROUP BY P.ProductId, P.Name

Wednesday, March 25, 2009

Free Java MIDlet Manager for Windows Mobile Phones

Some java applications need Java MIDlet Manger to run on your windows mobile devices. For example if you want to install and use Opera Mini, Gmail Client for windows mobiles then you need to have Java MIDlet Manager installed on your device. You can download a free MIDlet Manager avialable here.

Free JVM for Windows Mobile Phones

I was in need to run some java applications on my I-Mate JAM and was having a hard time locating a free or open source JVM for it. After a lot of searching and striking my head against walls finally I found an open source JVM and that is Mysaifu JVM. Its an open source JVM available for free. It doesn't contain any MIDlet Manager means you can not run some applications that require MIDlet Manger for example Opera Mini and Gmail client for mobile phones. But still it could be very helpfull running other java applications on your PDA.

1. How to install
  • Copy the CAB file to \My Documents.
  • Tap the CAB file. 
  • Program is installed under \Program Files\Mysaifu JVM folder.
2. How to uninstall
  • Select "Mysaifu JVM" in "Settings - Remove Programs".

Tuesday, March 24, 2009

How to build Bluetooth Remote Control for desktop machine

Some time ago I was searching for some .NET(CE) stuff and read about the concept of an application that could allow to turn your mobile into a remote control for your desktop machine. I was very impressed by the concept and tried to wrote something similar that could help me control Windows Media Player, PowerPoint slide show and some general windows operations like Logoff User, Shutdown and Restart, Volume Control etc. I am planing to post it with complete source code but currently it needs some finishing steps like removing some unused code and some miner UI improvements. Hopefully I will get some time in near future to get things done.

I developed it for my I-Mate JAM running .NET CE(2.0). Currently .NET does not have any explicit support for bluetooth like java where there is a seperate API (Java Bluetooth API). Microsoft recommends use of sockets for this purpose, using sockets would be really time consuming task because that is relativly a low level programming task so I searched for some open source Bluetooth API that targets microsoft .NET and finally descided to use 32feet.net API. Its an open source API for personal networking.

Hardware Requirements
  1. Develoment Machine capable of running Visual Studio 2005
  2. I-Mate JAM or equvalent PDA device that support Microsoft Bluetooth stack.
  3. Bluetooth dongle for desktop machine, make sure that dongle supports Microsoft Bluetooth stack.
  4. Data cable for PDA
Softwares Requirements
  1. Visual Studio 2005 Professional Edition
  2. .NET CE(2.0) on your PDA (You can install .NET(CE) on I-Mate JAM from here)
  3. Microsoft ActiveSync (You can get it from here)
  4. 32feet.net(InTheHand) API (You can get it from here)
Setting up development environment
  • Install Visual Studio 2005 on development machine
  • Install 32feet.net on development machine. If your hardware is not working with API then you can try following workarund.
  • Now install Microsoft ActiveSync on development machine as well.
  • Finally connect you PDA and machine with datacable and test the connection.
How to control Media Player remotly via Bluetooth
  • First create a Windows form applicaton that will work as server on desktop machine. This applicaton will work as a Bluetooth listner. In 32feet.net samples there is a Remote sample you can use it as guide line.
  • Next you need to find out command messages for Windows Media Player, You can use spy++ for this purpose. For example what is the command message sent against volume up command.
  • Next you need to use import some win32 functions in your C# application for locating the running instance of Winodws Media Player and pass it the command message to performs that action.
  • Finally map some keys that listner recieves via bluetooth and then raises apperoperiate command message for Windows Media Player.
  • Now create Device Application 2.0 for your PDA or you can use the client part of remote sample available with 32feet.net.
  • Once client applicaton is setup properly all you need is to send those keys to desktop machine for wich you define mapping on server component. Once server module will reieve a mapped key for example you have mapped 9 to volume up then it will raise volume up command message for Winodws Media Player and hence will stepup the volume.

Monday, July 21, 2008

Monday, July 14, 2008

Media Feeds for Piclens Plugin using .NET 2.0

About this post
This post is about the "MediaRSS" standard and how you can use it for your own website. If you have never heard of it - never mind. But maybe you have heard of a really cool Firefox Plugin called "PicLens".

"PicLens"?
"PicLens" is a incredible surface for some internet services, like YouTube, Google picture search, Flickr, Amazon, Deviant Art. Now you can have your favorite sites in Full-screen. 3D.

Media RSS
The Piclens guys have implemented the "MediaRSS" standard - that means: Each site with an MediaRSS can be viewed in Piclens.
If you are a webmaster, you should take a look at this site.

Bellow is the Media Feeds Example for ASP.NET 2.0 C# you can create a file with name
MediaRss.ashx on the root of your site and following line of code in the Head section of your pages.
Put a Link tag with href="MediaRss.ashx" type="application/rss+xml" id="gallery" and that's all

Bellow is the code of the MediaRss.ashx


<%@ WebHandler Language="C#" Class="MediaRss" %>
using System;
using System.Xml;
using System.IO;
using System.Web;

[System.Web.Services.WebService(Namespace = "http://tempuri.org/")]
[System.Web.Services.WebServiceBinding(ConformsTo = System.Web.Services.WsiProfiles.BasicProfile1_1)]
public class MediaRss : IHttpHandler {

string media = "http://search.yahoo.com/mrss";
string atom = "http://www.w3.org/2005/Atom";

public void ProcessRequest (HttpContext context)
{
XmlDocument xmlDocument = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", "yes");
xmlDocument.AppendChild(xmlDeclaration);

XmlElement rssElement = xmlDocument.CreateElement("rss");
rssElement.SetAttribute("version", "2.0");
rssElement.SetAttribute("xmlns:media",media);
rssElement.SetAttribute("xmlns:atom", atom);
xmlDocument.AppendChild(rssElement);

XmlElement channelElement = xmlDocument.CreateElement("channel");
rssElement.AppendChild(channelElement);

GenerateItems(channelElement, xmlDocument, context);

context.Response.ContentType = "text/xml";
xmlDocument.Save(context.Response.Output);
context.Response.End();
}

public void GenerateItems(XmlElement channelElement,XmlDocument xmlDocument,HttpContext context)
{
string[] imageFiles = Directory.GetFiles(context.Server.MapPath("~/Images/"));

foreach(string imageFile in imageFiles)
{
FileInfo fileInfo = new FileInfo(imageFile);

XmlElement itemElement = xmlDocument.CreateElement("item");

XmlElement titleElement = xmlDocument.CreateElement("title");
titleElement.InnerText = fileInfo.Name;

XmlElement linkElement = xmlDocument.CreateElement("link");
string link = "http://localhost/myapp/Images/" + fileInfo.Name;
linkElement.InnerText = link;

XmlElement thumbnailElement = xmlDocument.CreateElement("media","thumbnail",media);
thumbnailElement.SetAttribute("url", link);
XmlElement mediaElement = xmlDocument.CreateElement("media","content",media);
mediaElement.SetAttribute("url", link);
itemElement.AppendChild(titleElement);
itemElement.AppendChild(linkElement);
itemElement.AppendChild(thumbnailElement);
itemElement.AppendChild(mediaElement);

channelElement.AppendChild(itemElement);
}
}

public static string Utf8BytesToString(byte[] InBytes)
{
System.Text.UTF8Encoding utf8encoder = new System.Text.UTF8Encoding(false, true);
return utf8encoder.GetString(InBytes, 0, InBytes.Length);
}

public bool IsReusable {
get {
return false;
}
}
}


Friday, July 11, 2008

Free iPhone applications

Apple iTunes Remote
With Apple's new iTunes Remote app, you can control the music on your computer or Apple TV from your iPod touch or iPhone. Play, pause, skip, shuffle. See your songs, playlists and album art on your iPod touch or iPhone as if you were right in front of your computer.

Remote works with your Wi-Fi network, so you can control playback from anywhere in and around your home.

Features include:
- Control the music on iTunes or Apple lV
- See the album artwork on your Remote
- Search your whole iTunes library
- Control your AirTunes speakers

AIM

Mobile AIM lets you stay in touch with your friends and family right from your iPhone or iPod Touch. The app lets you communicate whenever you want, wherever you are, in whatever way that suits you best. Connect with friends and family and keep track track of status and presence updates in real time.

Features include:
-Send and receive messages over WiF, EDGE, or 3G networks.
-Connect to anyone on the AIM network worldwide, whether they're on AOL. AIM, ICQ, .Mac or MobileMe.
-Manage your Buddy List feature, choose Favorites, or add a new buddy anytime.
-Your changes are automatically synced with iChat and or Windows or Mac.
-View expressions and update status
-See who's available before you contact them
-Send IMs and SMS text messages -- even from an iPod Touch
-Take pictures with the built-in camera to use as your buddy icon

You can get started by signing in using your existing AOL, AIM, .Mac or MobileMe name, or register for a free screen name right from your device.

Facebook

Facebook for iPhooe makes it easy to stay connected and share information with friends. Use your iPhone to start a conversation with Face book Chat, check your friends' latest photo, and status updates, look up a phone number, or upload your own mobile photos to Facebook while on the go.

Facebook promises even more features will be updated in the weeks and months ahead.

Google Mobile App

Google Mobile App for the iPhone or iPod Touch aims to make it fast and easy to search the Web.

Find web pages, business listings, phone contacts and more with Iess typing than ever before via Google's intelligent query completion and handy search shortcuts which appear as you type. You'll get suggestions to help you complete your query, and can see the results on a map in a single click.

MySpace Mobile

If you spend large chunks of your life hanging out on MySpace, you're "going to love Myspace Mobile for iPhone" and the iPod touch.

Features include:

- Send and receive messages
- Browse your network of friends and see their current status
- Upload and share photos from your iPhone
- Post comments on friends' profiles and photos
- Stay up-to-date with bulletins
- Search to find new friends

Thursday, July 10, 2008

How to Troubleshoot web pages in IE

Most of the Web Developers are using FireFox when developing their Web applications because their are number of plugins that can help them troubleshoot their pages. A good example for such plugin is FireBug.
Personally as a web developer i can't work without FireBug because i can debug and fix my problems very easily with FireBug.

As a cross browser developer i found many times my self in a situation where i need a FireBug like functionality for IE. After some surfing i found IEDevloper Toolbar, a good utility for this purpose made by Microsoft.

IEDevloper Toolbar is not that strong and powerful as FireBug but still provide developer a good support for debugging.

The Internet Explorer Developer Toolbar provides several features for exploring and understanding Web pages. These features enable you to:

  • Explore and modify the document object model (DOM) of a Web page.
  • Locate and select specific elements on a Web page through a variety of techniques.
  • Selectively disable Internet Explorer settings.
  • View HTML object class names, ID's, and details such as link paths, tab index values, and access keys.
  • Outline tables, table cells, images, or selected tags.
  • Validate HTML, CSS, WAI, and RSS web feed links.
  • Display image dimensions, file sizes, path information, and alternate (ALT) text.
  • Immediately resize the browser window to a new resolution.
  • Selectively clear the browser cache and saved cookies. Choose from all objects or those associated with a given domain.
  • Display a fully featured design ruler to help accurately align and measure objects on your pages.
  • Find the style rules used to set specific style values on an element.
  • View the formatted and syntax colored source of HTML and CSS

Download Internet Explorer Developer Toolbar

Wednesday, July 9, 2008

Usefull plugins for FireFox 3

I mainly used FireFox for web development because of many cool plug ins that provide a boost to the development for example the FireBug, WebDeveloper etc. Recently i have installed and using FireFox 3. I found some very cool plugins and want to share them with you. Please check the following plugins.

ScribeFire Blog Editor 2.2.9

ScribeFire is a full-featured blog editor that integrates with your browser and lets you easily post to your blog.


FireFTP 0.99.2

FireFTP is a free, secure, cross-platform FTP client for Mozilla Firefox which provides easy and intuitive access to FTP servers.

Codetch 0.4.1rc1

Get the feel of Dreamweaver in a Firefox extension. Edit your documents right next to your web pages as you surf.

Test web site for different versions of IE

Most of the time web developers come into a situation facing problems with the different versions of Internet Explorer. Where their site works fine for a specific version of IE but have some problems with other version. I my self faced this situation several times when my site just works fine for IE 7 but has many issues when i test it in IE6.
As we can only have a single version of Internet Explorer on our development machine and this issue creates a lot of panics for me. I have to configure different version of IE on different machines and then to test my code on these different machines for different IE versions.

Thanks GOD at last i found a good tool that help me get rid of this problem. This is the IETester WebBrowser.

IETester is a free WebBrowser that allows you to have the rendering and javascript engines of IE8 beta 1, IE7 IE 6 and IE5.5 on Vista and XP, as well as the installed IE in the same process.

Thanks to the www.my-debugbar.com
for creating such a cool WebBrowser and making it free for developers community. There is many more cool stuff available at www.my-debugbar.com
You can download latest version of IETester from here