Showing posts with label Asp.Net. Show all posts
Showing posts with label Asp.Net. Show all posts

Friday, April 10, 2015

JSON to Dataset conversion

Sometimes we need to convert json to dataset in that case following code snippet will help us.

Code snippet :

public DataSet ConvertJsonToDataSet(string jsonString)
        {
                XmlDocument xd = new XmlDocument();
                jsonString = "{ \"myrootNode\": {" + jsonString.Trim().TrimStart('{').TrimEnd('}') + "} }";
                xd = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonString);
                DataSet ds = new DataSet();
                ds.ReadXml(new XmlNodeReader(xd));
                return ds;
          }

Happy Coding !!

Tuesday, March 31, 2015

Filename convenventions while uploading files.

Issue:

When you attempt to create, save, or rename a file, folder, or shortcut, you may receive one of the following error messages:
A filename cannot contain any of the following characters:\ / : * ? " < > | or This filename is not valid

Resolution :
To create, save, or rename a file, folder, or shortcut, use a valid character, dont use following charachters:
 \ / : * ? " < > |
Characters that are valid for naming files, folders, or shortcuts include any combination of letters (A-Z) and numbers (0-9),
plus the following special characters:
   ^   Accent circumflex (caret)
   &   Ampersand
   '   Apostrophe (single quotation mark)
   @   At sign
   {   Brace left
   }   Brace right
   [   Bracket opening
   ]   Bracket closing
   ,   Comma
   $   Dollar sign
   =   Equal sign
   !   Exclamation point
   -   Hyphen
   #   Number sign
   (   Parenthesis opening
   )   Parenthesis closing
   %   Percent
   .   Period
   +   Plus
   ~   Tilde
   _   Underscore


Happy Coding !! 

Encode Web Output for ASP.NET code that generates HTML using some input

If ASP.NET code that generates HTML using some input, we need to evaluate appropriate action for application.
Encoding output methods:

  •    Encode HTML output.
  •    Encode URL output.
  •    Filter user input.


Encode HTML Output:


If you write text output to a Web page and you do not know if the text contains HTML special characters (such as <, >, and &), pre-process the text by using the HttpUtility.HtmlEncode method as shown in the following code example.
Do this if the text came from user input, a database, or a local file.
 
    Response.Write(HttpUtility.HtmlEncode(Request.Form["stringvalue"]));


Encode URL Output:


If you return URL strings that contain input to the client, use the HttpUtility.
UrlEncode method to encode these URL strings as shown in the following code example.

    Response.Write(HttpUtility.UrlEncode(urlString));

Filter User Input:


If you have pages that need to accept a range of HTML elements, for example through some kind of rich text input field, you must disable ASP.NET request validation for the page.
If you have several pages that do this, create a filter that allows only the HTML elements that you want to accept.
A common practice is to restrict formatting to safe HTML elements such as bold (<b>) and italic (<i>).
To safely allow restricted HTML input Disable ASP.NET request validation by the adding the ValidateRequest="false" attribute to the @ Page directive.
Encode the string input with the HtmlEncode method.
Use a StringBuilder and call its Replace method to selectively remove the encoding on the HTML elements that you want to permit.

e.g.
<%@ Page Language="C#" ValidateRequest="false"%>
StringBuilder sb = new StringBuilder(HttpUtility.HtmlEncode(htmlInputTxt.Text));
    sb.Replace("&lt;b&gt;", "<b>");
    sb.Replace("&lt;/b&gt;", "");
    sb.Replace("&lt;i&gt;", "<i>");
Response.Write(sb.ToString());

New <%: %> Code Nugget Syntax:

With ASP.NET 4 we are introducing a new code expression syntax (<%:  %>) that renders output like <%= %> blocks do – but which also automatically HTML encodes it before doing so.  This eliminates the need to explicitly HTML encode content like we did in the example above.  Instead, you can just write the more concise code below to accomplish the exact same thing:
e.g.
<div>
<%: Model.Content %>
</div>


Happy Coding !! 

Defending Against XML Bombs

Using System.Xml.XmlDocument/XmlDataDocument LoadXml() method is potentially unsafe, replace with the Load().The easiest way to defend against all types of XML entity attacks is to simply disable altogether the use of inline DTD schemas in your XML parsing objects.

In .NET Framework versions 3.5 and earlier, DTD parsing behavior is controlled by the Boolean ProhibitDtd property found in the System.Xml.XmlTextReader and System.Xml.XmlReaderSettings classes. Set this value to true to disable inline DTDs completely:

e.g.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ProhibitDtd = true;
XmlReader reader = XmlReader.Create(xmlstream, settings);
The default value of ProhibitDtd in XmlReaderSettings is true, but the default value of ProhibitDtd in XmlTextReader is false, which means that you have to explicitly set it to true to disable inline DTDs.
In .NET Framework version 4.0 DTD parsing behavior has been changed. The ProhibitDtd property has been deprecated in favor of the new DtdProcessing property. You can set this property to Prohibit (the default value) to cause the runtime to throw an exception if a <!DOCTYPE> element is present in the XML:

e.g.
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
XmlReader reader = XmlReader.Create(xmlstream, settings);


Happy Coding!! 

Redirecting non-www requests to www requests

Redirection of Non-WWW domain to WWW (301 Redirection – permanent) is very important for ranking on search engine like Google.

The Problem is that the Google search consider http://domain.com to be a different domain than http://www.domain.com. so it makes the difference in search engine back links because you have made it with and without www prefix.

It is better to have every link use exactly the same form of your domain. for this purpose, it is common to redirect request from non-www to www.

We can do it in asp.net by many ways but I mentioned 2 solutions below -

1. web.config : 

       It is most common practice to do the redirection from non-www to www because we don’t have the IIS access on shared hosting environment.

Make sure you replace example.com with the name of your domain.

<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Redirect to WWW" stopProcessing="true">
          <match url=".*" />
          <conditions>
            <add input="{HTTP_HOST}" pattern="^example.com$" />
          </conditions>
          <action type="Redirect" url="http://www.example.com/{R:0}"
                  redirectType="Permanent" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>


2. Global.asax.cs  : 

          If you wish to do it from within your application, use the Application_BeginRequest in Global.asax.cs to intercept the request and do a 301 (permanent) redirection on the url.

 NOTE - you will need to set up the bindings of the site in IIS to accept both the www.domain.com and domain.com host names.

protected void Application_BeginRequest(object sender, EventArgs ev)
{
   string FromHomeURL = "http://www.example.com";
   string ToHomeURL = "http://example.com";
           
   if(HttpContext.Current.Request.Url.ToString().ToLower().Contains(FromHomeURL))
   {
       HttpContext.Current.Response.Status = "301 Moved Permanently";
       HttpContext.Current.Response.AddHeader("Location",
       Request.Url.ToString().ToLower().Replace(FromHomeURL, ToHomeURL));
   }
}

Happy Coding !! 

Tuesday, February 17, 2015

Read all keys and values from resource file

I have added Resource1.resx file in my project. This reosurce file contains some key - value entries.

Scenario : Suppose you have localized country list and you have stored localized country list in resource file for performance reason. You can store localized list in sql table but if you want to avoid database hit and read it on server side.


This function reads Resource1.resx file and reads all keys of that resource file.

 public static List<string> GetAllResourceKeyStrings()
        {
            List<string> resourceKeyStrings = new List<string>();
             ResourceSet resourceSet = null;
         
            resourceSet = Resource1.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true);
         
         
            IDictionaryEnumerator Myenumerator = resourceSet.GetEnumerator();
            while (Myenumerator.MoveNext())
            {
                resourceKeyStrings.Add(Myenumerator.Key.ToString());
            }
            return resourceKeyStrings;
        }

Happy Coding!!

Thursday, January 23, 2014

Windows Azure: Upload and Download Functionality- upload/download image to blob


Following class is useful to download or upload image from blob. Provide necessary parameters to function.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using System.Configuration;
using Microsoft.WindowsAzure;
using System.IO;
using Microsoft.WindowsAzure.ServiceRuntime;
namespace AzureDemo
{
    public class AzureBlobManager
    {
        public string uploadFilesToAzureBlob(FileUpload PostedFile, string FileName, string containerName, Guid userid)
        {
            string blobURLs = string.Empty;
            try
            {
                // Retrieve storage account from connection string.
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);
                // Create the blob client.
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                // Retrieve a reference to a container.            
                CloudBlobContainer container = blobClient.GetContainerReference(containerName);
                // Create the container if it doesn't already exist.
                container.CreateIfNotExists();
                if (PostedFile.PostedFile.ContentLength > 0)
                {
                    System.IO.Stream inputStream = PostedFile.PostedFile.InputStream;
                    inputStream.Position = 0;
                    byte[] myBinary = new byte[PostedFile.PostedFile.ContentLength];
                    //PostedFile.InputStream.Read(myBinary, 0, (int)PostedFile.ContentLength);
                    using (var binaryReader = new System.IO.BinaryReader(inputStream))
                    {
                        myBinary = binaryReader.ReadBytes(PostedFile.PostedFile.ContentLength);
                    }
                    // Retrieve reference to a blob named "myblob".
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(string.Concat(userid, "_", PostedFile.FileName));
                    // Create or overwrite the "myblob" blob with contents from a local file.                    
                    //blockBlob.UploadFromStream(PostedFile.PostedFile.InputStream);
                    blockBlob.UploadFromStream(new System.IO.MemoryStream(myBinary));
                    // blockBlob.UploadFromStream(PostedFile.PostedFile.InputStream);
                    blobURLs = blockBlob.Uri.ToString();
                }
            }
            catch (Exception ex)
            {
                //HandleException.HandleExceptionLog(ex);
            }
            return blobURLs;
        }

//Directly reads from blob and sends it to user
        public void DownloadFileFromBlob(string fileName,string containerName)
        {
            CloudStorageAccount account = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);
            CloudBlobClient blobClient = account.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);
            CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
            MemoryStream memStream = new MemoryStream();
            blob.DownloadToStream(memStream);
            HttpContext.Current.Response.ContentType = blob.Properties.ContentType;
            HttpContext.Current.Response.AddHeader("Content-Disposition", "Attachment; filename=" + fileName.ToString());
            HttpContext.Current.Response.AddHeader("Content-Length", blob.Properties.Length.ToString());
            HttpContext.Current.Response.BinaryWrite(memStream.ToArray());
        }
    }
}

Happy Coding!! 

Friday, October 25, 2013

IE11 and Windows 8.1 : Solution for __doPostBack and Ajax not working

When we tested our website against latest IE 11 browser then we came to know that our website is not working properly against IE 11 browser.

I tried to find out on the solution for this issue and i found out following ways which will help us to resolve issue on IE 11 browser.

​Following Steps are performed to fix IE 11: ajax and __dopostback issues:
You can upgrade to .net framework 4.5 which will help us to resolve issue. If you can not update then we have some temporary alternative solution.

There are 2 solutions:

1. Site Level Fix:

Nuget has provided an update for the browser, you can execute the co

   step 1: Perform Steps from following links
        http://www.nuget.org/packages/App_BrowsersUpdate/
  
   step 2: In ie.browser add mentioned settings from following link

In your project, add to (or create as) App_Browsers/ie.browser, the following:

<!-- Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko -->
<browser id="IE11Preview" parentID="Mozilla">
    <identification>
        <userAgent match="Trident/(?'layoutVersion'\d+).*rv:(?'revision'(?'major'\d+)(\.(?'minor'\d+)?))" />
        <userAgent nonMatch="MSIE" />
    </identification>

    <capabilities>
        <capability name="browser"              value="IE" />
        <capability name="layoutEngine"         value="Trident" />
        <capability name="layoutEngineVersion"  value="${layoutVersion}" />
        <capability name="isColor"              value="true" />
        <capability name="screenBitDepth"       value="8" />
        <capability name="ecmascriptversion"    value="3.0" />
        <capability name="jscriptversion"       value="6.0" />
        <capability name="javascript"           value="true" />
        <capability name="javascriptversion"    value="1.5" />
        <capability name="w3cdomversion"        value="1.0" />
        <capability name="ExchangeOmaSupported" value="true" />
        <capability name="activexcontrols"      value="true" />
        <capability name="backgroundsounds"     value="true" />
        <capability name="cookies"              value="true" />
        <capability name="frames"               value="true" />
        <capability name="javaapplets"          value="true" />
        <capability name="supportsCallback"     value="true" />
        <capability name="supportsFileUpload"   value="true" />
        <capability name="supportsMultilineTextBoxDisplay" value="true" />
        <capability name="supportsMaintainScrollPositionOnPostback" value="true" />
         <capability name="supportsVCard"        value="true" />
        <capability name="supportsXmlHttp"      value="true" />
        <capability name="tables"               value="true" />
        <capability name="supportsAccessKeyAttribute"    value="true" />
        <capability name="tagwriter"            value="System.Web.UI.HtmlTextWriter" />
        <capability name="vbscript"             value="true" />
        <capability name="revmajor"             value="${major}" />
        <capability name="revminor"             value="${minor}" />
    </capabilities>

</browser>


Once you perform above mentioned steps, your issue will be resolved.

2. Machine Level Fix:


   Step 1: Download patch from following link.
     http://support.microsoft.com/kb/2836939
   Step 2: install patch

   Main Source: http://www.hanselman.com/blog/IE10AndIE11AndWindows81AndDoPostBack.aspx

With the help of above fixes you can fix issue.

Happy Coding!!

Friday, June 14, 2013

Self Signed Certificate

Following link has described how to create self signed certificate for development/Testing purpose
http://www.robbagby.com/iis/self-signed-certificates-on-iis-7-the-easy-way-and-the-most-effective-way/

SelfCert Exe Download location:
https://skydrive.live.com/?cid=3c8d41bb553e84f5&id=3C8D41BB553E84F5!175&authkey=yeHVTUTVzGE$

Monday, April 29, 2013

SQL Parameter sniffing

SQL Parameter sniffing

For last few days we were having a problem with a few stored procedures that stop functioning for some set of values using SQL Server 2012. The stored procedure work correctly with one set of parameters, while with another set would timeout and fail.

The initial way that we bypassed this problem was that when this circumstance was found, we would alter the stored procedure and this seemed to fix it. As you can imagine it wasn't an ideal situation for an enterprise application because the problem would need to be found and reported before we would even know it existed but we struggled to find any proposed solutions to the problem.
After much investigation it was suggested that this could be caused by parameter sniffing. SQL Server does this by tracking what happens to the parameters passed into the stored procedure when creating the stored procedure and working out the execution plan. So the execution plan generated by SQL server was good most of the time but the plan would contain situations where the procedure would fail.
Below is a stored procedure that allows parameter sniffing. This is not one of the stored procedures that did have the problem, but a stored procedure where parameter sniffing occurs:
ALTER PROCEDURE [dbo].[ReportJobSeekerDetails]
@MarketPlaceID BIGINT,
@RoleName NVARCHAR(20),
@CountryId SMALLINT = NULL,
@StateId BIGINT = NULL,
@UserStatus TINYINT = NULL,
@RegStartDate DATETIME = NULL,
@RegEndDate DATETIME = NULL,
@StartRowNumber INT,
@PageSize INT,
@SortExpression NVARCHAR(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
SET NOCOUNT OFF;
IF @PageSize > 100
SET @PageSize = 100
SELECT COUNT(*) 'RowCount'
FROM
aspnet_users au
INNER JOIN aspnet_membership am ON au.userID = am.userid
INNER JOIN aspnet_usersinroles ur ON ur.userID = au.UserId
INNER JOIN UserPublicProfile upp ON upp.UserID = ur.ID
LEFT JOIN Country c ON upp.CountryID = c.Id
LEFT JOIN State s ON upp.StateID = s.ID
WHERE (@CountryId IS NULL OR c.Id = @CountryId)
AND (@StateId IS NULL OR upp.StateId = @StateId)
AND (@UserStatus IS NULL OR am.IsLockedOut = @UserStatus)
AND (@RegStartDate IS NULL OR am.CreateDate > @RegStartDate)
AND (@RegEndDate IS NULL OR am.CreateDate < @RegEndDate)
END
With the following addition of variables it prevents SQL Server from having the ability to perform parameter sniffing:
ALTER PROCEDURE [dbo].[ReportJobSeekerDetails]
@MarketPlaceID BIGINT,
@RoleName NVARCHAR(20),
@CountryId SMALLINT = NULL,
@StateId BIGINT = NULL,
@UserStatus TINYINT = NULL,
@RegStartDate DATETIME = NULL,
@RegEndDate DATETIME = NULL,
@StartRowNumber INT,
@PageSize INT,
@SortExpression NVARCHAR(100)= NULL,
@TotalCount INT OUTPUT
AS
BEGIN
DECLARE @CountryIdLocal SMALLINT = @CountryId
DECLARE @StateIdLocal BIGINT = @StateId
DECLARE @UserStatusLocal TINYINT = @UserStatus
DECLARE @RegStartDateLocal DATETIME = @RegStartDate
DECLARE @RegEndDateLocal DATETIME = @RegEndDate
SELECT @TotalCount = COUNT(au.UserName)
FROM dbo.aspnet_users au
INNER JOIN dbo.aspnet_membership am ON au.userID = am.userid
INNER JOIN dbo.aspnet_usersinroles ur ON ur.userID = au.UserId
INNER JOIN UserPublicProfile upp ON upp.UserID = ur.ID
LEFT JOIN Country c ON upp.CountryID = c.Id
LEFT JOIN State s ON upp.StateID = s.ID
WHERE (@CountryIdLocal IS NULL OR c.Id = @CountryIdLocal)
AND (@StateIdLocal IS NULL OR upp.StateId = @StateIdLocal)
AND (@UserStatusLocal IS NULL OR am.IsLockedOut = @UserStatusLocal)
AND (@RegStartDateLocal IS NULL OR am.CreateDate > @RegStartDateLocal)
AND (@RegEndDateLocal IS NULL OR am.CreateDate < @RegEndDateLocal)
END
By implementing the small change demonstrated above on a couple of troublesome stored procedures, this fixed our problem with our stored procedures randomly not working with certain parameters. This proved that the problem was caused by parameter sniffing and left me wondering how many other people are out there with the same problem.

Happy Coding!!

Prevent the browser from caching the ASPX page

​use this code to prevent the browser from caching the ASPX page.

By default browser cache the page. sometimes we don't require the page to be cached.

It will work for IE, Mozilla, and Chrome. I didn't checked the below code for other browsers.

<%@ Page language="c#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>HttpCachePolicy - SetNoStore - C# Example</title>
    <script runat="server">
      void Page_Load(Object sender, EventArgs e) 
      {
        // Prevent the browser from caching the ASPX page
        Response.Cache.SetNoStore();

        // Display the DateTime value.
        Label1.Text = DateTime.Now.ToLongTimeString();
      }
    </script>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">
      <h3>HttpCachePolicy - SetNoStore - C# Example</h3>

      <p>Click the Submit button a few times, and then click the Browser's Back button.<br />
      You should get a "Warning: Page has Expired" error message.</p>

      <p>Time:  <asp:Label id="Label1" runat="server" Font-Bold="True" ForeColor="Red" /></p>

      <asp:Button id="Button1" runat="server" Text="Submit" />
    </form>
  </body>
</html>

Happy Coding !!

Saturday, March 16, 2013

Custom errors in web.config

Some times after hosting web application on the server, we get unexpected error. But we did not get the detailed message for the unexpected error or if we added defaultredirect="error.htm".

<customErrors defaultRedirect="error.htm" mode="On" />

  how can we get detailed message for the unexpected error. Unexpected error may occur on remote or on local server. We can find out exact error message by doing some changes in web.config. Just change Custom error  mode to off.

<customErrors defaultRedirect="error.htm" mode="Off" />
There are three error modes in which an ASP.NET application can work:
1) Off Mode
2) On Mode
3) RemoteOnly Mode


The Error mode attribute determines whether or not an ASP.NET error message is displayed. By default, the mode value is set to "RemoteOnly".

Off Mode

When the error attribute is set to "Off", ASP.NET uses its default error page for both local and remote users in case of an error.

On Mode

In case of "On" Mode, ASP.NET uses user-defined custom error page instead of its default error page for both local and remote users. If a custom error page is not specified, ASP.NET shows the error page describing how to enable remote viewing of errors.

RemoteOnly

ASP.NET error page is shown only to local users. Remote requests will first check the configuration settings for the custom error page or finally show an IIS error. 

Happy Coding!!

Saturday, January 12, 2013

Grid view Column- Apply Word wrap to work in all browser

Sometimes in gridview we have a column which has too much information so it is not shown properly on page.

We can achieve with the help of CSS.
.word_wrap
{
    white-space: pre; /* CSS 2.0 */
    white-space: pre-wrap; /* CSS 2.1 */
    white-space: pre-line; /* CSS 3.0 */
    white-space: -pre-wrap; /* Opera 4-6 */
    white-space: -o-pre-wrap; /* Opera 7 */
    white-space: -moz-pre-wrap; /* Mozilla */
    white-space: -hp-pre-wrap; /* HP Printers */
    word-wrap: break-word; /* IE 5+ */
}
We have defined a css class, and we can assign this cssclass to column which has too much information.

<asp:TemplateField HeaderText="Name On Document" meta:resourcekey="HeaderText_NameOnResource1">
    <HeaderStyle Width="100px" Font-Bold="true" />
        <ItemTemplate>
            <div style="word-wrap: break-word; width: 100px;">
                 <%# Eval("NameOnDocument")%>
            </div>
        </ItemTemplate>
        <ItemStyle Width="100px" CssClass="word_wrap" Wrap="true" />
</asp:TemplateField>

Happy Coding!!

Wednesday, January 9, 2013

Encrypt connection string in web.config file

This time we have written a generalize function which will encrypt an decrypt connection strings.

Following code snippet will help to encrypt connection string in web.config file.

  protected void encryptConfi(bool bencrypt)
        {
            string webconfigfilepath = "~/";
            Configuration config = WebConfigurationManager.OpenWebConfiguration(webconfigfilepath);
            ConfigurationSection configsec = config.GetSection("connectionStrings");
            if (bencrypt)
            {
                configsec.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
            }
            else
            {
                configsec.SectionInformation.UnprotectSection();
            }
            config.Save();
        }

Happy Coding!!

Wednesday, December 19, 2012

Download File in Asp.net

Following is a snippet required to download a file


    private void StartDownloadFile(string attachmentPath)
        {
            FileInfo file = new FileInfo(attachmentPath);
            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.AppendHeader("Content-Disposition", "attachment; filename = " + file.Name);
            Response.AppendHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/download";
            Response.WriteFile(file.FullName);
            Response.Flush();
            Response.Close();
            Response.End();
        }

This is generalize function, you need to pass path of filename. With the help of above code snippet browser will popup download box where you need to give the path.

Happy Coding!!

Tuesday, June 26, 2012

hyperlink in template column gridview

following snippet is useful to insert hyperlink template column in grdview 

    <asp:TemplateField  HeaderText="User name">
                <ItemTemplate>
                    <asp:HyperLink runat="server" ID="lnkRedirect"  NavigateUrl='<%# String.Format("~/UserDetails.aspx?username={0}",Container.DataItem) %>' Text='<%# Container.DataItem %>'></asp:HyperLink>
                </ItemTemplate>
            </asp:TemplateField>

if you are binding arraylist to gridview & grdview contains template column then in controls text property use Text='<%# Container.DataItem %>' instead of Text='<%# ColumnName %>' because columnName is not available in arraylist

Happy Coding!!

add Serial Number in gridview

sometimes we need to add serial numbers in gridview. we can achieve it through following code snippet.
<asp:TemplateField>
<HeaderTemplate> Serial No. </HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblSRNO" runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label> </ItemTemplate>
</asp:TemplateField>

This code works as same when we apply paging.

We cannot use this on BoundFields because they support only those objects who have Databinding event.

Happy Coding!!

Sunday, June 3, 2012

html to pdf using itextSharp

In previous article we checked how to convert gridview to pdf.

https://blogabhijeet.blogspot.com/2012/06/gridview-to-pdf-using-itextsharp.html

First of all you need to convert contents of html to Pdf. There is an third party dll:- iTextSharp dll which will help us to convert html contents to pdf.

Just Download iTextsharp lib. from http://sourceforge.net/projects/itextsharp/

Add 1 form in your project named as "pdf" then copy following design & Code behind code &  replace it in your code.

Currently we have taken form and we are showing contents of current page in pdf.

Design Page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ShowCurrentContentPageinPdf.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:PlaceHolder ID="PlaceholderPdf" runat="server"></asp:PlaceHolder>
    <div>
        <table border="1">
            <tr>
                <td colspan="2">
                    aspdotnetcodebook
                </td>
            </tr>
            <tr>
                <td>
                    cell1
                </td>
                <td>
                    cell2
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Label ID="lblLabel" runat="server" Text="Label Test"></asp:Label>
                </td>
            </tr>
        </table>
    </div>
    <p>
        &nbsp;</p>
    <p>
        xzcv</p>
    <p>
        &nbsp;</p>
    <p>
        &nbsp;</p>
    <p>
        &nbsp;</p>
    <p>
        sdvasd</p>
    <p>
        &nbsp;</p>
    <p>
        &nbsp;</p>
    <p>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </p>
    </form>
</body>
</html>
Code Behind Page 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.xml;
using System.Xml;
using iTextSharp.text.html.simpleparser;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


    }

    protected override void Render(HtmlTextWriter writer)
    {
        MemoryStream mem = new MemoryStream();
        StreamWriter twr = new StreamWriter(mem);
        HtmlTextWriter myWriter = new HtmlTextWriter(twr);
        base.Render(myWriter);
        myWriter.Flush();
        myWriter.Dispose();
        StreamReader strmRdr = new StreamReader(mem);
        strmRdr.BaseStream.Position = 0;
        string pageContent = strmRdr.ReadToEnd();
        strmRdr.Dispose();
        mem.Dispose();
        writer.Write(pageContent);
        CreatePDFDocument(pageContent);


    }
    public void CreatePDFDocument(string strHtml)
    {

        string strFileName = HttpContext.Current.Server.MapPath("test.pdf");
        // step 1: creation of a document-object
        Document document = new Document();
        // step 2:
        // we create a writer that listens to the document
        PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
        StringReader se = new StringReader(strHtml);
        HTMLWorker obj = new HTMLWorker(document);
        document.Open();
        obj.Parse(se);
        document.Close();
        ShowPdf(strFileName);



    }
    public void ShowPdf(string strFileName)
    {
        Response.ClearContent();
        Response.ClearHeaders();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName);
        //Response.WriteFile(strFileName);
        Response.TransmitFile(strFileName);
        Response.End();
        Response.Flush();
        Response.Clear();
    }
}
We have created 1 more class file

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for MyPage
/// </summary>
public class MyPage : Page
{
    public override void VerifyRenderingInServerForm(Control control)
    {
        GridView grid = control as GridView;
        if (grid != null && grid.ID == "GridView1")
            return;
        else
            base.VerifyRenderingInServerForm(control);

    }
}
Above code snippet will help us to convert HTML page to pdf.

 Happy Coding !!