Pages

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

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;
         
        }

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

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>

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);

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));
   }
}

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;
        }

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());
        }
    }
}

Friday, October 25, 2013

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

​Following Steps are performed to fix IE 11: ajax and __dopostback issues:
There are 2 solutions:
1. Site Level Fix:
   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
           http://stackoverflow.com/questions/18009636/crosspostback-ajax-controls-and-asp-net-generated-postbacks-work-for-net-4-5

2. Machine Level Fix:
   Main Source: http://www.hanselman.com/blog/IE10AndIE11AndWindows81AndDoPostBack.aspx
   Step 1: Download patch from following link.
     http://support.microsoft.com/kb/2836939
   Step 2: install patch

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.

Prevent the browser from caching the ASPX page

​use this code to prevent the browser from caching the ASPX page.
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>

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. 

Saturday, January 12, 2013

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


.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+ */
}


<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>

Wednesday, January 9, 2013

Encrypt connection string in web.config file

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();
        }

Wednesday, December 19, 2012

Download

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();
        }

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

add Serial Number in gridview

sometimes we need to add serial numbers in gridview. we can achieve it through following code

<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

Sunday, June 3, 2012

html to pdf using itextSharp

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);

    }
}

 Happy Coding !!


GridView to Pdf using iTextSharp

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 1 gridview & button on form.
You can bind your data to gridview as you required. I have just created dataset manually & assign it to gridview

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

<!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">
  <div>
      <asp:GridView ID="GridView1" runat="server">
      </asp:GridView>
      <asp:Button ID="btnExportToPdf" runat="server" OnClick="btnExportToPdf_Click"
          Text="Pdf" /></div>
</form>
</body>
</html>

Code Behind File
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.Collections.Generic;

public partial class pdf : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = GetData();
            GridView1.DataBind();
        }
    }

    public DataSet GetData()
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable("Product");
        DataRow dr;
        dt.Columns.Add(new DataColumn("Price", typeof(Int32)));
        dt.Columns.Add(new DataColumn("DisCount", typeof(Int32)));
        dt.Columns.Add(new DataColumn("SellPrice", typeof(Int32)));
        for (int i = 1; i <= 10; i++)
        {
            dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i * 2;
            dr[2] = 1 * 3;
            dt.Rows.Add(dr);
        }
        ds.Tables.Add(dt);
        Session["dt"] = dt;
        return ds;
    }

    protected void btnExportToPdf_Click(object sender, EventArgs e)
    {
        MyPage tmpPage = new MyPage();
        HtmlForm form = new HtmlForm();

        form.Controls.Add(GridView1);

        tmpPage.Controls.Add(form);
        StringWriter sw = new StringWriter();
        HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
        form.Controls[0].RenderControl(htmlWriter);
        string htmlContent = sw.ToString();
        Document document = new Document();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.GetInstance(document, new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+ "\\Sample.pdf", FileMode.Create));
       

        // step 3: we open the document
        document.Open();

        // step 4: we add a paragraph to the document

        //document.Add(new Paragraph(htmlContent.ToString()));

        System.Xml.XmlTextReader _xmlr = new System.Xml.XmlTextReader(new StringReader(htmlContent));

        //HtmlParser.Parse(document, _xmlr);
        using (TextReader sReader = new StringReader(sw.ToString()))
        {
            List<IElement> list = HTMLWorker.ParseToList(sReader, new StyleSheet());
            foreach (IElement elm in list)
            {
                document.Add(elm);
            }
        }

        // step 5: we close the document
        document.Close();

        //  Response.Write(document);
        string Path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Sample.pdf";
        ShowPdf(Path);
    }

    private void ShowPdf(string strS)
    {
        Response.ClearContent();
        Response.ClearHeaders();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + strS);
        Response.TransmitFile(strS);
        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);

    }
}

 Happy Coding !!

Thursday, March 10, 2011

Send mail through gmail smtp


Following snippet is for sending mail through gmail smtp. create 4 textboxes for to, from,subject & message

            System.Net.Mail.MailMessage mailmessage=new System.Net.Mail.MailMessage();
            mailmessage.Body = txtBody.Text;
            mailmessage.From = new System.Net.Mail.MailAddress( txtFrom.Text);
            mailmessage.To.Add(txtTo.Text);
            mailmessage.Subject = txtSubject.Text;
            mailmessage.IsBodyHtml = true;
            System.Net.Mail.SmtpClient smt = new System.Net.Mail.SmtpClient();
            smt.UseDefaultCredentials = false;

            smt.Credentials = new System.Net.NetworkCredential("username@gmail.com", "pwd");
            smt.Host = "smtp.gmail.com";
            smt.Port = 587;
            smt.EnableSsl = true;

            smt.Send(mailmessage);