Thursday, July 2, 2015

Convert Gridview Rows To Column (Transpose Gridview)


In this article i will show how to convert Gridview Rows to Column in C#.Lets begin by adding 2 GridViews to a page and a button.Now we need to create a DataTable .For Simplicity i am adding data to datatable in gridbind Method and populating the gridview with that data manually you can fill datatable with database.Store this datatable in ViewState.Now we call this method in page load.
For converting GridView Row to column i have created a method Transpose.Now what we have to do in transpose method.
1)We need to create a new datatable newdt.Retrieve the old datatable from viewstate .The number of columns in new datatable newdt will be equal to number of rows in dt.
2)Add Columns to the new datatable newdt(Column Name is passed as blank ).
3) Create a datarow dr .Iterate through all columns and add for each column value get all the values of the rows in old datatable dt and store it in dr.
4)Add Datarow dr to newdt. Now Add Click event for the button and call the transpose method.

Here is the code


<style type="text/css">
        .header {
            padding:5px;background-color:#7ac0da; font-weight:bold;
        }
      .header content-wrapper table tr  td {
            border:dotted 1px solid !important;
        }
    </style>
    <br />
<div style="text-align: center;">
<asp:gridview alternatingrowstyle-backcolor="#ccffff" bordercolor="Gray" gridlines="Both" headerstyle-backcolor="#7ac0da" headerstyle-bordercolor="Gray" headerstyle-cssclass="header content-wrapper" id="grdNormal" runat="server">
    </asp:gridview>
    </div>
<div style="text-align: center;">
<asp:linkbutton id="lnkConvert" onclick="lnkConvert_Click" runat="server"><img src="Images/down.png" style="width: 50px;" /></asp:linkbutton>
    </div>
<div style="text-align: center;">
<asp:gridview bordercolor="Gray" gridlines="Both" headerstyle-bordercolor="Gray" id="grdTranspose" onrowcreated="grdTranspose_RowCreated" runat="server" showheader="false">
    </asp:gridview>
    </div>
</div>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; namespace GridTranspose { public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { grdibind(); } } protected void grdibind() { DataTable dt = new DataTable(); dt.Columns.Add("EmpId", typeof(string)); dt.Columns.Add("EmpName", typeof(string)); dt.Columns.Add("City", typeof(string)); DataRow dr1= dt.NewRow(); dr1[0] = "L1Z 5F4"; dr1[1] = "Nathaniel"; dr1[2] = "Ilbono"; dt.Rows.Add(dr1); DataRow dr2 = dt.NewRow(); dr2[0] = "B7F 4U4"; dr2[1] = "Ross"; dr2[2] = "Dover"; dt.Rows.Add(dr2); DataRow dr3 = dt.NewRow(); dr3[0] = "R9C 1T9"; dr3[1] = "Patrick"; dr3[2] = "Edam"; dt.Rows.Add(dr3); ViewState["GridData"] = dt; grdNormal.DataSource = dt; grdNormal.DataBind(); } protected void lnkConvert_Click(object sender, EventArgs e) { Transpose(); } protected void Transpose() { DataTable dt = (DataTable)ViewState["GridData"]; DataTable newdt = new DataTable(); //Create New Columns( count of columns will be equal to number of rows including header for (int i = 0; i <= dt.Rows.Count; i++) { //Column Name string is not specified because column name will come in rows at start newdt.Columns.Add(""); } //Now Iterate through old datatable and fill new datatable //Create a new row in New DataTable for (int k = 0; k < dt.Columns.Count; k++) { DataRow newdr = newdt.NewRow(); //Assign first column Value in NewDatatable with column name of old table newdr[0] = dt.Columns[k].ColumnName.ToString(); for (int j = 0; j < dt.Rows.Count; j++) { newdr[j + 1] = dt.Rows[j][k].ToString(); } newdt.Rows.Add(newdr); } grdTranspose.DataSource = newdt; grdTranspose.DataBind(); } protected void grdTranspose_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Cells[0].CssClass = "header"; } } } }
Note:-Actually here we are transposing data table and binding to gridview.

Thursday, June 25, 2015

C# equivalent of Mid Function & Mid Statement in VB6

Very often when migrating traditional windows application written in VB6  ,we may come across the inbuild functions which were available in VB6 but not available in C# One such function is Mid Function.
 Visual Basic has a Mid function and a Mid statement. These elements both operate on a specified number of characters in a string, but the Mid function returns the characters while the Mid statement replaces the characters.

Mid Function has following parameters

str

Required. String expression from which characters are returned.
Start
Required. Integer expression. Starting position of the characters to return. If Start is greater than the number of characters in str, the Mid function returns a zero-length string (""). Start is one based.
Length
Optional. Integer expression. Number of characters to return. If omitted or if there are fewer than Length characters in the text (including the character at position Start), all characters from the start position to the end of the string are returned.

Mid Statement
  Replaces a specified number of characters in a String variable with characters from another string.
Mid Statement has following parameters

Target
Required. Name of the String variable to modify.
Start
Required. Integer expression. Character position in Target where the replacement of text begins. Start uses a one-based index.
Length
Optional. Integer expression. Number of characters to replace. If omitted, all of String is used.
StringExpression
Required. String expression that replaces part of Target.
Here is the C# version for the same code.
/// <summary>
    /// Mid Statement and Mid Statement in C#     /// </summary>     public static class strMid     {         /// <summary>         /// This is Equivalent to Mid Statement in VB6         /// </summary>         /// <param name="input"> String to be altered.</param>         /// <param name="index"> Location of character in string.</param>         /// <param name="newChar"> Character to be replaced.</param>         /// <returns></returns>         public static  string Mid(string input, int index, char newChar)         {             if (input == null)             {                 throw new ArgumentNullException("input");             }             char[] chars = input.ToCharArray();             chars[index-1] = newChar;             return new string(chars);         }         /// <summary>         /// This is equivalent to Mid Function in VB6         /// </summary>         /// <param name="s"> String to Check.</param>         /// <param name="a">Position of Character</param>         /// <param name="b">Length </param>         /// <returns></returns>         public static string Mid(string s, int a, int b)         {             string temp = s.Substring(a - 1, b);             return temp;         }             }

Sunday, September 28, 2014

Creating RSS Feeds using Repeater Control

RSS Feeds are XML Formatted documents  using which updated data can be read from different website without actually visiting it.

To create a rss feed in asp.net all we need is to follow following steps:-
1)Create New Website in Visual Studio.
2)In WebForm Drag a Repeater Control.
3)In the Page Directive add ContentType="text/xml".

Feeds.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Feeds.aspx.cs" Inherits="_Default" %>
<asp:Repeater id="rptFeeds" runat="server" onitemdatabound="rptFeeds_ItemDataBound" >
<HeaderTemplate>
<rss version="2.0">
  <channel>
    <title>Test Feeds</title>
    <description></description>   
    <copyright></copyright>  
</HeaderTemplate>
<ItemTemplate>
  <blog>
    <title><%# Eval("Blog_Title")%></title>
<url><%# Eval("Blog_Url")%></url>
    <date><%# Eval("Blog_date")%></date>   
   
    <description><%# Eval("Blog_Description")%></description>
  </blog>
</ItemTemplate>
<FooterTemplate>
<asp:Literal ID="ltlEmpty" runat="server" Visible="false" ></asp:Literal>
  </channel>
</rss>   
</FooterTemplate>
</asp:Repeater>

Now in code behind file we will get data from database and bind the repeater.
Feeds.aspx.cs
public partial class Feeds : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["blogConnection"].ConnectionString);
      
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            { feedsbind(); }
        }
        protected void feedsbind()
        {
            SqlCommand cmd = new SqlCommand("Select * from Blogs", conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            rptFeeds.DataSource = ds;
            rptFeeds.DataBind();
        }

protected void rptFeeds_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {

            if (e.Item.ItemType == ListItemType.Footer)
            {
if(rptFeeds.Items.Count==0)
{
                Literal ltlEmpty= (Literal)(e.Item.FindControl("ltlEmpty"));
                ltlEmpty.Text="No Blogs Found.";
ltlEmpty.Visible=true;
               }
            }
        }
    }

Note:- Above i have used Literal instead of label since Label will generate HTML ,but we only need to show plain text.

Wednesday, April 16, 2014

Url Rewriting using Global.asax file and System.Web.Routing

URL rewriting is the process of accepting the web request and redirect it to some resource.Most often url rewriting is used for making our urls SEO Friendly.
We can rewrite our Urls either by using

1) Http Context  in Application_BeginRequest in Global.asax file .
2) Use System.Web.Routing to register routes in routes collection and then redirect based on those routes.

Using Http Context:-

We can rewrite url using http context.Whenever a request is made to the server,application begin request is fired and in that we can get the path requested and redirect to that path.

protected void Application_BeginRequest(object sender,EventArgs e)
  {
HttpContext context = HttpContext.Current;
                string path = context.Request.Path.ToLower();
                if(path.Equals("/AP"))
                {
                    context.RewritePath("~/AndhraPradesh.aspx");
                }
  }

Using System.Web.Routing:-

To register and routes in routes collection the first most important step is to import System.Web.Routing in Global.asax file.

<%@ Import Namespace="System.Web.Routing" %>

Then we have to declare a method a method to register routes and call that method on
Application_Start


void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup
        RegisterRoutes(RouteTable.Routes);
        
    }
public static void RegisterRoutes(RouteCollection routes)
    {

        routes.MapPageRoute("", "", "~/Default.aspx");
        
        routes.MapPageRoute("", "seo/", "~/seo.aspx");
     }

The  various parameters in MapPageRoute are
routeName
Type: System.String
The name of the route.
routeUrl
Type: System.String
The URL pattern for the route.
physicalFile
Type: System.String
The physical URL for the route.
checkPhysicalUrlAccess
Type: System.Boolean
A value that indicates whether ASP.NET should validate that the user has authority to access the physical URL (the route URL is always checked). This parameter sets the PageRouteHandler.CheckPhysicalUrlAccess property.
defaults
Type: System.Web.Routing.RouteValueDictionary
Default values for the route parameters.

Note:-
1)We can ignore certain files from url rewrite by just passing them in Ignore method

routes.Ignore("{*alljs}", new { alljs = @".*\.js(/.*)?" });
        routes.Ignore("{*allpng}", new { allpng = @".*\.png(/.*)?" });
        routes.Ignore("{*allcss}", new { allcss = @".*\.css(/.*)?" });

The above code will ignore all js,css,png files from url rewrite.
2)We can also pass parameters as query string to a page when we do url rewrite
Suppose our page url looks like
product.aspx?id=C102

then we can rewrite it as
/product/C102

To achieve such type of Url rewrite we have to add route like this
 
routes.MapPageRoute("", "product/{Id}", "~/product.aspx");
        

In the product.aspx page we have to add reference to the System.Web>Routing Namespace and we can collect that id using RouteData.Values Method of Page class
if (Page.RouteData.Values["Id"] != null)
            {
                string id = Page.RouteData.Values["Id"].ToString();
}

Thursday, April 10, 2014

How to use connection string from config file in LINQ To SQL

Most of the time when we are working with Linq To SQL We come across a situation when our application takes the connection string of the database which we used while dragging tables or procedures on dbml designers.But this is not the right way to do.So what we can do in such situation??
Possible answer may be change the connection string in dbml.designer.cs.
But there is another work around and possibly the better approach.We should not modify our dbml designer.cs file manually(the reason is that it will be rewritten when we edit/add a table.Now what is to be done next--

1) Right click on the empty space in designer and view the properties and Set the connection property of your .dbml file to “none”



 2)Now add a separate partial class with same name as in dbml file(in the above example it will be "DataClassesDataContext" with a default parameter less constructor.

public partial class DataClassesDataContext
{
  public DataClassesDataContext() : base(ConfigurationManager.ConnectionStrings["ConnectionString Name"].ConnectionString)
  {
    OnCreated();
  }
}

3) Set the connection string in web.config file

<connectionStrings>
  <add name="democonnection"
  connectionString="Data Source=Rajeev-PC;Initial Catalog=testdb;Persist Security Info=True;Integrated Security="true"
  providerName="System.Data.SqlClient" />

</connectionStrings>

Note:The down side to this approach is that you have to set the Connection property to none every time  you add new objects to the dbml file, but it's not as bad as having to manage the connection string in multiple places.

Tuesday, February 18, 2014

Enable copy & right -click in a webpage that is copy protected.

Many a times when we visit a webpage and try to copy some content from the page ,we are unable to copy that content. There are two possibilities that you are unable to copy.
1)Webpage has disabled the right click of the webpage.
2)The webpage has disabled select of the webpage.
Now here is the solution to these scripts .

For enabling right click just copy the below script and paste it in browser url of the same page

javascript:void(document.oncontextmenu=null)

For enabling copy just copy the below script and paste in browser url of same page


javascript:void(document.onselectstart=true)

Monday, February 17, 2014

WCF Web HTTP Service Help Page and Show Exception Detail when calling methods of WCF Service

WCF Help Page:

This functionality is turned off by default. When a user browses to a WCF WEB HTTP service and appends "/Help" on to the end of the a help page like the following is displayed.
The user can then click any method listed in the help page and detailed page for that operation is displayed showing more information about the method, including message formats and example responses. To enable the WCF WEB HTTP Help age in configuration, add an endpoint behavior with a <webhttp>  element, set enableHelp to true.


      <endpointBehaviors>

        <behavior name="Jsonbehavior">

          <webHttp helpEnabled="true" />

        </behavior>

      </endpointBehaviors>


Show Errors in WCF:

To show exact error in WCF Hosted on IIS we need to set service debug includeExceptionDetailInFaults attribute to true.
    <behavior name="Service1">

                    <dataContractSerializer maxItemsInObjectGraph="2147483646" />

          <serviceMetadata httpGetEnabled="true" />

          <serviceDebug includeExceptionDetailInFaults="true" />



        </behavior>