Wednesday, October 13, 2010

How to transform XML file to differently formated XML file XSLT


Demo:

Download supported files:

Code:
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    string xml = this.Transform(Server.MapPath("~/Companies.xml"), Server.MapPath("~/CompaniesXml.xsl"));
    this.Response.Clear();
    this.Response.ContentType = "text/xml";
    this.Response.Write(xml);
    this.Response.End();
}
public string Transform(string sXmlPath, string sXslPath)
{
    XPathDocument myXPathDoc = new XPathDocument(sXmlPath);
    XslTransform myXslTrans = new XslTransform();
    myXslTrans.Load(sXslPath);
    StringBuilder output = new StringBuilder();
    using (XmlTextWriter myWriter = new XmlTextWriter(new StringWriter(output)))
    {
        myXslTrans.Transform(myXPathDoc, null, myWriter);
        myWriter.Close();
    }
    return output.ToString();
}
XML file - Companies.xml
<companies>
  <company>
    <name>Mirosoft Ltd</name>
    <address1>Microsoft Campus</address1>
    <address2>Some avenue</address2>
    <city>Reading</city>
    <county>Berkshire</county>
    <postcode>RG6 1WG</postcode>
    <country>United Kingdom</country>
  </company>
  <company>
    <name>Tesco</name>
    <address1>65</address1>
    <address2> Nicholsons Walk</address2>
    <city>Maidenhead</city>
    <county>Bukinghamshire</county>
    <postcode>SL6 1LL</postcode>
    <country>United Kingdom</country>
  </company>
  <company>
    <name>Tesco</name>
    <address1>Off Alexander Road</address1>
    <address2>Park Road</address2>
    <city>City of London</city>
    <county>London</county>
    <postcode>TW3 1JT‎</postcode>
    <country>United Kingdom</country>
  </company>
</companies>
 XSLT file - CompaniesXml.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="/">
    <companies>
      <xsl:apply-templates />
    </companies>
  </xsl:template>
  <xsl:template match="company">
    <company>
      <xsl:attribute name="name">
        <xsl:value-of select="name"/>
      </xsl:attribute>
      <xsl:attribute name="address1">
        <xsl:value-of select="address1"/>
      </xsl:attribute>
      <xsl:attribute name="address2">
        <xsl:value-of select="address2"/>
      </xsl:attribute>
      <xsl:attribute name="city">
        <xsl:value-of select="city"/>
      </xsl:attribute>
      <xsl:attribute name="postcode">
        <xsl:value-of select="postcode"/>
      </xsl:attribute>
      <xsl:attribute name="country">
        <xsl:value-of select="country"/>
      </xsl:attribute>
    </company>
  </xsl:template>
</xsl:stylesheet>

How to transform XML file to HTML format using XSLT


Demo:

Download supported files:

Code:
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    string html = this.Transform(Server.MapPath("~/Companies.xml"), Server.MapPath("~/CompaniesHtml.xsl"));
    this.Response.Clear();
    this.Response.Write(html);
    this.Response.End();
 
}
public string Transform(string sXmlPath, string sXslPath)
{
    XPathDocument myXPathDoc = new XPathDocument(sXmlPath);
    XslTransform myXslTrans = new XslTransform();
    myXslTrans.Load(sXslPath);
    StringBuilder output = new StringBuilder();
    using (XmlTextWriter myWriter = new XmlTextWriter(new StringWriter(output)))
    {
        myXslTrans.Transform(myXPathDoc, null, myWriter);
        myWriter.Close();
    }
    return output.ToString();
}
 XML File - Companies.xml
<companies>
  <company>
    <name>Mirosoft Ltd</name>
    <address1>Microsoft Campus</address1>
    <address2>Some avenue</address2>
    <city>Reading</city>
    <county>Berkshire</county>
    <postcode>RG6 1WG</postcode>
    <country>United Kingdom</country>
  </company>
  <company>
    <name>Tesco</name>
    <address1>65</address1>
    <address2> Nicholsons Walk</address2>
    <city>Maidenhead</city>
    <county>Bukinghamshire</county>
    <postcode>SL6 1LL</postcode>
    <country>United Kingdom</country>
  </company>
  <company>
    <name>Tesco</name>
    <address1>Off Alexander Road</address1>
    <address2>Park Road</address2>
    <city>City of London</city>
    <county>London</county>
    <postcode>TW3 1JT‎</postcode>
    <country>United Kingdom</country>
  </company>
</companies>

XSLT file - CompaniesHtml.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="html" />
  <xsl:template match="/">
    <html>
      <head>
        <title>
         Clients List - Company Ltd.
        </title>
        <style>
          body {font-family:Tahoma,Arial; font-size:9pt;}
        </style>
      </head>
      <body>
        <h1>Our Clients</h1>
        <xsl:for-each select="companies/company">
          <h2>
            <xsl:value-of select="name"/>
          </h2>
          <p>
            <xsl:value-of select="address1"/>
          </p>
          <p>
            <xsl:value-of select="address2"/>
          </p>          
          <p>
            <xsl:value-of select="city"/>
          </p>
          <p>
            <xsl:value-of select="county"/>
          </p>
          <p>
            <xsl:value-of select="postcode"/>
          </p>
          <p>
            <xsl:value-of select="country"/>
          </p>
          <hr />
        </xsl:for-each>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

How to work with XML files

  1. How to use XPathNodeIterator to navigate through XML file
  2. How to transform XML file to HTML format using XSL
  3. How to transform XML file to differently formated XML file XSL

How to work with threads?

  1. How to create STA (Single Threaded Apartment) thread?
  2. How to implement a background worker?

How to implement a background worker thread

<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script runat="server">
        int? time;
        public int Time
        {
            get
            {
                if (this.time.HasValue) return time.Value;
                return (time = (int)(Session["time"] ?? 0)).Value;
            }
            set
            {
                Session["time"] = this.time = value;
            }
        }
        public System.Threading.Thread Current
        {
            get { return (System.Threading.Thread)Session["Current"]; }
            set { Session["Current"] = value; }
        }
        public void Start(object sender, EventArgs e)
        {
            this.Time = 0;
            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(Process));
            this.Current = thread;
            thread.Start();
        }
        private void Process()
        {
            this.Time++;
            ///
            /// some operation on each second. 
            ///
            System.Threading.Thread.Sleep(1000);
            Process();
 
        }
        protected void Update(object sender, EventArgs e)
        {
            this.lblTime.Text = this.Time.ToString();
        }
        protected void Stop(object sender, EventArgs e)
        {
            if (this.Current != null)
            {
                this.Current.Abort();
                while (this.Current.IsAlive) System.Threading.Thread.Sleep(1);
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Button runat="server" ID="btnStart" Text="Start" OnClick="Start" />
        <asp:Button runat="server" ID="btnUpdate" Text="Update Time" OnClick="Update" />
        <asp:Button runat="server" ID="btnStop" Text="Stop" OnClick="Stop" />
        <hr />
        <asp:Label runat="server" ID="lblTime" />
    </form>
</body>
</html>

How to bind DataTable to a asp.net TreeView using ParentID and ID relationship

Here are some useful tips for you:
  1. TreeView control expects a heirarchical data structure, so we cant bind the DataTable to menu directly.
  2. Use data table Select where ParentID = ID
  3. Please use a recursive method to create child items relevent to current menu item ID
Here is an working example that you may use to transfer your ralational data structure (TABLE) to hierarchical data structure (TREE) using the relationship between ParentID and ID
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script runat="server">
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!this.IsPostBack)
                this.AddNodes(this.trvCategories.Nodes, 0, this.LoadData());
        }
        private void AddNodes(TreeNodeCollection nodes, int level, System.Data.DataTable dt)
        {
            string filterExp = string.Format("ParentID='{0}'", level);
            foreach (System.Data.DataRow r in dt.Select(filterExp))
            {
                TreeNode item = new TreeNode()
                {
                    Text = r[1].ToString(),
                    Value = r[2].ToString()
                };
                this.AddNodes(item.ChildNodes, int.Parse(r[0].ToString()), dt);
                nodes.Add(item);
            }
        }
        private System.Data.DataTable LoadData()
        {
            ///
            /// For the simplicity I do build the datatable dynamically,
            /// But you may get this data from the DATABASE
            ///
            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("ID"String.Empty.GetType());
            dt.Columns.Add("[Name]"String.Empty.GetType());
            dt.Columns.Add("[Value]"String.Empty.GetType());
            dt.Columns.Add("ParentID"String.Empty.GetType());
            dt.Columns.Add("[Order]"String.Empty.GetType());
            int index = 9;
            for (int i = 0; i < 1100; i++)
            {
                string item = "{0},Item{1},Value{1},{2},{1}";
                if (i < 110)
                {
                    index = i < 10 ? 0 : int.Parse(Math.Ceiling((decimal)i / 10).ToString());
                    dt.Rows.Add((string.Format(item, i + 1, i, index)).Split(char.Parse(",")));
                }
                else
                {
                    if (i % 10 == 0) index++;
                    dt.Rows.Add((string.Format(item, i + 1, i, index)).Split(char.Parse(",")));
                }
            }
            return dt;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:TreeView runat="server" ID="trvCategories" />
    </form>
</body>
</html>

Tuesday, October 12, 2010

How to print long page with multiple pages as PDF

using System.Windows.Forms;
using iTextSharp.text.pdf;
using iTextSharp.text;
 
namespace ActiveTest
{
    public partial class Test : Page
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            string mode = this.Request.QueryString.Get("mode");
            string page = this.Request.QueryString.Get("page");
            if (!string.IsNullOrEmpty(mode) && mode.Equals("Print"))
            {
                int p = int.Parse(page);
                ///
                /// bind relevent page of the gridview
                /// 
                Response.Write("This is page " + page);
            }
        }
        protected void PrintPDF(object sender, EventArgs e)
        {
            int listId = 12345;
            ///
            /// A4 Size:
            ///
            int width = 595;
            int height = 792;
            int leftMargin = 20;
            int rightMargin = 20;
 
            iTextSharp.text.Rectangle pgSize = new iTextSharp.text.Rectangle(width, height);
            Document doc = new Document(pgSize, leftMargin, rightMargin, 48, 24);
            string f = Server.MapPath(string.Format("~/Temp/{0}.pdf", listId));
            PdfWriter.GetInstance(doc, new FileStream(f, FileMode.Create));
            doc.Open();
 
            int rowCount = this.GetRowCount();
            int pageSize = 30;
            for (int j = 0; j < (rowCount / pageSize) + 1; j++)
            {
                string url = this.Request.Url.ToString() + "?id=" + listId + "&mode=Print&page=" + j;
                Image thumbnail = new Image(url, width, height, width, height, Image.ImageMethod.Url);
                using (Bitmap image = thumbnail.GenerateImage())
                {
                    iTextSharp.text.Image i = iTextSharp.text.Image.GetInstance(image, 
                                                        System.Drawing.Imaging.ImageFormat.Bmp);
                    doc.Add(i);
                    doc.NewPage();
                }
            }
            doc.Close();
            ///
            /// Use pdf file 
            ///
            File.Delete(f);            
        }
        protected int GetRowCount()
        {
            ///
            /// Get from database.
            ///
            return 130;
        }
    }
    public class Image
    {
        public enum ImageMethod { Url, Html };
        public string Url { getset; }
        public Bitmap Current { getset; }
        public int Width { getset; }
        public int Height { getset; }
        public int BrowserWidth { getset; }
        public int BrowserHeight { getset; }
        public string Html { getset; }
        public ImageMethod Method { getset; }
 
        public Image(string data, int browserWidth, int browserHeight, int width,
                                        int height, ImageMethod method)
        {
            this.Method = method;
            if (method == ImageMethod.Url)
                this.Url = data;
            else if (method == ImageMethod.Html)
                this.Html = data;
            this.BrowserWidth = browserWidth;
            this.BrowserHeight = browserHeight;
            this.Height = height;
            this.Width = width;
        }
        public Bitmap GenerateImage()
        {
            Thread thread = new Thread(new ThreadStart(GenerateThumbnailInteral));
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
            return Current;
        }
        private void GenerateThumbnailInteral()
        {
            WebBrowser webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            if (this.Method == ImageMethod.Url)
                webBrowser.Navigate(this.Url);
            else webBrowser.DocumentText = this.Html;
            webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
            while (webBrowser.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents();
            webBrowser.Dispose();
        }
        private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser webBrowser = (WebBrowser)sender;
            webBrowser.ClientSize = new Size(this.BrowserWidth, this.BrowserHeight);
            webBrowser.ScrollBarsEnabled = false;
            this.Current = new Bitmap(webBrowser.Bounds.Width, webBrowser.Bounds.Height);
            Graphics g = Graphics.FromImage((System.Drawing.Image)this.Current);
            g.InterpolationMode = InterpolationMode.High;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.Clear(Color.Transparent);
            webBrowser.BringToFront();
            webBrowser.DrawToBitmap(Current, webBrowser.Bounds);
            this.Current = (Bitmap)this.Current.GetThumbnailImage(Width, Height, nullIntPtr.Zero);
            g.Dispose();
        }
    }
}

Sunday, October 10, 2010

How print page as PDF using iTextSharp

Example code:
using System.Windows.Forms;
using iTextSharp.text.pdf;
using iTextSharp.text;
 
namespace ActiveTest
{
    public partial class Test : Page
    {
        protected void CreatePDF(object sender, EventArgs e)
        {
            string fileName = "PrintView";
            Document doc = new Document();
            string f = Server.MapPath(string.Format("~/Temp/{0}.pdf",fileName));
            PdfWriter.GetInstance(doc, new FileStream(f, FileMode.Create));
            doc.Open();
            ///
            /// A4 Size
            ///
            int width = 585;
            int height = 842;
            string url = this.Request.Url.ToString() + "?m=Print";
            Image thumbnail = new Image(url, width, height, width, height, Image.ImageMethod.Url);
            Bitmap image = thumbnail.GenerateImage();
            string p = Server.MapPath(string.Format("~/Temp/{0}.bmp",fileName));
            image.Save(p);
            iTextSharp.text.Image i = iTextSharp.text.Image.GetInstance(p);
            doc.Add(i);
            doc.Close();
            File.Delete(p);
            ///
            /// use pdf file
            ///
            File.Delete(f);            
        }
    }
    public class Image
    {
        public enum ImageMethod { Url, Html };
        public string Url { getset; }
        public Bitmap Current { getset; }
        public int Width { getset; }
        public int Height { getset; }
        public int BrowserWidth { getset; }
        public int BrowserHeight { getset; }
        public string Html { getset; }
        public ImageMethod Method { getset; }
 
        public Image(string data, int browserWidth, int browserHeight, int width,
                                        int height, ImageMethod method)
        {
            this.Method = method;
            if (method == ImageMethod.Url)
                this.Url = data;
            else if (method == ImageMethod.Html)
                this.Html = data;
            this.BrowserWidth = browserWidth;
            this.BrowserHeight = browserHeight;
            this.Height = height;
            this.Width = width;
        }
        public Bitmap GenerateImage()
        {
            Thread thread = new Thread(new ThreadStart(GenerateThumbnailInteral));
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
            return Current;
        }
        private void GenerateThumbnailInteral()
        {
            WebBrowser webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            if (this.Method == ImageMethod.Url)
                webBrowser.Navigate(this.Url);
            else webBrowser.DocumentText = this.Html;
            webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
            while (webBrowser.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents();
            webBrowser.Dispose();
        }
        private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser webBrowser = (WebBrowser)sender;
            webBrowser.ClientSize = new Size(this.BrowserWidth, this.BrowserHeight);
            webBrowser.ScrollBarsEnabled = false;
            this.Current = new Bitmap(webBrowser.Bounds.Width, webBrowser.Bounds.Height);
            webBrowser.BringToFront();
            webBrowser.DrawToBitmap(Current, webBrowser.Bounds);
            this.Current = (Bitmap)Current.GetThumbnailImage(Width, Height, nullIntPtr.Zero);
        }
    }
}

References:
  1. iTextSharp - Working with images

How to play a sound on error


Demo: 

<%@ Page Language="C#" %>
<html>
<head id="Head1" runat="server">
    <script language="javascript" type="text/javascript">
        function PlaySound() {
            if (typeof (Page_ClientValidate) == "function") {
                Page_ClientValidate();
                if (!Page_IsValid) {
                    var thissound = eval("document.error");
                    thissound.Play();
                    return false;
                }
                return true;
            }
        }
    </script>
</head>
<body style="padding:0margin:0">
    <form runat="server" id="form1">
        <asp:TextBox runat="server" ID="txtName" />
        <asp:RequiredFieldValidator runat="server" ID="rvalName" 
            ErrorMessage="Error" ControlToValidate="txtName" Display="Dynamic" />    
        <hr />
        <asp:Button runat="server" ID="btnSave" Text="Save" OnClientClick="javascript:PlaySound()" />
        <embed src="Resources/Error.wav" autostart="false" width="0" 
            height="0" name="error" enablejavascript="true"></embed>
    </form>
</body>
</html>

Saturday, October 09, 2010

How to convert PDF files:

  1. Convert web page to PDF file - All methods
  2. Convert PDF file text file
  3. Print a page as PDF using iTextSharp
  4. How to print long page with multiple pages as PDF

How to convert PDF to text file

We can use PDFBox open source library.
Download PDFBox .NET version

Download source files

You need three four dll files from the bin folder where you extracted the download rar file.

PDFBox-0.7.3.dll
IKVM.GNU.Classpath
IKVM.Runtime
FontBox-0.1.0-dev

using following assembiles:

using System.Security;
using org.pdfbox.pdmodel;
using org.pdfbox.util;
 
Having a pdf file like below:


We can convert PDF to text like below:

PDDocument doc = PDDocument.load(Server.MapPath("~/StudentsResults.pdf"));
PDFTextStripper stripper = new PDFTextStripper();
string text = stripper.getText(doc);
File.WriteAllText(Server.MapPath("~/StudentsResults.txt"), text);

Output will be like this: 

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...