Prabir's Blog

where the tech matters...

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: 100]

Tags: ,

Blog | BlogEngine.NET | snippets | Windows

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: 267]

Tags: , , ,

ASP.NET | JQuery | snippets

Retrieve ASP.NET Profile from App_Code, asmx Web Services

September 19
by prabir 19. September 2009 19:55

Its most very likely that you will be using the Membership, Roles and Profile providers provided by the .NET framework. It has been well designed and is very easy to use.

When you are in the .aspx.cs (basically the class that inherits from System.Web.UI.Page) you can easily access Profile class and get the profile for a particular user by using the following syntax.

ProfileCommon profile=Profile.GetUser("username");

But if you are creating some huge enterprise level applications, you will soon arrive to a problem where you can no longer the access the Profile. This happens if you want to call your profile from .cs files App_Code or library files (.dll) including webservices such as .asmx.

This problem can be solved by accessing the ProfileBase class in System.Web.Profile namespace.

ProfileCommon profile = (ProfileCommon)ProfileBase.Create("username", true);

Even though the method called is Create, it doesn’t create a new Profile for the user. If the profile already exists it retrieves it. Second parameter indicates whether the user is authenticated or anonymous. true if the user is authenticated else false to indicate anonymous.

Tags:

ASP.NET | snippets

Javascript debugging in IE8 with console

August 21
by prabir 21. August 2009 20:42

Internet Explorer 8 has taken the javascript development to the next level by providing a rich developer integration with the browser. In this post I will explain one of the core feature that I use often when debugging my web applications containing javascript.

Traditionally one of the best way to debug was using the alert function. But this is quite annoying as we have to press ok all the time. IE8 creators understood this and have created a set of functions to easily allow us to debug.

Instead of using alert, you can use console.clear(), console.log(), console.info(),console.error(),console.warn() to provide better information when debugging.

console.clear();
console.log("hello world from js to ie8 console");
console.info("sample info");
console.error("sample error");
console.warn("sample warning");
var x = "hello";
var y = 10;
var z=1.1;
console.log("string:%s:int:%i,real:%f",x,y,z);
image

The parameters for the console functions have the same format as printf function in c. Anyways I have put some examples above to make it easier.

  • %s  string
  • %i   integer (whole numbers only)
  • %f   floating point numbers (decimal values)

I would recommend you to use proper info, error and warn rather than just log as it even allows us to filter as shown below.

image

If you get image  at the bottom of you IE on status bar, it is basically the error telling the the console is undefined. In order to solve it, open the IE developer tools (press F12) and refresh the page. This automatically registers the console and you will not get any javascript errors.

Tags:

snippets

Syntax Highlighter 2.0 and Blog Engine.Net

July 07
by prabir 7. July 2009 21:47

This post is a continuation of my previous article on integrating Syntax Highlighter 2.0 with Windows Live Writer. I would recommend you to read it also. This article will take it one step further by learning how to integrate it with Blog Engine.Net 1.5. For Syntax Highlighter 1.5 with Blog Engine and Windows Live Writer you can find my article here.

You will need to download the Syntax Highlighter 2.0 files from http://alexgorbatchev.com/wiki/SyntaxHighlighter or at the end of this post.

You will need to upload the necessary files and folders (scripts and styles folder are only required). Then login to your blog as administration and go to the settings tab of the BlogEngine. In your html head section paste the following code and click save settings.

<link type="text/css" rel="stylesheet" href="/styles/shCore.css" />
<link type="text/css" rel="stylesheet" href="/styles/shThemeDefault.css" />
<script type="text/javascript" src="/scripts/shCore.js"></script>
<script type="text/javascript" src="/scripts/shBrushCSharp.js"></script>
<script type="text/javascript" src="/scripts/shBrushCpp.js"></script>
<script type="text/javascript">
SyntaxHighlighter.config.clipboardSwf = '/scripts/clipboard.swf';
SyntaxHighlighter.all();
</script>

At the moment only C# and C++ syntax highlighting is available. If you would like to support more languages please add the appropriate javascript file as shown below

<script type="text/javascript" src="/scripts/shBrushXml.js"></script>

The list of available languages can be seen from Scripts folder that you just uploaded.

syntaxhighlighter_2.0.320.zip (81.54 kb) [Downloads: 107]

Windows Live Writer Plugin (Setup recommended):
Prabir.wlw.Syntaxhiglighter.dll.zip (38.40 kb) [Downloads: 149]
Prabir.wlw.SyntaxHiglighter.msi (Setup) (360.00 kb) [Downloads: 205] 

Get from Windows Live Gallery

Tags: , ,

Blog | BlogEngine.NET | snippets

The hidden C# Operator - ??

May 20
by prabir 20. May 2009 15:03

How many times have you actually written your program to check if an object is null or not. Well! It isn’t difficult at all. Let me introduce you to one of those hidden operator. Dot you know what it looks like ?? Well the answer is in the question it self. ?? is our new operator.

?? is referred to as null coalescing operator. Its main task is to assign a default value to an object if it is null.

Let’s start with an example:

string text = "hello world!" ; 
string test = text ?? "this is not the value";

The outcome of the above code will result in test = “hello world!” because text is not null.

string text = null; 
string test = text ?? "this was null";

The value of test = “this was null”. Since text is null, it will assign the default value after ?? operator. It works with any objects not just string.

For more information check out MSDN library at http://msdn.microsoft.com/en-us/library/ms173224.aspx.

Tags: ,

C# | snippets