How To Export WebPage as Image in asp..net

In this post i will show how to export Webpage as image in asp.net
  1. Start Visual Studio 2005.
  2. Create a Web site.
  3. Add Reference of System.Windows.Forms
  4. Add AspCompat="true" in page attribute.
  5. Verify that the following namespaces are included in the ExportWebPageToImage.c
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.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
Here is complete source code
<%@ Page Language="C#" AspCompat="true" AutoEventWireup="true" CodeFile="ExportWebPageToImage.aspx.cs"
   Inherits="ExportWebPageToImage" %>

<!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>
   <style type="text/css">
       .style1
       {
           width: 100%;
       }
   </style>
</head>
<body>
   <form id="form1" runat="server">
   <div>
       <asp:TextBox ID="txtUrl" runat="server" Width="208px"></asp:TextBox><br />
       <asp:Button ID="btnConvert" runat="server" Text="Convert Page To Image" OnClick="btnConvert_Click" />
   </div>
   </form>
</body>
</html>
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.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

public partial class ExportWebPageToImage : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {


   }

   public System.Drawing.Bitmap CaptureWebPage(string URL)
   {
       // create a hidden web browser, which will navigate to the page
       System.Windows.Forms.WebBrowser web = new System.Windows.Forms.WebBrowser();
       // we don't want scrollbars on our image
       web.ScrollBarsEnabled = false;
       // don't let any errors shine through
       web.ScriptErrorsSuppressed = true;
       // let's load up that page!
       web.Navigate(URL);

       // wait until the page is fully loaded
       while (web.ReadyState != WebBrowserReadyState.Complete)
           System.Windows.Forms.Application.DoEvents();
       System.Threading.Thread.Sleep(1500); // allow time for page scripts to update
       // the appearance of the page

       // set the size of our web browser to be the same size as the page
       int width = web.Document.Body.ScrollRectangle.Width;
       int height = web.Document.Body.ScrollRectangle.Height;
       web.Width = width;
       web.Height = height;
       // a bitmap that we will draw to
       System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height);
       // draw the web browser to the bitmap
       web.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, width, height));

       return bmp; // return the bitmap for processing
   }
   protected void btnConvert_Click(object sender, EventArgs e)
   {
       Bitmap bitmap = new Bitmap(CaptureWebPage(txtUrl.Text));
       Response.ContentType = "image/jpeg";
       bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
       bitmap.Dispose();
       bitmap.Dispose();
       Response.End();
   }
}

How To Read xml using JQuery

In this post i will show how to read xml using JQuery
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

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

   <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

   <script type="text/javascript">

       $(document).ready(function() {
           $.get('Data.xml', function(d) {
               var data = "";
               var startTag = "<table border='1' id='mainTable'><tbody><tr><td style=\"width: 120px\">Name</td><td style=\"width: 120px\">Link</td></tr>";
               var endTag = "</tbody></table>";
               $(d).find('url').each(function() {
                   var $url = $(this);
                   var link = $url.find('link').text();
                   var name = $url.find('name').text();
                   data += '<tr><td>' + name + '</td>';
                   data += '<td>' + link + '</td></tr>';
               })
               $("#content").html(startTag + data + endTag);
               ;
           });

       });
   </script>

</head>
<body>
   <div id="content">
   </div>
</body>
</html>
Data.xml
<?xml version="1.0" encoding="utf-8" ?>
<Urls>
 <url>
   <name>google</name>
   <link>
     www.google.com
   </link>
 </url>
 <url>
   <name>aspdotnetcodebook</name>
   <link>http://aspdotnetcodebook.blogspot.com</link>
 </url>
</Urls>

jQuery Ajax call and result XML parsing in asp.net

In this post i will show how to use Jquery in asp.net
  1. Start Microsoft Visual Studio .NET.
  2. On the File menu, point to New, and then click Project.
  3. In the New Project dialog box, click Visual C# Projects
  4. Add a new xml file and copy the following xml.
labels.xml
<?xml version="1.0" encoding="utf-8"?>
<labels>
<label id="1">
<name>Test</name>
<address>
  <street>street1</street>
  <city>City1</city>
  <province>ID</province>
</address>
</label>
<label id='2'>
<name>Name2</name>
<address>
  <street>Street2</street>
  <city>City2</city>
  <province>CT</province>
</address>
</label>

</labels>

5. Add a reference to the jQuery script 6.Copy below code in aspx page.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.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>

  <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

  <script type="text/javascript">
   $(function() {
       $('#update-target a').click(function() {
           $.ajax({
               type: "GET",
               url: "labels.xml",
               dataType: "xml",
               success: function(xml) {
                   $(xml).find('label').each(function(){
                       var id_text = $(this).attr('id')
                       var name_text = $(this).find('name').text()

                       $('<li></li>')
                           .html(name_text + ' (' + id_text + ')')
                           .appendTo('#update-target ol');
                   }); //close each(
               }
           }); //close $.ajax(
       }); //close click(
   }); //close $(
  </script>

</head>
<body>
  <form id="form1" runat="server">
  <div>
      <p>
          <div id='update-target'>
              <a href="#">Click here to load addresses</a>
              <ol>
              </ol>
          </div>
      </p>
  </div>
  </form>
</body>
</html>

How To Include Content of One Page To another Page

In this post i will show how to include the content of one page inside another using Regular expression .
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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:Label ID="lblHtml" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>
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;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      lblHtml.Text= ParseHtml();

    }
    private static string ParseHtml()
    {
        StreamReader sr;
        string html;
        sr = File.OpenText(HttpContext.Current.Server.MapPath("Default.aspx"));
        html = sr.ReadToEnd();
        sr.Close();

        Regex
            start = new Regex(@"[\s\S]*<body[^<]*>", RegexOptions.IgnoreCase);
        html = start.Replace(html, "");
        Regex end = new Regex(@"</body[\s\S]*", RegexOptions.IgnoreCase);
        html = end.Replace(html, "");
        return html;
    }
}

How To Select Value of gridview row using javascript

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

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!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:ScriptManager ID="ScriptManger1" runat="server">
    </asp:ScriptManager>
    <div>
    </div>
    <style>
        .invisibleColumn
        {
            display: none;
            width: 0px;
        }
        body
        {
            font-family: Arial;
            font-size: 12px;
        }
    </style>

    <script type="text/javascript">
        function getValue(obj) {

            document.getElementById('<%=txtFriend.ClientID %>').value = obj;
        }
    </script>

    <asp:UpdatePanel ID="Update1" runat="server">
        <ContentTemplate>
            <cc1:DropDownExtender ID="DropDownExtender1" DropDownControlID="FriendGridView" TargetControlID="txtFriend"
                runat="server">
            </cc1:DropDownExtender>
            <asp:TextBox ID="txtFriend" runat="server" Width="200px"></asp:TextBox>
            <asp:GridView ID="FriendGridView" runat="server" Width="200px" AutoGenerateColumns="false"
                OnRowDataBound="FriendGridView_RowDataBound" OnSelectedIndexChanged="FriendGridView_SelectedIndexChanged">
                <RowStyle BackColor="#DDDDDD" />
                <Columns>
                    <asp:BoundField DataField="ID" HeaderStyle-CssClass="invisibleColumn" ItemStyle-CssClass="invisibleColumn" />
                    <asp:BoundField DataField="Name" HeaderText="Name" />
                    <asp:BoundField DataField="Description" HeaderText="Description" />
                </Columns>
                <HeaderStyle BackColor="Blue" ForeColor="White" />
                <AlternatingRowStyle BackColor="#EEEEEE" />
                <SelectedRowStyle BackColor="#999999" />
            </asp:GridView>
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    }
    protected void FriendGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // The value that we want is in column #9...
            string valueText = e.Row.Cells[1].Text;

            string clickHandler = string.Format("alert('Value in column #9 is {0}')", valueText);
            e.Row.Attributes.Add("onclick", "getValue('" + valueText + "')");
        }
    }
    public List<Friend> GetFriends()
    {

        List<Friend> users = new List<Friend>();
        users.Add(new Friend("Xyz", "Coder"));
        users.Add(new Friend("Abc", "Writer"));
        users.Add(new Friend("Charles", "Poet"));
        return users;


    }
    protected void FriendGridView_SelectedIndexChanged(object sender, EventArgs e)
    {
        // assign firstname
        if (FriendGridView.SelectedRow != null)
            txtFriend.Text = Server.HtmlDecode(
              FriendGridView.SelectedRow.Cells[1].Text);
        else
            txtFriend.Text = "";

    }
}
public class Friend
{

    public Friend(string name, string description)
    {

        _name = name;

        _description = description;

        _id = Guid.NewGuid().ToString();

    }



    private string _id;
    public string Id
    {

        get { return _id; }

        set { _id = value; }

    }

    private string _name;
    public string Name
    {

        get { return _name; }

        set { _name = value; }

    }
    private string _description;
    public string Description
    {

        get { return _description; }

        set { _description = value; }

    }
}

how to convert web page to pdf

In this post i will show how to convert web page to pdf using iTextSharp.
<%@ 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">
    <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>
    </form>
</body>
</html>
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 Pdf : System.Web.UI.Page
{
    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.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
        Response.ContentType = "application/pdf";
        Response.WriteFile(strFileName);
        Response.Flush();
        Response.Clear();
    }
}

ASP.NET and Ajax - using XmlHttpRequest

In this post i will show how to use XmlHttpRequest object in asp.net.Here's an example that fetches the Product details by categoryid.Create a new web application and add following code on Default.aspx page( I have used Ajax.aspx). Ajax.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ajax.aspx.cs" Inherits="Ajax" %>

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

  <script type="text/javascript">
      function GetXmlHttpObject(handler) {
          var objXmlHttp = null
          if (navigator.userAgent.indexOf("Opera") >= 0) {
              alert("This example doesn't work in Opera")
              return
          }
          if (navigator.userAgent.indexOf("MSIE") >= 0) {
              var strName = "Msxml2.XMLHTTP"
              if (navigator.appVersion.indexOf("MSIE 5.5") >= 0) {
                  strName = "Microsoft.XMLHTTP"
              }
              try {
                  objXmlHttp = new ActiveXObject(strName)
                  objXmlHttp.onreadystatechange = handler
                  return objXmlHttp
              }
              catch (e) {
                  alert("Error. Scripting for ActiveX might be disabled")
                  return
              }
          }
          if (navigator.userAgent.indexOf("Mozilla") >= 0) {
              objXmlHttp = new XMLHttpRequest()
              objXmlHttp.onload = handler
              objXmlHttp.onerror = handler
              return objXmlHttp
          }
      }

      function GetProduct(id) {
          var url = "Details.aspx?CatId=" + id;
          xmlHttp = GetXmlHttpObject(stateChanged);
          xmlHttp.open("GET", url, true);
          xmlHttp.send(null);
      }


      function stateChanged() {
          if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
              document.getElementById('ProductDetails').innerHTML = xmlHttp.responseText;
          }
      }

  </script>

</head>
<body>
  <form id="form1" runat="server">
  <div>
      <div>
          <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1"
              DataTextField="CategoryName" DataValueField="CategoryID">
          </asp:DropDownList>
      </div>
      <div id="ProductDetails">
      </div>
  </div>
  <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:northwindConnectionString %>"
      SelectCommand="SELECT [CategoryID], [CategoryName] FROM [Categories]"></asp:SqlDataSource>
  </form>
</body>
</html>



Ajax.aspx.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Ajax : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
      if (!Page.IsPostBack)
      {
          DropDownList1.DataBind();
          DropDownList1.Items.Insert(0, "");
      }
      DropDownList1.Attributes["onChange"] = "GetProduct(this.value);";
      HttpResponse myHttpResponse = Response;
      HtmlTextWriter myHtmlTextWriter = new HtmlTextWriter(myHttpResponse.Output);
      DropDownList1.Attributes.AddAttributes(myHtmlTextWriter);


  }
}
And finally create Details.aspx page and remove everything from .aspx page except the first line. write down following code on Page_Load event of details.aspx page.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data.SqlClient;

public partial class Details : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       Response.Clear();
       StringBuilder sb = new StringBuilder();
       sb.Append("<br />");
       string connstr = System.Configuration.ConfigurationManager.ConnectionStrings["northwindConnectionString"].ConnectionString;
       string query = "SELECT * FROM Products WHERE CategoryId = @CustId";
       SqlConnection conn = new SqlConnection(connstr);
       SqlCommand cmd = new SqlCommand(query, conn);
       cmd.Parameters.AddWithValue("@CustId", Request.QueryString["CatId"]);
       conn.Open();
       SqlDataReader dr = cmd.ExecuteReader();
       while (dr.Read())
       {
           sb.Append(dr[1].ToString() + "<br />");
           sb.Append(dr[2].ToString() + "<br />");
           sb.Append(dr[3].ToString() + "<br />");
           sb.Append(dr[4].ToString() + "<br />");
           sb.Append(dr[5].ToString() + "<br />");
           sb.Append(dr[6].ToString() + "<br />");
       }
       dr.Close();
       dr.Dispose();
       conn.Close();
       conn.Dispose();
       Response.Write(sb.ToString());
       Response.End();

   }
}