Saturday, January 1, 2011

URL Rewrite Using ASP.net 3.5 or Over

The blog will explin how we can achieve url rewriting in ASP.net 3.5 or Over.

Step 1 : Create a helper class title "SiteRouteHandler.cs".


#region System
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Routing;
using System.Web.Compilation;
#endregion

namespace UrlRewrite
{
/// <summary>
/// Handler for routing
/// </summary>
public class SiteRouteHandler : IRouteHandler
{
#region Properties

/// <summary>
/// Page Virtual Path
/// </summary>
public string PageVirtualPath { get; set; }

#endregion

#region Implements IRouteHandler

/// <summary>
/// Gets the handler in return
/// </summary>
/// <param name="requestContext"></param>
/// <returns></returns>
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
Page page = BuildManager.CreateInstanceFromVirtualPath(PageVirtualPath, typeof(Page)) as Page;
foreach (var item in requestContext.RouteData.Values)
{
HttpContext.Current.Items["qparam." + item.Key] = item.Value;
}
return page;
}

#endregion
}
}


Step 2 : In global.asax.cs file declare the routes you want to give to the pages with a particular pattern. Use the SiteRouteHandler.cs class for getting the params mentioned in the route pattern. The "{ID}", "{AspxPage}" and "{PageNumber}" are the dynamic values which can be used on our aspx page for manupulation. So if the link is "http://localhost/UrlReWrite/blog/123/This-is-a-blog.aspx/32". Than according to the pattern "123" is {ID}, "This-is-a-blog" is {AspxPage} and 32 is {PageNumber}. "~/Blog.aspx" is the actual page.


using System.Web.Routing;
protected void Application_Start(object sender, EventArgs e)
{
//Clears all route
RouteTable.Routes.Clear();
//Handles the route
RouteTable.Routes.Add("Blog", new Route("blog/{ID}/{AspxPage}.aspx/{PageNumber}", new SiteRouteHandler() { PageVirtualPath = "~/Blog.aspx" }));
}




Step 3 : Now on Blog.aspx we can use params to retrieve the data.


/// <summary>
/// The blog id from the query string
/// </summary>
private int BlogID
{
get
{
if (Context.Items["qparam.ID"] == null)
{
return 0;
}
return Convert.ToInt32(Context.Items["qparam.ID"]);
}
}

/// <summary>
/// The blog id from the query string
/// </summary>
private string AspxPage
{
get
{
if (Context.Items["qparam.AspxPage"] == null)
{
return string.Empty;
}
return Context.Items["qparam.AspxPage"].ToString();
}
}

/// <summary>
/// The Page Number
/// </summary>
private int PageNumber
{
get
{
if (Context.Items["qparam.PageNumber"] == null)
{
return 0;
}
return Convert.ToInt32(Context.Items["qparam.PageNumber"]);
}
}


Please let me know about your thoughts.

Thursday, November 18, 2010

Make MVC working with Virtual Directory

I have referred this site to get the MVC applicaiton working using Virtual directory. There is no direct way to get the MCV working on the IIS. It can run through port by default but making it work with IIS Virtual Directory follow this link.

http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx

Wednesday, October 20, 2010

Read XML in SQL Server 2005/2008

Can read an xml file format in SQL Server 2005 2005/2008

To read the attributes use "@AttributeName"

To read the node under it use "NodeName[0]"

Just copy/patse the below given stuff in sql server and run it.


--//---------- Declare ----------//
DECLARE @xmlTest XML
SET @xmlTest = '<GUIDs>
<GUID Temp="a">1</GUID>
<GUID Temp="a">2</GUID>
<GUID Temp="a">3</GUID>
<GUID Temp="b">4</GUID>
<GUID Temp="b">5</GUID>
</GUIDs>'


--//---------- Set Query ----------//
SELECT Temp , MAX(GUID) FROM (
SELECT xmlTest.value('.', 'INT') AS GUID , xmlTest.value('@Temp', 'VARCHAR(36)') AS Temp
FROM @xmlTest.nodes('/GUIDs/GUID') d(xmlTest) ) AS A
GROUP BY Temp

Wednesday, August 18, 2010

Apply group by clause on Datatable in C#

The blog will explain how to retrieve a data table using C# using a group by clause.
//The way to call the Group By Function
//Argument 1 = Data table in IMAGE 1
//Argument 2 = The fields you want for the data table returned
//Argument 3 = The field you want to group by
//Argument 4 = The function you want to do It can be either SUM, COUNT, AVG etc.
DataTable dtGroupedBy = GetGroupedBy(dt, "CodeName,Quantity,Current", "CodeName", "Sum");
/// <summary>
/// The group by clause for Data Table
/// </summary>
/// <param name="dt">The main data table to be filtered with the Group By.</param>
/// <param name="columnNamesInDt">The Fields sent seperated by commas. EG "Field1,Field2,Field3"</param>
/// <param name="groupByColumnNames">The column name which should be used for group by.</param>
/// <param name="typeOfCalculation">The calculation type like Sum, Avg Or Count.</param>
/// <returns></returns>
private DataTable GetGroupedBy(DataTable dt, string columnNamesInDt, string groupByColumnNames, string typeOfCalculation)
{
    //Return its own if the column names are empty
    if (columnNamesInDt == string.Empty || groupByColumnNames == string.Empty)
    {
        return dt;
    }

    //Once the columns are added find the distinct rows and group it bu the numbet
    DataTable _dt = dt.DefaultView.ToTable(true, groupByColumnNames);

    //The column names in data table
    string[] _columnNamesInDt = columnNamesInDt.Split(',');

    for (int i = 0; i < _columnNamesInDt.Length; i = i + 1)
    {
        if (_columnNamesInDt[i] != groupByColumnNames)
        {
            _dt.Columns.Add(_columnNamesInDt[i]);
        }
    }


    //Gets the collection and send it back
    for (int i = 0; i < _dt.Rows.Count; i = i + 1)
    {
        for (int j = 0; j < _columnNamesInDt.Length; j = j + 1)
        {
            if (_columnNamesInDt[j] != groupByColumnNames)
            {
                _dt.Rows[i][j] = dt.Compute(typeOfCalculation + "(" + _columnNamesInDt[j] + ")", groupByColumnNames + " = '" + _dt.Rows[i][groupByColumnNames].ToString() + "'");
            }
        }
    }

    return _dt;
}


Screen shots to show the achievements


Image 1 :

Image 2 :

Related Blog

Apply "Multiple" column Group By on DataTable in C#

Wednesday, August 4, 2010

SQL 2005/2008 Query to retrieve a comma seperated single row from a table.

SQL 2005/2008 Query to retrieve a comma seperated single row from a table.




This query will help to combine all records in a single row result with comma seperation. I have taken both type string as well as integers.



-- Take a table variable
DECLARE @TBL as TABLE(VAL1 INT, VAL2 VARCHAR(10));
-- POPULATE THE VALUES
INSERT INTO @TBL VALUES(10,'A');
INSERT INTO @TBL VALUES(20,'B');
INSERT INTO @TBL VALUES(30,'C');
INSERT INTO @TBL VALUES(40,'D');
INSERT INTO @TBL VALUES(50,'E');
-- Show the values in tables
SELECT * FROM @TBL;

-- Declare variables
DECLARE @CommaValsInt AS VARCHAR(MAX);
DECLARE @CommaValsString AS VARCHAR(MAX);

-- Gets the sql query with Comma Seperated
SELECT
@CommaValsInt = COALESCE(@CommaValsInt + ',', '') + CAST(VAL1 AS VARCHAR(10))
, @CommaValsString = COALESCE(@CommaValsString + ''',''', '''') + VAL2
FROM
@TBL;
-- Show the result
SELECT @CommaValsInt AS ResultForInt , (@CommaValsString + '''') ResultForString