Prabir's Blog

where the tech matters...

CodePlex now supporting native Mercurial

January 23
by prabir 23. January 2010 06:38

More information at http://blogs.msdn.com/codeplex/archive/2010/01/22/codeplex-now-supporting-native-mercurial.aspx?CommentPosted=true#commentmessage

Here’s a short tutorial on using Mercurial with codeplex for beginners http://blogs.msdn.com/codeplex/archive/2010/01/22/using-mercurial-on-codeplex.aspx

If you would like to GIT to be supported at CodePlex please vote at http://codeplex.codeplex.com/WorkItem/View.aspx?WorkItemId=19723

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags:

Best of 2009

December 31
by prabir 31. December 2009 15:00

Happy New Year to all of you.

As we come to the end of the year, let me summarize you through what prabir.me achieved during 2009.

Top 5 Most Popular Posts of 2009

  1. Dark Eclipse Theme
  2. My Visual Studio Theme
  3. Using jqGrid with ASP.NET Web Forms - Part II
  4. Windows Live Writer Syntax Highlighter
  5. LLVM# – Native C# Compiler

Top 5 Most Downloaded Files of 2009

  1. .NET/E – .net/everywhere
  2. Dark Eclipse Theme
  3. My Visual Studio Theme
  4. Visual Studio 2010 Beta 1 - Theme Patch
  5. Screwturn Wiki 3 Syntax Highlighter 2

Open Sourced Project that I had been active during 2009.

  1. LLVM# (A New C# Compiler)
  2. Coco/R For Visual Studio
  3. Helpers.NET
  4. Windows Live Writer Syntax Highlighter

You can see other projects that I have help developed here.

During the end of 2009 I have been bit busy and it continue till the end of 1st quarter of 2010, but I promise to share my knowledge to the open community from where I have gained so much.

Once again Happy New Year to all of you and hope you have enjoyed reading my blog. Any new improvements or suggestions that you would like to see in the blog please write the comment below or contact me from here.

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags:

Create a Windows 7 Federated Search Connector for your Blog

December 20
by prabir 20. December 2009 08:28

The driving force that landed me to create this blog that you are reading now, has mainly been that I wanted to contribute back to the society, “the internet society” from where I have learned so much. And the other one was to also put as a reference from the future. There are many times when I actually need to refer to my own blog.

For instance, I often need to redirect HTTP to HTTPS. (You can find this article at http://blog.prabir.me/post/HTTP-redirection-to-HTTPS.aspx). But opening blog.prabir.me and then typing redirect in the search box would quite lose my time. So I landed up creating a Windows 7 Federated Search Connector – a cool new Windows 7 feature.

When I search for redirect keyword in my blog using the Window 7 connector I would get the following result.

image

 

How does the magic happen. Well first the search results show up as RSS feeds using the open search URL conventions. And luckily BlogEngine.NET already supports it out of the box. Try this url http://blog.prabir.me/syndication.axd?q=redirect

It already contains the page called syndication.axd where we can pass you search query using the q querystring.

To do that we define a Windows 7 Search Connector file ending with .osdx extension. It is a normal text file. So you can edit it using your favorite text editor.

<?xml version="1.0" encoding="UTF-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
  <ShortName>Prabir's Blog - www.prabir.me</ShortName>
  <Description>Prabir's Blog - where the tech matters</Description>
  <Language></Language>
  <Url type="application/rss+xml" template="http://blog.prabir.me/syndication.axd?q={searchTerms}"/>
</OpenSearchDescription>

Notice the URL, we pass the search query in querystring q as {searchTerms}, that is how Windows 7 uses it.

Once you save it to .osdx file, double click it and you will asked if you want to add it. Click add then you are all set.

But the fun doesn’t end here. In the search results when you double click, it will open the article in Web Browser. And if you have the preview pane, it will show up in the Window Explorer Search Window it self as shown below.

image

prabirDOTme-Windows7FederatedSearchConnector.zip (371.00 bytes) [Downloads: 236]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: ,

BlogEngine.NET | Windows

Syntax Highlighter for Windows Live Writer v0.2 released

December 06
by prabir 6. December 2009 23:08

Syntax Highlighter v0.2 has been released along with source code at Codeplex. This is an update to my original Windows Live Writer plugin which can be found at http://blog.prabir.me/post/Windows-Live-Writer-Syntax-Highlighter.aspx.

As you might have noticed some of the features such as auto link detection, collapse, gutter (line numbering), toolbar, wrap lines and starting line number have been added.

image

To download the files please visit http://codehighlighter.codeplex.com

or download from windows live gallery.

More features coming soon. If you want to help develop this plug-in please leave a comment below or contact me at http://blog.prabir.me/contact.aspx.

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: ,

BlogEngine.NET

Using jqGrid with ASP.NET Web Forms - Part II

December 06
by prabir 6. December 2009 19:43

This article is continuation of my previous article.

To start of with, we first need to create an asmx web service in JSON format. If you are not sure of how to use JSON in asmx web services, I would suggest you to read my previous articles - JSON in Classical Web Services - ASMX and Consuming ASP.NET Web Services using JQuery.

Lets create a web service method called GetListOfPersons. Remember to decorate it with ScriptMethod Attribute as our means of data communication will be in JSON format. In the following example JsonHelper.GetPersons() is responsible for retrieving the list of persons. You can have a appropriate data access logic out there.

[WebMethod]
[ScriptMethod]
public string GetListOfPersons()
{
    List<Person> persons = JsonHelper.GetPersons();
    return Newtonsoft.Json.JsonConvert.SerializeObject(
        new PagedList(persons, persons.Count, 1, persons.Count));
}

Then we create a new instance of PagedList object that we defined in the previous post. Here’s one of the constructor that we will be using in case you have forgotten.

public PagedList(IEnumerable rows, int totalRecords, int pageIndex, int pageSize);

For simplicity we will not be including features such as paging and sorting for now. (I will include it in later posts.) So, here the rows will be the list of persons retrieved, totalRecords will be the number of persons in the list hence persons.Count, pageIndex will just be simple as 1 as all data will be displayed on the same page number 1. pageSize will be the totalRecords as we don’t want to having paging enabled for now.

Now that the instance of PageList has been created. We need to serialize the object into JSON format which can be recognized easily by jqGrid. To achieve this we make use of Newtonsoft.JSON library by calling the SerializeObject method as shown above.

Now that we are done with the web service, we need to start coding the user interface in HTML and JavaScript.

Create a HTML table along with an ID. This table will be rendered as jqGrid when previewed in the browser.

 

<table id="table" cellpadding="0" cellspacing="0">
</table>

 

Include appropriate css style sheets and javascript files required for jqGrid to function. You will need the JQuery UI,  and multiselect also. Multiselect JQuery plugin can be obtained from http://quasipartikel.at/multiselect.

 

<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/jquery-1.3.2.min.js") %>"></script>
<link type="text/css" rel="stylesheet" href="<%= ResolveClientUrl("~/styles/redmond/jquery-ui-1.7.2.custom.css") %>" />
<link type="text/css" rel="stylesheet" href="<%= ResolveClientUrl("~/styles/ui.jqgrid.css") %>" />
<link type="text/css" rel="stylesheet" href="<%= ResolveClientUrl("~/styles/ui.multiselect.css") %>" />
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/jquery-ui-1.7.2.custom.min.js") %>"></script>
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/i18n/grid.locale-en.js") %>"></script>
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/jquery.jqGrid.min.js") %>"></script>
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/ui.multiselect.js") %>"></script>

 

Let me write the code first and then explain later on. So it would be easier for you guys to copy paste and learn.

 

<script type="text/javascript">
    $(function () {
        $("#table").jqGrid({
            datatype: function (pdata) { getData(pdata); },
            height: 250,
            colNames: ['ID', 'First Name', 'Last Name'],
            colModel: [
           		{ name: 'ID', width: 60, sortable: false },
           		{ name: 'FirstName', width: 200, sortable: false },
           		{ name: 'LastName', width: 200, sortable: false }
           	],
            imgpath: '<%= ResolveClientUrl("~/styles/redmon/images") %>',
            caption: "Sample JSON data retrieved from ASMX web services"
        });
    });
    function getData(pData) {
        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            url: '<%= ResolveClientUrl("~/WebService.asmx/GetListOfPersons") %>',
            data: '{}',
            dataType: "json",
            success: function (data, textStatus) {
                if (textStatus == "success")
                    ReceivedClientData(JSON.parse(getMain(data)).rows);
            },
            error: function (data, textStatus) {
                alert('An error has occured retrieving data!');
            }
        });
    }
    function ReceivedClientData(data) {
        var thegrid = $("#table");
        thegrid.clearGridData();
        for (var i = 0; i < data.length; i++)
            thegrid.addRowData(i + 1, data[i]);
    }
    function getMain(dObj) {
        if (dObj.hasOwnProperty('d'))
            return dObj.d;
        else
            return dObj;
    }
</script>

 

jQuery ready function initializes the jqGrid. The data type we have chosen is a custom function with a parameter called pdata. pdata is a short of ParameterData. You can name it what ever you feel comfortable with. It then calls the function called getData. ColName is an array of string containing the column header. ColModal contains more information on how to render data.

Note: The name in ColModal is not the same as ColName but rather its same as that of the list of objects, which was passed as enumerable rows when creating PageList.

Function getData is responsible for doing an AJAX request to the webservice. If success it calls another function called ReceivedClientData. RetrieveClientData function is responsible for appending the data to the grid.

As the data is Ajax request and our response is in string, we need to parse the JSON string to JSON object using json2.js. (We will not be using eval due to security reasons though it is possible.)

GetMain function is used to trip of the “d” property, which is generated by web services if using new versions of ASP.NET for security reasons.

jqGridAspNetWebForms.zip (617.09 kb) [Downloads: 767]

jquery.jqGrid-3.6.zip (274.12 kb) [Downloads: 746]
jquery-ui-1.7.2.custom.zip (745.92 kb) [Downloads: 353]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: , , , ,

ASP.NET | JQuery

My Dark Visual Studio Theme - Update

November 17
by prabir 17. November 2009 19:03

Some of you must have already tried my Dark Visual Studio Theme from http://blog.prabir.me/post/My-Visual-Studio-Theme.aspx as seen below.

dark visual studio theme

But as I upgraded to Visual Studio 2010, some of the colors didn’t seem to go well with the new WPF editor.

image

As you can see above, you cannot read the text at all, and its too bright which breaks the total aim of the theme. I have upgraded the theme to have better support in VS2010. Tweaked a bit of settings to suit VS2010.

Now the fixed one would look like this.

image

There are others changes also especially to the .aspx pages. When you upgrade my VS2008 settings in 2010 it would be displayed as below. The <% %> colors are unreadable. The same with JavaScript keywords (function…) and strings. And for some reasons, the HTML attribute the appears in red which it should not had been as shows below. (for some reason VS2010 didn’t upgrade this particular setting – HTML attribute name color)

image

Now that I have fixed, it is more pleasant as you can see the updated version below.

image

Now its better. I had to make some changes like the keyword to green which is the same as in C#, because the blue as in VS2008 didn’t seem to work at all. It was too blurry. The same with strings – defaulted to C# type coloring. I hope the C# type coloring in JavaScript will help you get familiar more easily.

Any other stuffs I forgot to update, please leave a comment below.

Read my original article on the dark theme on why you should shift @ http://blog.prabir.me/post/My-Visual-Studio-Theme.aspx

Note: The font used is Consolas which comes preinstalled with Windows Vista and up. But incase you want to use it for your Windows XP, Windows Server 2003 or others you can either download from below or from the official Microsoft link over here. 

Click here to download the theme

Prabir.vssettings (209.98 kb) [For VS2010] [Downloads: 553] (Right click and Save Target As ...)

CurrentSettings.vssettings [For VS2008](252.68 kb) [Downloads: 1363] (Right Click and Save Target As ...)

Consolas Font Pack for Microsoft Visual Studio 2005 or 2008.exe (4.33 mb) [Downloads: 896]

This same theme for Eclipse IDE can be downloaded from http://blog.prabir.me/post/Dark-Eclipse-Theme.aspx.

[UPDATE]

Due to the popularity. I moved moved the themes to be in source control, which can be found at http://gitorious.org/themes. If any one of you would like to contribute your own theme or extend my dark theme please post it in the comment below. My dark themes for various IDEs and text editors can be download from http://www.ohloh.net/p/themes/download

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: ,

Visual Studio

Using jqGrid with ASP.NET Web Forms - Part I

November 14
by prabir 14. November 2009 14:55

(As this article grew up to be quite long then I expected, I have broken up this post into different Parts.)

When I first started to use jqGrid few months back, I couldn’t find good tutorials on using jqGrid with ASP.NET webforms. Any search on ASP.NET and jqGrid would lead to ASP.NET MVC tutorial. So, I thought of writing this article to help you guys.

I will be using jqGrid version 3.6 (the codes presented here will most probably work with the earlier versions too – You can download the latest version of jqGrid from http://www.trirand.com/blog or version 3.6 at the end of this article).

We will be using JSON as means of data communication which will be provided by asmx web services. If you don’t know how to use JSON in asmx web services, I would suggest you to read my previous articles - JSON in Classical Web Services - ASMX and Consuming ASP.NET Web Services using JQuery. (Similar concepts can also be applied to WCF RESTful web services.)

How does jqGrid understand our JSON format?

Answering the above question is vital for getting things done right. So lets start with understanding JSON format used by jqGrid.

{
    "page":"1",
    "total":4,
    "records":"10",
    "rows":[
        {"id":"1","cell":["Prabir","Shrestha"]},
        {"id":"2","cell":["Bill","Gates"]},
        {"id":"3","cell":["Steve","Ballmer"]}
    ]
}

Page stands for the current page index. Total represents the total number of pages available and records for the total number records in the entire data list including those not shown in the rows.

Let’s have a closer look at rows. It contains 2 fields, id and cell. The cell contains the main data which needs to be rendered. Here again we have two fields. Try guessing what those fields are.

The first field represents First Name and second field represents Last Name. It is basically an array of string. If others are consuming your web services it would be very difficult for them to actually guess the meaning of these fields. To overcome this difficulty in understanding, lets take an alternative approach. We would then have the result in the following manner.

{
    "page":"1",
    "total":4,
    "records":"10",
    "rows":[
        {id:1,FirstName:"Prabir",LastName:"Shrestha"},
        {id:1,FirstName:"Bill",LastName:"Gates"},
        {id:1,FirstName:"Steve",LastName:"Ballmer"},
    ]
}

The above example is more descriptive and easier to understand. But now another problem arises. How do I convert to that JSON format?

To work with this we create a helper class called PagedList as follows.

using System;
using System.Collections;

public class PagedList
{
    IEnumerable _rows;
    int _totalRecords;
    int _pageIndex;
    int _pageSize;
    object _userData;

    public PagedList(IEnumerable rows, int totalRecords, int pageIndex, int pageSize, object userData)
    {
        _rows = rows;
        _totalRecords = totalRecords;
        _pageIndex = pageIndex;
        _pageSize = pageSize;
        _userData = userData;
    }

    public PagedList(IEnumerable rows, int totalRecords, int pageIndex, int pageSize)
        : this(rows, totalRecords, pageIndex, pageSize, null)
    {
    }

    public int total { get { return (int)Math.Ceiling((decimal)_totalRecords / (decimal)_pageSize); } }

    public int page { get { return _pageIndex; } }

    public int records { get { return _totalRecords; } }

    public IEnumerable rows { get { return _rows; } }

    public object userData { get { return _userData; } }

    public override string ToString()
    {
        return Newtonsoft.Json.JsonConvert.SerializeObject(this);
    }
}

Notice that I have included all the fields required by jqGrid. And all these also violates standard C# naming standards. This is to make it easy (Javascript is case sensitive) for us to serialize the object to JSON string understandable by  jqGrid by using the help of Newtonsoft JSON library. Total is also calculated automatically for us.

The rows is basically IEnumerable, which means we can also assign List<T> to it. Which makes our work easier. And since we have overridden the ToString method, converting the object to JSON string representation is far lot easier.

Then how do I put all the things together?

For example lets assume the Person class is declared as below.

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

and let us also assume that there is a method called GetPersons which returns us a List of Person (List<Person>).

Now to create the PagedList, we simply call the constructor of the PagedList.

PagedList pagedList = new PagedList(GetPersons(), 10, 1, 3);

It will then create a new instance of PagedList and assign the GetPersons List<Person> to rows, 10 to records, 1 to page index and 3 to pageSize.

There is no default constructor for PagedList and it is also an immutable object, which means if you need to change anything you will need to create a new instance of it again. The reason I did this was because, I always used to get confused between total, page and records. So I came up with a solution that I would always use constructor and the parameters in these constructors would be name is such a way that it would not confuse me, so I landed up naming them as pageIndex, pageSize and so on. The other way around would be to use the get and set for all the properties and use the xml documentation features using /// <summary> to prevent the confusion.

This concludes the Part I for Using jqGrid with ASP.NET web forms. In part II, I will be going through on how to actually display it in jqGrid. Stay tuned.

jquery.jqGrid-3.6.zip (274.12 kb) [Downloads: 746]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: , , ,

ASP.NET | JQuery

Consuming ASP.NET Web Services using JQuery

November 10
by prabir 10. November 2009 19:49

In this tutorial we will be using JQuery to consume Asp.Net web services.

If you do not know how to create webservices that output JSON results please see my previous blog post on JSON in Classical Web Services ASMX.

If you have reached this point, I assume you know how to create webservices in JSON.

Inorder to do this, we will be using JQuery’s. $.ajax. As asp.net explicitly makes all ScriptMethods POST, we cannot use JQuery’s get method.

contentType needs to be changed to application/json and dataType as json.

data:’{}’ is the parameter being passed.

success:function(msg){} this method is executed when the POST successfully happens, and stores the result in msg.

error:function(){} this method is executed when an error occurs.

$.ajax({
    type: 'POST',
    url: '<%= ResolveClientUrl("~/JsonWebService.asmx/ReturnStudent") %>',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: '{}',
    success: function (msg) {
        var jsonObject = JSON.parse(getMain(msg));
        alert('FirstName:' + jsonObject.FirstName);
    },
    error: function () {
        alert('error occured');
    }
});

ReturnStudent is a WebService Method which is shown as below.

[WebMethod]
[ScriptMethod]
public string ReturnStudent()
{
    return JsonHelper.ToJson(JsonHelper.CreateSampleStudent());
}

The above method create an Object and then serializes to JSON string and returns the JSON string as the output.  (You can read more on this at http://blog.prabir.me/post/JSON-in-Classical-Web-Services-ASMX.aspx – The same example is used. I’m using Newtonsoft’s JSON library to convert the object to JSON string).

When we execute the above JQuery code, msg contains the JSON string not a JSON object. (Our WebMethod returns a string.) So we need to parse the JSON string to a JSON object. To do this we will be using a 3rd party library called json2.js. You can read more about parsing at http://blog.prabir.me/post/Parsing-JSON-in-JavaScript.aspx. To achieve this we use JSON.parse(msg). But we need to be a bit careful out here. .NET 2.0 and .NET 3.5 will give different output. .NET 3.5 adds the d property which we have to be careful. The result would be as follows.

var net20ResultFromWebService = "{\"FirstName\":\"Prabir\",\"LastName\":\"Shrestha\"}";
var net35ResultFromWebService = { "d": "{\"FirstName\":\"Prabir\",\"LastName\":\"Shrestha\"}" };

Notice the “d”. It was added for security reasons.

So, instead of just using JSON.parse(msg) we use our own custom helper function called getMain(). It basically strips off the “d” property if it contains else returns the object it self. This is important especially if you are consuming others webservices and all of the sudden when they upgrade the .NET version, all you site cracks down. Taking this extra precaution might be a bonus to you.

Here’s the function that solves the .NET version compatibility problem.

function getMain(dObj) {
    if (dObj.hasOwnProperty('d'))
        return dObj.d;
    else
        return dObj;
}

What if you have a function which contains parameters like below.

[WebMethod]
[ScriptMethod]
public string Print(string name, int times)
{
    // code omitted for brevity
}

Remember the data:’{}’ parameter in $.ajax I told before. We need to make use of it.

data: "{name:'Prabir',times:2}"

It would be represented as above in JSON string format. That is it.

In the upcoming posts I will be guiding through on how increase the user experience by showing animating features (loading…please wait…). Stay tuned.

JQueryAndAspNetWebservices.zip (769.57 kb) [Downloads: 473]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags:

JQuery

Downgrading VS2010 solutions to VS2008

November 05
by prabir 5. November 2009 11:27

Visual Studio 2010 has been my default IDE now. It has a bunch of cool features to work with. But unfortunately some of my colleagues are not comfortable in migrating to VS2010 as it is in beta stages or either they don’t want to have 2 instances of VS installation which takes up their storage.

But I couldn’t just leave VS2010. Not only because of its new features but also due to the fact that it has to be the default IDE later on anyways and VS team needs to find as much bugs and errors and fix them all by the time it RTMs. (VSTeam actually really does listen to your feedback. They fixed all my 10 bugs I reported in VS2010 Beta 1. So for the betterment I would like you to try updating to VS2010 and find as much bug as you can and send them feedbacks.)

Now lets get to the real thing of downgrading. I will not be explaining on how to upgrade from VS2008 to VS2010, because it already does automatically. But I will rather be going through on how to do the opposite.

1. Make a backup copy of your .sln file. It will result in two solutions. One for VS2010 and the other for VS2008. The .csproj files doesn’t need to be modified at all.

2. Open one of the .sln file in a text editor (notepad is more than fine).

image

 

You will see somewhat like the above in the selected text, where version is 11.00 and visual studio version is 2010.

3. Edit the version numbers. Now change it 11.00 to 10.00 and 2010 to 2008.

image

 

Then save it. Rename your solution files to solutionname-2008.sln and solutionname-2010.sln or something like that if you want.

Now you can open it in older version’s of Visual Studio.

But since my VS2010 is my default IDE, I didn’t even install VS2008 rather installed only VS2008 C# Express versions. You can open it from VS2008 C# Express Versions, but test projects will not be loaded and solution folders will not work. Besides that everything will most probably work fine.

Note: Any updates like adding new file in VS2010 or VS2008 is also maintained in both solutions, because the file structures are stored in .csproj file which is by nature VS version independent.

And since my projects are at max in .NET v3.5, it all works fine in VS2008. I did land up with some warning errors during compilation under VS2008.

Project file contains ToolsVersion="4.0", which is not supported by this version of MSBuild. Treating the project as if it had ToolsVersion="3.5".

So since it goes back to 3.5 it still works fine. You can just ignore the warning.

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags:

Visual Studio

Engineering Windows 8

October 26
by prabir 26. October 2009 01:06

As I was surfing through some articles I landed up in Engineering Windows 7 blog at http://blogs.msdn.com/e7.

Out of curiosity I thought of giving a try on Windows 8 blog, by replacing 7 with 8 and out of my surprise, they are already prepared for writing the blog. All thought it doesn’t contain any blog posts.

http://blogs.msdn.com/e8

image If you notice carefully, you will see that the title is <TBD> which is an abbreviation of “to be determined” or “to be defined”. So, my guess is Microsoft is already starting to work quite hard on Windows 8, but trying to remain quite by not disturbing the small brother – Windows 7 as much as it can.

I did try checking out for Windows 9 blog too, but no success. http://blogs.msdn.com/e9 returns with a 404 File or Directory not found error.

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: