web 2.0

Setting up SVN on Windows

Subversion is ultimately one of the best source control option we have in today’s world. it has very light instance running on Server and of course it is FREE.

To access the Subversion repository on the client machine we have multiple options. If we want to use shell integrated UI (means we can call your source control options in our windows explorer), we can use TortoiseSVN but being a developer based on Visual Studio it always looks good to get my source control on Solution Explorer inside Visual Studio world and for that we have Visual SVN  which off cost  and  AnkhSVN which is FREE.

One time server configuration is needed on almost every server software so as with SVN. After downloading and installing SVN following configuration is needed in order to work properly. By the way, we are assuming that you download the setup from CollabNet.

Download URL : http://www.open.collab.net/downloads/subversion/

Installing SVN (CollabNet):

This installation is next next stuff but the following screens needs a little awareness.

settingup_svn_service

Port will be the default port on which the Subversion server listen for the request and the repository is a location where your source code will be saved.

Notice the checkbox, titled “Install svnserve to run as Windows service”. If this box is checked SVN will run as windows service and will be available as soon as the Server Machine starts.

settingup_svn_apache

It is important to understand that the SVN works on the Apache web server. If you are already using any other web server such as IIS, it is important to change the port of the Web Server. Also, an other checkbox is available to run the Apache web server as windows service.

Configuration:

Well, the above mentioned setup has done almost every thing for us. But still following configuration needs to understand in case of getting command over SVN.

 

    1. Configure SVN to run as service (Manually)
    2. Creating Repository (Manually)
    3. Configure Security
      1. Enable / Disable anonymous access
      2. Create Users
      3. Authorization
    4. Firewall Consideration 

Configure SVN to run as service (Manually):

To create SVN run as Windows service, we need to open CMD and run the following command

sc create svnserve binpath= "
    \C:\Program Files (x86)\CollabNet\Subversion Server\svnserve.exe\"
    --service --root c:\repos" displayname= "SubVersion Server" 
    depend= tcpip start= auto

 

Notice that the path of the svnserve.exe might be change in your case. Once we run this we can now see our newly created service in the service console.

settingup_svn_servicelist

Just in case, if we want to delete the service we can run the following command in cmd
sc delete svnserve

Creating Repository (Manually):


To create repository we need to use svnadmin utility. Following is the procedure

    1. Go to Run (Ctrl + R) –> CMD
    2. Go to the install directory of SVN in my case it is ( C:\Program Files (x86)\CollabNet\Subversion Server)
    3. Run command : svnadmin create C:\svn_repository  (we can change the path according to our need)

Configure Security:

Like other source control, you can create users in svn, give them right what they can do and all that important stuff but the user right assignments are change from repository to repository.

Once you successfully create a repository, you will find the following items under the folder of repository.

settingup_svn_folder

Now open the “conf” folder and create the following file (if it is not already there)svnserve.conf

and add the following lines

[general]
anon-access = read
auth-access = write
authz-db = authz
password-db = passwd

Disable anonymous access:

Anonymous access can be very useful in many scenario but in our case, we want to disable this access. To do this, we will edit svnserve.conf file and comment the anon-access line. after editing that file, svnserve.conf file will look like as below

[general]
#anon-access = read
auth-access = write
authz-db = authz
password-db = passwd

Of course, to enable the access we have to un comment this line.

Create Users :

If you have notice the last line we wrote in svnserve.conf file, it is password-db = passwd. Basically, it is the name of the file which contains the information about users.

Now lets create a file named “passwd” with no extension and add the following lines.

[users]
admin = adminpassword
admin2 = admin2password
ausman = ausmanpassword
ruser = ruserpassword

Note that the string before “=” is user id and the later one is password. if you still confuse, here is the formulae :)

username = password

That’s how, this file is saving the user information. Now, create as many users you want.

Authorization:

Now notice the second last line of the svnserve.conf file, where it says authz-db = authz. Basically, it is the name of the file which contains the authorization information about the users.

Now let’s consider the situation, where you want to create two set of users in your repository. It can be “Administratots” and ‘Regular Users’. You want to give read / write permission to both the users but on some folders you want only “Administrators” to write  files.

Now lets create a file named “authz” with no extension and add the following lines.

[groups]
adminstrators = admin, admin2
regulars = ausman, ruser

[repository:/]
* =
@adminstrators = rw
@regulars = rw

[repository:/trunk/admin-files]
* =
@adminstrators = rw

Ok, now let me explain how we did the whole thing line by line.  In the first three lines we simple created two groups that we discussed before.
On line no 4-7, we gave general write permission on every folder of the repository to both the groups.
On line no 8-10, we gave a special write permission to group named “Administrators”  for a folder called “admin-files”.

There we go, every thing is configured and we are ready to access the files from SVN Client.

Firewall Consideration:

As mentioned earlier SVN server listen for the request on port number 3690. In my case of implementation, the server was using Windows 2008 built-in Firewall which means, I can access the SVN server locally but from any remote machine I wasn’t able to get the files..

To do that, we simply need to add the port 3690 in the exception list of Firewall and allow the traffic coming thru this port.

That’s it and we are all done :)

Happy Eid-ul-Fitar 2009

Not too long a ago I can call myself blogger :). Actually I am posting any thing to my blog approximately about a month after. I have sacrifice some commitments to save the most important commitment to ALLAH. These 29 days of Ramadan went like a flash, it seems Ramadan start just yesterday.

I have not been a religious being in this holy month. Just finished the 12 days Taraweeh and a Holy Qur’an which I have started before Ramadan. Indeed, I pay thanks to ALLAH who make me enable to do all this worship. I can do nothing by my self :).

My family is about to leave for my grand parents house that’s why let me wrap up this post by saying HAPPY EID-UL_FITAR to all of you. May ALLAH shower his blessings to all of you and make these three days the memorable days of your life :). Don’t forget the needy people near you who cannot afford to have joy of eid.

Getting started with Unit Testing in C#

Introduction:

In this post, I will explain you how can we write a unit test in c#. It is a basic guideline for those who wants a quick start.

Unit testing is an integral part of any software that is developed. It is an advantage which most of us are either not aware of or we are neglecting it.  It actually helps a developer to write error free code.

To write unit test, we will first install a unit-testing framework.

 

About Unit-Testing Framework:

Well, Unit-Testing Frameworks are useful to simplify the process of unit testing. If you don’t want to use any framework then you can still do unit-testing by writing the client code which implements assertions, exception handling etc.

There are numerous framework available for unit testing. A list of which can be found here . But in our case, we will use NUnit to test our code because it is easy to use, show detail test reports and of course open source.

 

Installing NUnit:

To download the NUnit goto : http://www.nunit.com/ and download NUnit Windows MSI. The installation is a conventional next next stuff. So, you will not face any hard time.

 

Writing Testable code:

Now open visual studio and create a new console application (I name it TestAbleApp). Please note, to do unit-testing it is not important to write your code in console application. It is just a matter of my choice because I want to make it simple and easy to understand.

Create a new class call it “Utilities” and write the following code.

public class Utilities
{
    public enum Gender
    { Male =1,
      Female = 2
    }


    public string GetCompleteProfession(string professionName, Gender g)
    {
        string strPronoun = string.Empty;

        if (g == Gender.Male)
            strPronoun = "he";
        else
            strPronoun = "she";

        if (Regex.IsMatch(professionName,"^[aeiou]"))
            return strPronoun + " is an " + professionName;
        else
            return strPronoun + " is a " + professionName;
    }

    public decimal GetWeeks(DateTime dtFrom, DateTime dtTo)
    {
        int Days = ((TimeSpan)(dtTo - dtFrom)).Days;
        decimal Weeks = Math.Ceiling((decimal)Days / 7);
        return Weeks;
    }
    public decimal GetDays(DateTime dtFrom, DateTime dtTo)
    {
        int Days = ((TimeSpan)(dtTo - dtFrom)).Days;
        return Days;
    }
}

Let me explain, we have an enum here which hold the gender and we have a function which have Profession and Gender as parameter. it will simply return a formatted string. For example if someone pass

GetCompleteProfession(“System Analyst”,Gender.Male). It will return “He is a System Analyst”. A very simple function.

Then we have a function that will take date range as parameter and return the number of weeks in that range. We call it GetWeeks and another function is GetDays which takes same date range as parameter but return days instead of week.

We are completed with the testable code. If you want, you can check the output of the functions.

 

Writing Unit-Test:

To write a unit-test, create a class library project under the same solution and call it, “TestProject”. Now, create a new class and name it “UtilitiesUnderTest”. The naming convention can explain that this class contain the unit test of class “Utilities”.

Now, Add the executable of console application which we have created before (In my case, it is TestableApp ) as a reference in TestProject.

To use the NUnit Testing framework, we also need to add the reference of NUnit Dll which you will find under the .net Tab in Add Reference window.

sc_unittest_1

 

Create a class and call it UtilitiesUnderTest. Naming convention shows that we are creating a test code for class “Utilities”. Now write the following code.

[TestFixture]
class UtilitiesUnderTest
{
    [Test]
    public void GetCompleteProfession_Return_SheIsASoftwareEngineer()
    {
        
        Utilities objUtil = new Utilities();

        string strResult = objUtil.GetCompleteProfession("software engineer", Utilities.Gender.Female);

        StringAssert.AreEqualIgnoringCase("She is a software engineer", strResult);
    }

    [Test]
    public void GetCompleteProfession_Return_HeIsAProjectManager()
    {
        Utilities objUtil = new Utilities();

        string strResult = objUtil.GetCompleteProfession("software engineer", Utilities.Gender.Male);

        StringAssert.AreEqualIgnoringCase("He is a software engineer", strResult);
    }

    [Test]
    public void GetCompleteProfession_Return_HeIsAnEngineer()
    {
        Utilities objUtil = new Utilities();

        string strResult = objUtil.GetCompleteProfession("engineer", Utilities.Gender.Male);

        StringAssert.AreEqualIgnoringCase("He is an engineer", strResult);
    }

    [Test]
    public void GetWeeks_Return_6()
    {
        Utilities objUtil = new Utilities();

        decimal weeks = objUtil.GetWeeks(DateTime.Now.AddDays(-42), DateTime.Now);

        Assert.AreEqual(6, weeks);
    }

    [Test]
    public void GetDays_Return_25()
    {
        Utilities objUtil = new Utilities();

        decimal days = objUtil.GetDays(DateTime.Now.AddDays(-25), DateTime.Now);

        Assert.AreEqual(25, days);
    }
}

Notice the Attribute, [TestFixture] is used to mark a class as a test class where as [Test] is used to mark a method as Unit-Test (test method). It is used by Unit testing framework like N-Unit to test the code.

Also notice, the name of methods. It is named like “{MethodUndertestName}_Return_{ExpectedReturnValue}”. The naming convention is there to make your tests readable for others.

Now come to the explanation part of the first three functions.

In the first of line each function we are creating an object of the class under test (In our case Utilities).
In the second line we are calling a method under test by specifying parameters.
In the third line we are using StringAssert to Assert the returned value.

Now notice the last two functions, the first two lines are same. The minor difference is in the last line. Instead of using StringAssert, we are using Assert to test the return value.

Once, you have complete writing the Unit-Test. Now its time to see it in action.

Running Unit-Tests:

Run NUnit, Goto File –> New Project and specify the location.
Now, Goto Project menu and select Add Assembly and locate your TestProject DLL, the one which you created to test your code.
Once, you have done that, you will all your Unit-Test in the left pane as shown below.

sc_unittest_2

Now, click the big run button on the right pane and you will see the result as give below.

sc_unittest_3

Happy ending, green progress bar means every thing went well. Now let’s create another unit-test in out test class which will fail out tests. So that, we can see how NUnit reacts when a test fails.

Lets add the following method in our test class.

[Test]
public void GetWeeks_Return_3()
{
    Utilities objUtil = new Utilities();

    decimal weeks = objUtil.GetWeeks(DateTime.Now.AddDays(-8), DateTime.Now);

    Assert.AreEqual(3, weeks);
}


Here I am giving the range of eight days and expecting my function to return 3 weeks instead of two. Now, when I run the test it will get fail and NUnit display us something like below.

sc_unittest_4

Red progress bar means, some thing went wrong and notice the text area at the bottom. It will show you the detail that you were expecting three but the function returns two. That is the test get fails.

Now lets see what happen when any exception occur in the function we are testing.  Add the following line in GetWeek function

throw new ArgumentOutOfRangeException();

 

Now, when we run out tests, we will see some thing like below.

sc_unittest_5

NUnit fails our test with the exception with Stacktrace at the botoom.

 

Conclusion:

This was just a quick start of doing test driver development and write Unit-Tests that is why we create unit-test for very simple functions. In future, I will be posting the unit-tests which I will write for some more complex functions.

I have tried to make it simple for you guys to grab it and start writing your own unit-test. The resource I found very valuable for starting test driven development is Roy Osherove’s The Art of Unit Testing.

Get Countries Name in .Net

Introduction:

In this post, I will explain you how can we get the countries name filled in any collection using .net without using any database.

It is a regular task, which we all as developers did some past day but the difference is we used database table or xml file to hold the country names. But .net framework provide us with all the countries information in Globalization namespace.

So, here is the code for that

Dictionary<string,string> objDic = new Dictionary<string,string>();

foreach (CultureInfo ObjCultureInfo in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
    RegionInfo objRegionInfo = new RegionInfo(ObjCultureInfo.Name);
    if (!objDic.ContainsKey(objRegionInfo.EnglishName))
    {
        objDic.Add(objRegionInfo.EnglishName, objRegionInfo.TwoLetterISORegionName.ToLower());
    }
}

var obj = objDic.OrderBy(p => p.Key );
foreach (KeyValuePair<string,string> val in obj)
{
    ddlCountries.Items.Add(new ListItem(val.Key, val.Value));
}

 

Explanation:

Notice that, we have used typed dictionary object to store the name and the values of the countries.

Then, we use CultureInfo.GetCultures to get the cultural information of the countries.

Later on, we use RegionInfo to get the regional information of that  culture.

Since, there can be multiple cultures of the same country that is why there is a condition which check either the country is already added in dictionary. If not, then simply add the country name and country two letter name. (Note : We are treating the two letter country name as the value)

After the loop, I used some LinQ stuff to sort county names, and then iterate through the returned object to add the values in drop down list.

That’s it. Now you are not only limited to show the English name of the country but you can also show the native name. For example, the name of my country in English is “Islamic Republic of Pakistan” but the native name is پاکستان.

Also, you can get the following country information using RegionInfo

 

sc_clbn_1

Some developers are habitual of using country id along with the country name. if they still want to use some id to save the country information they can use the GeoId property of the RegionInfo.

CodeGain.com .net Community Portal

A guy named RRaveen  has setup a .net community portal named CodeGain and located on http://www.codegain.com.

Yet the portal is still in process but the content which he has posted is really useful and in fact it really help me in some places.

The best part about this portal is, it is not .net or asp.net specific. You will find articles  on desktop applications, Java, Oracle etc.

Previously, RRaveen had also written some articles on HighOnCoding.com and is active .net community so he is on a great task.

CodeGain

Show Loading Message in Asp.net AJAX

In this post, I will explain you how can we show Loading message in asp.net ajax without using Update Progress. Now some one may asked, why do I want to skip Update Progress ?

Well, there can be several reasons for this, fist of all you have to work on every single page, and on every update panel to get the update progress working.

There are basically three methods of meeting this requirement.

  1. Using Master Pages : A very smart way, but not all of us are using them .. right ?
  2. Extending Page Class  : A little harder but to me it is very elegant way.
  3. Extending Script Manager : Similar to the page class one, but implementation is comparatively simple.

The Basics:

Before I start with exploring the different approaches let me first create a ground by showing what things will be involve in creating a loading message.

I want the background to be grayed and displayed a simple loading text at the top, for that we need a style sheet, which will apply to the loading message div.  Create a stylesheet and call it style.css

.ModalProgressContainer
{
    z-index: 10005;
    position: fixed;
    cursor: wait; 
    top:0%; 
    background-color: #ffffff; 
    filter: alpha(opacity=50);
    opacity: 0.5;
    -moz-opacity: .5; 
    height: 100%;
    width: 100%;
    text-align: center; 
    
    } 
.ModalProgressContent
{
    padding: 10px; 
    border: solid 0px #000040; 
    font-weight: bold; 
    background-color:#ffffff;
    margin-top:300px;
} 

Now lets read and understand the following script.

var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);

// ----------------------------- //
// the below script will be saved in JS File, create a JS file and call it ajaxload.js and save the following script

function InitializeRequest(sender, args) {

    if (document.getElementById('ProgressDiv') != null)
       $get('ProgressDiv').style.display = 'block';
    else
        createContorl();
}

function EndRequest(sender, args) {

    if (document.getElementById('ProgressDiv') != null)
        $get('ProgressDiv').style.display = 'none';
    else
        createContorl();
}

function createContorl() {
    var parentDiv = document.createElement("div");
    parentDiv.setAttribute("class", "ModalProgressContainer");
    parentDiv.setAttribute("Id", "ProgressDiv");
 

    var innerContent = document.createElement("div");
    innerContent.setAttribute("class", "ModalProgressContent");
    var img = document.createElement("img");

    img.setAttribute("src", "/Images/Images/Loading.gif");

    var textDiv = document.createElement("div");
    textDiv.innerHTML = 'Loading....';

    innerContent.appendChild(img);
    innerContent.appendChild(textDiv);

    parentDiv.appendChild(innerContent);

    document.body.appendChild(parentDiv);

}

Notice,in the first three lines. We are getting the instance of PageRequestManager and then defining InitilizeRequest and EndRequest functions to display or hide the loading div. Where as, in createControl function we are simply writing DHTML, to be more specific there is no HTML of the loading div in our markup. So, we are writing that from JavaScript.

Also, note the that I have break down this script into two part by using comments. First is the declaration and second is definition of the functions.

note: The definition will take place on a seperate JS file where as the declaration need to be made in the page, under body markup.  Now we are all set to explore different approaches.

 

Using Master Pages :

A very simple approach, all you need to do is open your master page and paste the following lines in the head section.

<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="ajaxload.js"></script>

 

And in body, after form tag create a script section and paste the following JavaScript.

var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);

 

Notice it is the same declaration section which we have discussed above and that’s it you are done. All the content form of your web application should now display loading div on each partial postback.

 

Extending Page Class  :

For this, create a class file and call it ajaxPage and inherit it from System.Web.UI.Page and write the following code.

public class ajaxPage : Page
{
    protected override void OnLoad(EventArgs e)
    {
        //Include CSS File
        Page.Header.Controls.Add(new LiteralControl("<link href='style.css' rel='stylesheet' type='text/css' />"));


        //Include JS file on the page
        ClientScript.RegisterClientScriptInclude("ajaxload", ResolveUrl("~/ajaxload.js"));

        //Writing declaration script 
        String script = "var prm = Sys.WebForms.PageRequestManager.getInstance();";
        script += "prm.add_initializeRequest(InitializeRequest);";
        script += "prm.add_endRequest(EndRequest);";

        ClientScript.RegisterStartupScript(typeof(string), "body", script, true);

        base.OnLoad(e);
    }

}

 

Well, we have simply extend the System.Web.UI.Page into our own class and override OnLoad function to include the JS file and write the declaration markup.

Now, on the page code behind where you want to implement Loading message change the inherit namespace from System.Web.UI.Page to ajaxPage (make sure you namespace).

 

Extending Script Manager :

Now instead of extending page class we will extend Script Manager control and for that create a new class file and call it ScrtipManagerExt and write the following code.

public class ScriptManagerExt : ScriptManager
{
    protected override void OnLoad(EventArgs e)
    {

        //Include CSS File
        Page.Header.Controls.Add(new LiteralControl("<link href='style.css' rel='stylesheet' type='text/css' />"));

        RegisterClientScriptInclude(this, typeof(Page), "ajaload", ResolveClientUrl("~/ajaxload.js"));

        String script = "var prm = Sys.WebForms.PageRequestManager.getInstance();";
        script += "prm.add_initializeRequest(InitializeRequest);";
        script += "prm.add_endRequest(EndRequest);";

        RegisterStartupScript(this, typeof(Page), "ajaxtest", script, true);
        base.OnLoad(e);
    }
}

Almost the same thing we did in extend page approach, only the implementation will be change. Instead of using the old Script Manager we will use our new one. the include directive and markup will look like as below.

<%@ Register Assembly="Assembly" Namespace="namespace" TagPrefix="cc1" %>
<cc1:ScriptManagerExt ID="ScriptManagerExt1" runat="server">
</cc1:ScriptManagerExt>

 

That’s it we are done. I tried to make it simpler and show you every possible way I know of doing this task. Again, any approach selection will be on you and your project type. You can also download  the VS 2008 project file.

Migrate from WordPress to BlogEngine.net

In this post, I will explain how to migrate a blog running on Word Press (Self Hosted) to BlogEngine. But before I start let me say, that Word Press simply rocks. The reason why I plan to switch my blog is customization. Since I am a dotnet geek, I really have no great idea of what I can make out of Word Press using PHP and when it comes to Blogging in .net, I guess I made a very right decision to use BlogEngine. It is open source and included all the necessary blogging utilities.

The main thing which I want to migrate is as follows

  • Post
  • Categories
  • Tags
  • Comments

The moment I start, I was thinking to get some export / import tool. Then I came to know about BlogML. A format that is created to interchange content between different bloging engines. Natively, Word Press don’t support BlogML but Robert McLaws did great job on wiring this tool. Unfortunately, that tool didn’t work for me, for some reason it is keep giving me error.

Finally, I tried it in my own way. Since that blog was self hosted, I have access to mysql database engine through phpMyAdmin. Hence, I decided to export SQL of my related tables and data in MSSQL (TSQL) format.

 

  1. After the login into phpMyAdmin, go to the table list by selecting the databases comes at left.
  2. From the tab at the top select export.
  3. In the export group, select SQL and tables in my case it is wp_comments, wp_posts, wp_term_relationships, wp_term_taxonomy, and wp_term
  4. Now from the SQL Compatibility Mode, Select MSSQL. Save the file and your are complete.

Your selection screen should like like below.

sc_wp_to_be

 

Now open the generated SQL in MSSQL and before you run you might need to fix some column names and some data type issues of the table. But believe that is pretty easy. To help you more, please see the table creation script below

CREATE TABLE [dbo].[wp_comments](
    [comment_ID] [bigint] IDENTITY(1,1) NOT NULL,
    [comment_post_ID] [int] NOT NULL,
    [comment_author] [varchar](200) NOT NULL,
    [comment_author_email] [varchar](100) NOT NULL,
    [comment_author_url] [varchar](200) NOT NULL,
    [comment_author_IP] [varchar](100) NOT NULL,
    [comment_date] [datetime] NOT NULL,
    [comment_date_gmt] [datetime] NOT NULL,
    [comment_content] [text] NOT NULL,
    [comment_karma] [int] NOT NULL,
    [comment_approved] [varchar](20) NOT NULL,
    [comment_agent] [varchar](255) NOT NULL,
    [comment_type] [varchar](20) NOT NULL,
    [comment_parent] [bigint] NOT NULL,
    [user_id] [bigint] NOT NULL,
    [comment_subscribe] [varchar](1) NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [comment_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

CREATE TABLE [dbo].[wp_posts](
    [ID] [bigint] NOT NULL,
    [post_author] [bigint] NOT NULL,
    [post_date] [datetime] NOT NULL,
    [post_date_gmt] [datetime] NOT NULL,
    [post_content] [text] NOT NULL,
    [post_title] [text] NOT NULL,
    [post_category] [int] NOT NULL,
    [post_excerpt] [text] NOT NULL,
    [post_status] [varchar](20) NOT NULL,
    [comment_status] [varchar](20) NOT NULL,
    [ping_status] [varchar](20) NOT NULL,
    [post_password] [varchar](20) NOT NULL,
    [post_name] [varchar](200) NOT NULL,
    [to_ping] [text] NOT NULL,
    [pinged] [text] NOT NULL,
    [post_modified] [datetime] NOT NULL,
    [post_modified_gmt] [datetime] NOT NULL,
    [post_content_filtered] [text] NOT NULL,
    [post_parent] [bigint] NOT NULL,
    [guid] [varchar](255) NOT NULL,
    [menu_order] [int] NOT NULL,
    [post_type] [varchar](20) NOT NULL,
    [post_mime_type] [varchar](100) NOT NULL,
    [comment_count] [bigint] NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

CREATE TABLE [dbo].[wp_terms](
    [term_id] [bigint] IDENTITY(1,1) NOT NULL,
    [name] [varchar](200) NOT NULL,
    [slug] [varchar](200) NOT NULL,
    [term_group] [bigint] NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [term_id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

CREATE TABLE [dbo].[wp_term_relationships](
    [object_id] [bigint] NOT NULL,
    [term_taxonomy_id] [bigint] NOT NULL,
    [term_order] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [object_id] ASC,
    [term_taxonomy_id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
CREATE TABLE [dbo].[wp_term_taxonomy](
    [term_taxonomy_id] [bigint] IDENTITY(1,1) NOT NULL,
    [term_id] [bigint] NOT NULL,
    [taxonomy] [varchar](32) NOT NULL,
    [description] [text] NOT NULL,
    [parent] [bigint] NOT NULL,
    [count] [bigint] NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [term_taxonomy_id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

 

Please note  that it is just the schema script. All you data will be included in mysql generated SQL File which we have created before.

Now, we have all the required tables with data imported from Word Press to Blog Engine Db but we will fill Blog engine tables to show imported data. Lets first start with category.

 

Category:

There is no such table in wp_categories in word press instead it uses wp_term and wp_term_taxonomy to store categories where as in Blog engine we have a table called be_categories which hold categories information. So following query will dump the data from wp_terms , wp_taxonomy to be_categories.

INSERT INTO [dbo].[be_Categories]
           ([CategoryID]
           ,[CategoryName]
           ,[Description]
           ,[ParentID]
           ,[Slug])
     SELECT
           NEWID(),
           w1.[name],
           ('Posts in ' + w1.[name]) as Description,
           NULL, -- as I am not going to make any parent child relation now ...
           w1.[slug]
           FROM [BlogEngine].[dbo].[wp_terms] w1
  INNER JOIN  wp_term_taxonomy w2 on w1.term_id = w2.term_id and w2.taxonomy = 'category'
GO

Posts:

Now lets deal with posts, a very easy query because we have the post table in both the blogging engines. In Word Press it is wp_posts where as in Blog Engine it is be_post

INSERT INTO [dbo].[be_Posts]
      ([PostID]
      ,[Title]
      ,[Description]
      ,[PostContent]
      ,[DateCreated]
      ,[DateModified]
      ,[Author]
      ,[IsPublished]
      ,[IsCommentEnabled]
      ,[Raters]
      ,[Rating]
      ,[Slug])

SELECT newid(),
       post_title,
       post_excerpt,
       post_content,
       post_date,
       post_modified,
      'username',
      1,
      1,
      0,
      0,
      post_name
from wp_posts where post_type ='post'

 

Post Category Relation:

Now its time to set, which post have which categories. The table which is repsonsible for saving this information is called wp_term_relationship in Word Press and be_PostCategory in Blog Engine. See the following query.

select  wp.post_title ,wtr.name into #temp1 from wp_term_relationships wr inner join 
wp_term_taxonomy wt on wr.term_taxonomy_id = wt.term_taxonomy_id and wt.taxonomy = 'category' 
inner join wp_terms wtr on wt.term_id = wtr.term_id
inner join wp_posts wp on wr.object_id = wp.ID and post_type = 'post'



INSERT INTO [dbo].[be_PostCategory]
           ([PostID]
           ,[CategoryID])
select (select postId from be_Posts where Title= convert(nvarchar(max),t.post_title)),
(select CategoryID from  be_Categories where CategoryName = t.name) from #temp1 t

drop table #temp1

GO

I guess this query might need some explanation. See, in the top query I am getting the title of posts and name of categories and storing it to temp table.

Now come to the second part, here I insert new reords in be_postcategory based on the category names and post titles we filled before.

 

Tag:

In Blog Engine we have a table called be_PostTag which manage all the tags related stuff but in wordpress again involve all the tables containing wp_term. So, I write the following query which get the data from those tables and store it in Tags.

INSERT INTO [dbo].[be_PostTag]
         ([PostID]
         ,[Tag])
         
         
         
   SELECT
         (select postId from be_Posts where Title= convert(nvarchar(max),wp.post_title)) ,SUBSTRING(w1.[name], 1, 50)
         FROM [BlogEngine].[dbo].[wp_terms] w1
INNER JOIN  wp_term_taxonomy w2 on w1.term_id = w2.term_id and w2.taxonomy = 'post_tag'
inner join  wp_term_relationships wr on wr.term_taxonomy_id = w2.term_taxonomy_id
inner join  wp_posts wp on wr.object_id = wp.ID

 

 

Comment:

This one is comparatively easy. We have table called wp_comments in Word Press and be_postcomment in Blog Engine to manage the comments. Here is the final query.

INSERT INTO be_PostComment]
         ([PostCommentID]
         ,[PostID]
         ,[ParentCommentID]
         ,[CommentDate]
         ,[Author]
         ,[Email]
         ,[Website]
         ,[Comment]
         ,[Country]
         ,[Ip]
         ,[IsApproved])

SELECT 
      newId()
    ,(select postId from be_Posts where Title= convert(nvarchar(max),wpp.post_title)) as PostID
    ,(select postId from be_Posts where Title= convert(nvarchar(max),wpp.post_title)) as PostID
    ,[comment_date_gmt]
    ,[comment_author]
    ,[comment_author_email]
    ,[comment_author_url]
    ,[comment_content]
    ,NULL
    ,[comment_author_IP]
    ,1
    
FROM [wp_comments] wpc
INNER JOIN BlogEngine.dbo.wp_posts wpp on wpc.comment_post_ID = wpp.ID
where wpc.comment_approved = '1' 

 

Note : You might see some /r/n between some post and comments. Don’t get afraid of this, just replace “/r/n”  with “<br/>” on effected using Replace function of TSQL.

 

That’s how you can  import all the data from Word Press to Blog Engine and this is fairly a huge issue why people don’t move their blogs.  I have tried to explain the method by making it more simple, if you still face any issue please feel free to contact me.

Maintain Scroll Position With Asp.net Validation Controls.

Few days ago, when I was trying to put validation controls on a form which is at the bottom of the page. I noticed that each time Asp.net validation controls executed it reset the scroll position to top and the end user see no messages until page scroll back to the old position. Irritated :)

Problem:

Untitled

 

So, In this post I will demonstrate you how to maintain the scroll position of asp.net validation controls on a page. To start with an example, lets create a form like below

<div>
     <p>

 </p>
 <p>
     &nbsp;</p>
 <p>
     &nbsp;</p>

         <p>
             &nbsp;</p>

         <p>
             &nbsp;</p>
         <p>
             &nbsp;</p>
         <p>
             &nbsp;</p>
         <p>
             &nbsp;</p>
         <p>
             &nbsp;</p>
 <p>
     &nbsp;</p>
 <p>
     &nbsp;</p>
 <p>
     &nbsp;</p>
     <table class="style1">
         <tr>
             <td>
                 Name</td>
             <td>
                 <asp:TextBox ID="txtName" runat="server" autocomplete="off" Width="200"></asp:TextBox>
                 <asp:RegularExpressionValidator ID="revName" runat="server" 
                     ControlToValidate="txtName" Display="None" 
                     ErrorMessage="Please enter a valid name" 
                     ValidationExpression="(^([0-9-a-z-A-Z\\s+?\\.+?\\(+?\\)+?])+$)" 
                     ValidationGroup="grpTop"></asp:RegularExpressionValidator>
                     <asp:RequiredFieldValidator ID="rfvName" runat="server" 
                     ControlToValidate="txtName" Display="None" ErrorMessage="Please enter a name." 
                     SetFocusOnError="true" ValidationGroup="grpTop"></asp:RequiredFieldValidator>
             </td>
         </tr>
         <tr>
             <td>
                 Email Address</td>
             <td>
                 <asp:TextBox ID="txtUsername" runat="server" autocomplete="off" Text="" 
                     Width="200"></asp:TextBox>
                 <asp:RequiredFieldValidator ID="rfvEmailAddress" runat="server" 
                     ControlToValidate="txtUsername" Display="None" 
                     ErrorMessage="Please enter a valid email address." ValidationGroup="grpTop"></asp:RequiredFieldValidator>
                 <asp:RegularExpressionValidator ID="revEmail" runat="server" 
                     ControlToValidate="txtUsername" Display="None" 
                     ErrorMessage="Please key in a valid email address." SetFocusOnError="true" 
                     ValidationExpression="^([a-zA-Z0-9_'+*$%\\^&amp;!\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9:]{2,4})+$" 
                     ValidationGroup="grpTop"></asp:RegularExpressionValidator>
                 <asp:CustomValidator ID="valEmailAlreadyExists" runat="server" Display="None" 
                     ErrorMessage="Email address already exists" ValidationGroup="grpTop"></asp:CustomValidator>
             </td>
         </tr>
         <tr>
             <td>
                 Date Format</td>
             <td>
                 <asp:DropDownList ID="ddlDateFormat" runat="server" Width="200px">
                     <asp:ListItem>Select</asp:ListItem>
                     <asp:ListItem Text="dd/MM/yyyy" Value="dd/MM/yyyy">dd/MM/yyyy</asp:ListItem>
                     <asp:ListItem Text="MM/dd/yyyy" Value="MM/dd/yyyy">MM/dd/yyyy</asp:ListItem>
                     <asp:ListItem Text="dd/MM/yy" Value="dd/MM/yy">dd/MM/yy</asp:ListItem>
                     <asp:ListItem Text="MM/dd/yy" Value="MM/dd/yy">MM/dd/yy</asp:ListItem>
                 </asp:DropDownList>
                 <asp:RequiredFieldValidator ID="rfvDateFormat" runat="server" 
                     ControlToValidate="ddlDateFormat" Display="None" 
                     ErrorMessage="Please select date format." InitialValue="Select" 
                     SetFocusOnError="true" ValidationGroup="grpTop"></asp:RequiredFieldValidator>
             </td>
         </tr>
         <tr>
             <td>
                 &nbsp;</td>
             <td>
                 <asp:CheckBox ID="cbIsAdmin" runat="server" Checked="false" 
                     Text="Administrator?" />
                 &nbsp;<asp:CheckBox ID="cbResetPW" runat="server" Checked="false" 
                     Text="Reset Password" />
             </td>
         </tr>
         <tr>
             <td>
                 &nbsp;</td>
             <td>
                 <asp:Button ID="Button1" runat="server" Text="Submit Group 1"  ValidationGroup="grpTop"
                     onclick="Button1_Click" />
                 <asp:ValidationSummary ID="ValidationSummary1" runat="server" 
                     EnableClientScript="true" HeaderText="Fix the following issues :" 
                     ValidationGroup="grpTop" />
             </td>
         </tr>
         <tr>
             <td>
                 &nbsp;</td>
             <td>
                 &nbsp;</td>
         </tr>
     </table>
</div>

Notice that <p> tag which I have given in the above snippet to keep my form at the bottom of the page so that the scroll position problem can easily be demonstrated.

When you run the above snippet, you will realize that the page scroll position will lost as soon as you want to submit the form. If you try the page directive System.Web.Ui.Page.MaintainScrollPositionOnPostBack. Noting will change because by using this property Asp.net engine will take care of scroll position after post back. But we want it on client script. It means, we need to modify the mechanism on which asp.net validation controls executed.

To start with the understanding, I came across a very good article “Understanding ASP.NET Validation Library” by DeepakRaghavan. Which gives me the understanding of two methods. Page_ClientValidate and WebForm_OnSubmit and ultimately I need to modify them and bear in mind that these function will be written inside form tag not in title.

The idea is to use the bookmark to maintain the scroll bar. So lets modify both the functions respectively.

 

Page_ClientValidate:

   1: var bookMark = "#OtherBookMark";
   2: function Page_ClientValidate(validationGroup)
   3: {
   4:   
   5:   Page_InvalidControlToBeFocused = null;  
   6:   if (typeof(Page_Validators) == "undefined") {  
   7:   return true;  
   8:   }  
   9:   var i;  
  10:   for (i = 0; i < Page_Validators.length; i++) {  
  11:   ValidatorValidate(Page_Validators[i], validationGroup, null);  
  12:   }  
  13:   ValidatorUpdateIsValid();  
  14:   ValidationSummaryOnSubmit(validationGroup);  
  15:   Page_BlockSubmit = !Page_IsValid;  
  16:   
  17:   if (validationGroup == "grpTop")
  18:   {
  19:       bookMark = "#addForm";
  20:   }
  21:   else
  22:   {
  23:       bookMark = "#OtherBookMark";
  24:   }
  25:   return Page_IsValid;  
  26: }

Description:

Line No 1.       A variable that will hold the bookmark name

Line No 2-14   The default function implementation (We have simple nothing to do with it… simply copy / paste)

Line No 15- 22 Since we can have multiple forms on a page, that is why it is better to keep track that which validation group is called and decide the bookmark name accordingly.

 

Now instead of modifying WebForm_OnSubmit, let’s first create a following function

SubmitAction:

 

   1: function SubmitAction() {
   2: if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false)
   3:   {
   4:           var hashIndex = location.href.indexOf("#");
   5:           
   6:           if (hashIndex > -1) 
   7:           {
   8:               var loc = location.href.substring(0,hashIndex);
   9:               location.href = loc + bookMark;
  10:           }
  11:           else
  12:           {
  13:               location.href = location + bookMark;
  14:           }
  15:           
  16:           return false;
  17:   }
  18:   else
  19:   {
  20:       return true;
  21:   }
  22: }

 

Description:

Well, the function is very simple and don’t really need line by line commentary.
We are checking if the validation is fail, set the bookmark. other wise just let it go.

 

WebForm_OnSubmit:

Now we will call the above SubmitAction function inside WebForm_OnSubmit. To inject this function you need to write the following lines on the Page_Load

   1: if (!Page.ClientScript.IsOnSubmitStatementRegistered("keySubmitAction"))
   2: {
   3:     Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "keySubmitAction", "return SubmitAction();");
   4: }

System.Web.UI.Page.ClientScript.RegisterOnSubmitStatement is actually used to inject your script inside WebForm_OnSubmit. To be more specific, the first lines will be yours :).

and if you notice the Line No : 3 I used return statement which means as soon as WebForm_OnSubmit will execute my function (SubmitAction) will run first and then return the execution out… no more processing on WebForm_OnSubmit.

Now when you look at the view source of your browser you will see some thing similar to the following.

sc_mvc

Ok, now we only need to setup our bookmark.

Just give the id “addForm” to the table or div inside which the validation summary control is placed. that’s it.  However, you can download the VS 2008 Solution from here.

How to show and select month/year in Calendar Extender

In this post I will explain you, How to make calendar extender control to show month / year view by default and instead of selecting dates how can we use calendar extender to select months.

Before I start, let me say that I got extensive support from this forum post http://forums.asp.net/t/1349086.aspx. Thanks to Zhi-Qiang Ni, but the way he follow was a little bit lengthy. However, all credit still goes to him because I gain the exact idea from his post.

Let me start by creating a calendar extender control and attach it to a textbox.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc1:CalendarExtender ID="TextBox1_CalendarExtender" runat="server" OnClientHidden="onCalendarHidden"  OnClientShown="onCalendarShown" BehaviorID="calendar1"
    Enabled="True" TargetControlID="TextBox1">
</cc1:CalendarExtender>


Now, in extender markup, notice onClientHidden and OnClientShown event which I implemented as below.

function onCalendarShown() {
 
     var cal = $find("calendar1");
     //Setting the default mode to month
     cal._switchMode("months", true);
     
     //Iterate every month Item and attach click event to it
     if (cal._monthsBody) {
         for (var i = 0; i < cal._monthsBody.rows.length; i++) {
             var row = cal._monthsBody.rows[i];
             for (var j = 0; j < row.cells.length; j++) {
                 Sys.UI.DomEvent.addHandler(row.cells[j].firstChild, "click", call);
             }
         }
     }
 }
 
 function onCalendarHidden() 
 {
     var cal = $find("calendar1");
     //Iterate every month Item and remove click event from it
       if (cal._monthsBody) {
         for (var i = 0; i < cal._monthsBody.rows.length; i++) {
             var row = cal._monthsBody.rows[i];
             for (var j = 0; j < row.cells.length; j++) {
                 Sys.UI.DomEvent.removeHandler(row.cells[j].firstChild,"click",call);
             }
         }
     }
 
 }

Pretty simple, In onCalendarShown method I just set the default mode to month and then iterate the control to get month item and attach on click event to it. So that, it will not go further to show us dates of that month and select the first day of that month instead.

Where as, In onCalendarHidden I am simply detaching the click event from month items. Now notice the last parameter of Sys.UI.DomEvent.addHandler function, it is the name of the function which will do the rest of the magic as below.

function call(eventElement)
        {
            var target = eventElement.target;
            switch (target.mode) {
            case "month":
                var cal = $find("calendar1");
                cal._visibleDate = target.date;
                cal.set_selectedDate(target.date);
                cal._switchMonth(target.date);
                cal._blur.post(true);
                cal.raiseDateSelectionChanged();
                break;
            }
        }

Here we are simply selecting the month as the selected date of calendar control. and finally the control will look like as below.

cal_extender

You can get the source code from here :
http://cid-cdbfe38dc780f729.skydrive.live.com/self.aspx/.Public/Calendar%20Extender%20Month.zip

PMP Preparation Blog

One of my friend Sarim Shehkhani has created a blog on PMP Preperation. I red that blog and found it very useful for anyone who is planning to get PMP. Here is the URL : http://pmpforidiots.blogspot.com/Sarim Shehkhani is him self a PMP and got 7+ years experience in Project Management and he is the one who introduces Visual Studio Team Foundation System to me. So, I am looking forward to get some more professional project management skils from PMP for Idiots.