iPhone Development using only jQuery

http://www.jqtouch.com/

No Comments

Character Encoding for HTML and XML

HTML
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >

XHTML (note the slash at the end)
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

XML
<?xml version="1.0" encoding="utf-8" ?>

Reference
http://www.w3.org/International/O-charset

No Comments

ASP.Net URL/Request Paths

Here’s a good article on the different properties:

http://www.xcess.info/request_url_parameters_details_asp_net_aen.aspx

Request.Url
Full URL : http://localhost:2000/virtual_dir/myrep/page.aspx?q=qvalue

Request.ApplicationPath : /virtual_dir
Request.CurrentExecutionFilePath : /virtual_dir/myrep/page.aspx
Request.FilePath : /virtual_dir/myrep/page.aspx
Request.Path : /virtual_dir/myrep/page.aspx
Request.PhysicalApplicationPath : d:\Inetpub\wwwroot\Websitename\virtual_dir\
Request.QueryString : /virtual_dir/myrep/page.aspx?q=qvalue
Request.Url.AbsolutePath : /virtual_dir/myrep/page.aspx
Request.Url.AbsoluteUri : http://localhost:2000/virtual_dir/myrep/page.aspx?q=qvalue
Request.Url.Host : localhost
Request.Url.Authority : localhost:2000
Request.Url.LocalPath : /virtual_dir/myrep/page.aspx
Request.Url.PathAndQuery : /virtual_dir/myrep/page.aspx?q=qvalue
Request.Url.Port : 2000
Request.Url.Query : ?q=qvalue
Request.Url.Scheme : http
Request.Url.Segments : /
virtual_dir/
myrep/
page.aspx

No Comments

jQuery Modal Quick Example

<!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>Untitled Page</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js" type="text/javascript"></script>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.0/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />   

    <script type="text/javascript">

        $(document).ready(function() {

            $("#dialog").dialog({
              autoOpen: false,
              modal: true,
              resizable:false,
              overlay: {
                  backgroundColor: '#000',
                  opacity: 0.5
              },
              buttons: {
                      "Cancel": function() {
                          $(this).dialog("close");
                      },
                      "No": function() {
                          //your javascript here
                          $(this).dialog("close");
                      },
                      "Yes": function() {
                          //your javascript here
                          window.location.href = "http://google.com"; //redirect example
                      }
                  }
            });

            $("#mybutton").click(function() {
              $("#dialog").dialog("open");
            });

      });

    </script>

</head>
<body>

    <input type="button" id="mybutton" class="myclass" value="Click Me" />

    <div id="dialog" title="Hola Ivy!">
        <p>
            Are you sure?
       </p>
    </div>

</body>
</html>

1 Comment

Adding an IP address to your server’s NIC in Windows Server 2008

Assuming you have the IP and the subnet mask, you can add it with the following steps:

  • Open up you command prompt (cmd.exe)
  • type ‘netsh interface ipv4
  • type:  add address “Local Area Connection” [ip address] [subnet mask]

That’s it.

No Comments

Generate PDF files using C# and FO.Net

Given that you have an XSL-FO template ready to go, it’s pretty straight-forward to generate a PDF using FO.Net.

It’s not easy to create an XSL-FO from scratch, and I wouldn’t care to. There are programs that can convert your HTML into XSL-FO, though they usually cost a lot of money. You can create one on the cheap using HTML2FO though. The page shows the HTML tags that it supports. Run the application on the commandline and pass two parameters like this:

HTML2FO.exe  <inputHtmlFile>.html  <outputFileName>.fo

You can then use that output file to render a PDF using Fo.Net. I created a wrapper that takes in an XSL-FO file and an XML file and returns a PDF.

FonetButler.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Fonet;
using Fonet.Pdf;
using Fonet.Render;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Xml.Linq;

namespace FonetButler{
    public class PDF
    {
        public static MemoryStream Render(XElement XmlData, string XslFoPath)
        {
            //get the xsl transform
            MemoryStream transformed = Transform(XmlData, XslFoPath);

            //allocate memory for the pdf
            MemoryStream pdffile = new MemoryStream();

            //create the pdf
            FonetDriver driver = FonetDriver.Make();
            driver.Render(transformed, pdffile);

            //return the pdf stream
            return new MemoryStream(pdffile.ToArray());
        }

        public static MemoryStream Render(string XmlDataPath, string XslFoPath)
        {
            //get the xsl transform
            MemoryStream transformed = Transform(XmlDataPath, XslFoPath);

            //allocate memory for the pdf
            MemoryStream pdffile = new MemoryStream();

            //create the pdf
            FonetDriver driver = FonetDriver.Make();
            driver.Render(transformed, pdffile);

            //return the pdf stream
            return new MemoryStream(pdffile.ToArray());
        }

        public static MemoryStream Render(XElement XmlData, Stream XslFoStream)
        {
            //get the xsl transform
            MemoryStream transformed = Transform(XmlData, XslFoStream);

            //allocate memory for the pdf
            MemoryStream pdffile = new MemoryStream();

            //create the pdf
            FonetDriver driver = FonetDriver.Make();
            driver.Render(transformed, pdffile);

            //return the pdf stream
            return new MemoryStream(pdffile.ToArray());
        }

        public static void Render(XElement XmlData, Stream XslFoStream, string OutputFilePath)
        {
            //get the xsl transform
            MemoryStream transformed = Transform(XmlData, XslFoStream);

            //allocate memory for the pdf
            MemoryStream pdffile = new MemoryStream();

            //create the pdf
            FonetDriver driver = FonetDriver.Make();
            driver.Render(transformed, pdffile);

            //reopen the stream
            pdffile = new MemoryStream(pdffile.ToArray());

            //create the file
            FileStream f = new FileStream(OutputFilePath, FileMode.Create, FileAccess.ReadWrite);
            f.Write(pdffile.ToArray(), 0, (int)pdffile.Length);
            f.Close();
        }

        public static void Render(string XmlDataPath, string XslFoPath, string OutputFilePath)
        {
            //get the xsl transform
            MemoryStream transformed = Transform(XmlDataPath, XslFoPath);

            //allocate memory for the pdf
            MemoryStream pdffile = new MemoryStream();

            //create the pdf
            FonetDriver driver = FonetDriver.Make();
            driver.Render(transformed, pdffile);

            //reopen the stream
            pdffile = new MemoryStream(pdffile.ToArray());

            //create the file
            FileStream f = new FileStream(OutputFilePath, FileMode.Create, FileAccess.ReadWrite);
            f.Write(pdffile.ToArray(), 0, (int)pdffile.Length);
            f.Close();
        }

        public static void Render(XElement XmlData, string XslFoPath, string OutputFilePath)
        {
            //get the xsl transform
            MemoryStream transformed = Transform(XmlData, XslFoPath);

            //allocate memory for the pdf
            MemoryStream pdffile = new MemoryStream();

            //create the pdf
            FonetDriver driver = FonetDriver.Make();
            driver.Render(transformed, pdffile);

            //reopen the stream
            pdffile = new MemoryStream(pdffile.ToArray());

            //create the file
            FileStream f = new FileStream(OutputFilePath, FileMode.Create, FileAccess.ReadWrite);
            f.Write(pdffile.ToArray(), 0, (int)pdffile.Length);
            f.Close();
        }

        private static MemoryStream Transform(XElement XmlData, Stream XslFo)
        {
            XmlWriter writer = null;
            try
            {
                //load the xsl-fo 
                XslCompiledTransform xslTrans = new XslCompiledTransform();
                xslTrans.Load(XmlReader.Create(XslFo));

                //create the output stream
                MemoryStream result = new MemoryStream();
                writer = XmlWriter.Create(result, null);

                //create the xml reader for the data
                XmlReader data = XmlData.CreateReader();

                //do the actual transform of xml
                xslTrans.Transform(data, null, writer);

                writer.Close();

                return new MemoryStream(result.ToArray());
            }
            catch (Exception e)
            {
                if (writer != null) writer.Close();
                throw e;
            }
        }

        private static MemoryStream Transform(string XmlDataPath, string XslFoPath)
        {
            XmlWriter writer = null;
            try
            {
                //load the Xml doc
                XPathDocument myXPathDoc = new XPathDocument(XmlDataPath);

                //load the Xsl
                XslCompiledTransform xslTrans = new XslCompiledTransform();
                xslTrans.Load(XmlDataPath);

                //create the output stream
                MemoryStream result = new MemoryStream();
                writer = XmlWriter.Create(result, null);

                //do the actual transform of Xml
                xslTrans.Transform(myXPathDoc, null, writer);

                writer.Close();

                return new MemoryStream(result.ToArray());
            }
            catch (Exception e)
            {
                if (writer != null) writer.Close();
                throw e;
            }
        }

        private static MemoryStream Transform(XElement XmlData, string XslFoPath)
        {
            XmlWriter writer = null;
            try
            {
                //load the xsl
                XslCompiledTransform xslTrans = new XslCompiledTransform();
                xslTrans.Load(XslFoPath);

                //create the output stream
                MemoryStream result = new MemoryStream();
                writer = XmlWriter.Create(result, null);

                //create the xml reader for the data
                XmlReader data = XmlData.CreateReader();

                //do the actual transform of xml
                xslTrans.Transform(data, null, writer);

                writer.Close();

                return new MemoryStream(result.ToArray());
            }
            catch (Exception e)
            {
                if (writer != null) writer.Close();
                throw e;
            }
        }
    }
}

Sample Code

Creating a physical PDF in classic ASP.Net:

protected void Page_Load(object sender, System.EventArgs e)
{
    //a physical xml file
    XElement xmldata = XElement.Load(Server.MapPath("~/Content/XML/Application.xml"));

    //a physical xsl file
    string xslfo = Server.MapPath("~/Content/XML/Application.xslt");

    //the path for the physical file
    string outputPath = Server.MapPath("~/Content/XML/Application.pdf");

    //create the pdf
    FonetButler.PDF.Render(xmldata, xslfo, outputPath);
}

Generate a PDF in memory in classic ASP.Net:

protected void Page_Load(object sender, System.EventArgs e)
{
    //a physical xml file
    XElement xmldata = XElement.Load(Server.MapPath("~/Content/XML/Application.xml"));

    //a physical xsl file
    string xslfo = Server.MapPath("~/Content/XML/Application.xslt");

    //create the pdf file stream
    MemoryStream pdf = FonetButler.PDF.Render(xmldata, xslfo);

    //prepare output stream
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=Application.pdf");
    Response.Buffer = true;
    Response.Clear();
    Response.OutputStream.Write(pdf.ToArray(), 0, (int)pdf.Length);
    Response.OutputStream.Flush();
    Response.End();
}

Create a physical PDF in MVC:

public ViewResult CreatePdf()
{
    //xml file
    XElement xmldata = XElement.Load(Server.MapPath("~/Content/XML/Application.xml"));

    //xsl file
    string xslfo = Server.MapPath("~/Content/XML/Application.xslt");

    //the path for the physical file
    string outputPath = Server.MapPath("~/Content/XML/Application.pdf");

    //the pdf file stream
    FonetButler.PDF.Render(xmldata, xslfo, outputPath);

    return View();
}

Generating a PDF in memory using MVC:

public FileStreamResult ServePdf()
{
    //xml file
    XElement xmldata = XElement.Load(Server.MapPath("~/Content/XML/Application.xml"));

    //xsl file
    string xslfo = Server.MapPath("~/Content/XML/Application.xslt");

    //the pdf file stream
    MemoryStream pdf = FonetButler.PDF.Render(xmldata, xslfo);

    return new FileStreamResult(pdf, "application/pdf");
}

10 Comments

XML from SQL using Correlated Subqueries

It’s really easy to get an XML object from an SQL database and structure the elements in anyway you like. If you’re familiar with creating SELECT statements, you’ll be a pro with this cool way of creating XML objects to feed your application or whatever else.

So, you have your plain vanilla select query:

SELECT column1, column2 FROM table1 AS t1

Now just replace column2 with another SELECT statement that has a WHERE clause relating it to the parent SELECT statement and you’ve got yourself a correlated subquery.

SELECT column1, (SELECT * FROM table2 AS t2 WHERE t1.key=t2.key) FROM table1 AS t1

Now, it’s easy to turn this into XML by adding this at the end of each SELECT statement:

FOR XML PATH ('myElementName'), TYPE

Here’s my example using the AdventureWorksLT2008 database:

DECLARE @SalesOrderNumber AS varchar(10) = 'SO71774';

SELECT OrderDate, SalesOrderNumber, AccountNumber, SubTotal, TotalDue
    ,-- Order Details
    (SELECT p.Name, p.ProductNumber, p.ListPrice, OrderQty, LineTotal
        FROM SalesLT.SalesOrderDetail AS sod
            INNER JOIN SalesLT.Product p ON p.ProductID=sod.ProductID
        WHERE sod.SalesOrderID=soh.SalesOrderID
        FOR XML PATH ('Product'), TYPE, ROOT('Products'))
    ,-- Customer Information
    (SELECT  FirstName, MiddleName, LastName, EmailAddress
        FROM SalesLT.Customer AS c
        WHERE c.CustomerID=soh.CustomerID
        FOR XML PATH ('Customer'), TYPE)
    ,-- Shipping Address
    (SELECT  AddressLine1, City, StateProvince, CountryRegion, PostalCode
        FROM SalesLT.Address AS a
        WHERE a.AddressID=soh.ShipToAddressID
        FOR XML PATH ('ShippingAddress'), TYPE)
FROM SalesLT.SalesOrderHeader soh
WHERE soh.SalesOrderNumber=@SalesOrderNumber
FOR XML PATH('SalesOrder'), ROOT('root')

Running this query gives you the following output:

<root>
  <SalesOrder>
    <OrderDate>2004-06-01T00:00:00</OrderDate>
    <SalesOrderNumber>SO71774</SalesOrderNumber>
    <AccountNumber>10-4020-000609</AccountNumber>
    <SubTotal>880.3484</SubTotal>
    <TotalDue>972.7850</TotalDue>
    <Products>
      <Product>
        <Name>ML Road Frame-W - Yellow, 48</Name>
        <ProductNumber>FR-R72Y-48</ProductNumber>
        <ListPrice>594.8300</ListPrice>
        <OrderQty>1</OrderQty>
        <UnitPriceDiscount>0.0000</UnitPriceDiscount>
        <LineTotal>356.898000</LineTotal>
      </Product>
      <Product>
        <Name>ML Road Frame-W - Yellow, 38</Name>
        <ProductNumber>FR-R72Y-38</ProductNumber>
        <ListPrice>594.8300</ListPrice>
        <OrderQty>1</OrderQty>
        <UnitPriceDiscount>0.0000</UnitPriceDiscount>
        <LineTotal>356.898000</LineTotal>
      </Product>
    </Products>
    <Customer>
      <FirstName>David</FirstName>
      <LastName>Hodgson</LastName>
      <EmailAddress>david16@adventure-works.com</EmailAddress>
    </Customer>
    <ShippingAddress>
      <AddressLine1>99700 Bell Road</AddressLine1>
      <City>Auburn</City>
      <StateProvince>California</StateProvince>
      <CountryRegion>United States</CountryRegion>
      <PostalCode>95603</PostalCode>
    </ShippingAddress>
  </SalesOrder>
</root>

You can then package this into a stored procedure, passing it the OrderNumber, and get a nicely formatted XML to use to generate PDFs or whatever else.

Cheers

No Comments

Creating a PDF with iTextSharp and ASP.Net MVC 2

Here’s a simple example to create a PDF on the fly and provide it as a streaming download, rather than creating a physical file:

public FileStreamResult About()
{
    //mem buffer
    MemoryStream ms = new MemoryStream();

    //the document
    Document document = new Document();

    //the writer
    PdfWriter.GetInstance(document, ms);//fs);

    //open the document
    document.Open();

    //add header image
    //Image headerlogo = Image.GetInstance("C:\\Temp\\citylogo.png");
    //document.Add(headerlogo);

    //create the fonts
    BaseFont timesNormal = BaseFont.CreateFont(BaseFont.TIMES_ROMAN,
                                               BaseFont.CP1252,
                                               BaseFont.NOT_EMBEDDED);
    Font fontNormal = new Font(timesNormal, 10, Font.NORMAL);
    Font fontH1 = new Font(timesNormal, 16, Font.NORMAL);

    //add a paragraph
    document.Add(new Paragraph("Instructions", fontH1));
    document.Add(new Paragraph(@"Lorem ipsum dolor sit amet, consectetur adipisicing
                                elit, sed do eiusmod tempor incididunt ut labore et
                                dolore magna aliqua. Ut enim ad minim.", fontNormal));

    document.Add(new Paragraph("\n")); //better way to do a newline?

    //add a table
    PdfPTable table = new PdfPTable(3);
    PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns"));
    cell.Colspan = 3;
    cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
    table.AddCell(cell);

    table.AddCell("Row 1 Col 1");
    table.AddCell("Row 1 Col 2");
    table.AddCell("Row 1 Col 3");
    table.AddCell("Row 2 Col 1");
    table.AddCell("Row 2 Col 2");
    table.AddCell("Row 2 Col 3");

    document.Add(table);

    //close the document
    document.Close();

    //prepare output stream
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=MyPdfName.pdf");
    Response.Buffer = true;
    Response.Clear();
    Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
    Response.OutputStream.Flush();
    Response.End();

    return new FileStreamResult(Response.OutputStream,"application/pdf");
}

You’ll need to download the iTextSharp DLL and give reference to it in your project.

And that’s the way the cookie crumbles.

13 Comments

DB Hits Performance Booster Tip

Using XML to pass data for an Stored Procedure to handle using some logic, can save a lot of database hits and greatly improve the performance of your application.

Here’s an article describing a simple implementation:
http://www.c-sharpcorner.com/UploadFile/skumaar_mca/XMLDmlOperation07292009123939PM/XMLDmlOperation.aspx

, , ,

No Comments

For Keeping Up-To-Date

News
http://www.infoworld.com/d/developer-world/news
http://slashdot.org/
http://dotnetslackers.com/
http://www.dotnetcurry.com/
http://dotnetkicks.com/
Blogs
http://www.hanselman.com/blog/
http://blog.wekeroad.com/
http://weblogs.asp.net/scottgu/
http://haacked.com/
http://devlicio.us/blogs/
References
http://dotnetperls.com/
Podcasts
http://www.asp.net/learn/podcasts/
http://www.hanselminutes.com/
Videos
http://channel9.msdn.com/
http://channel8.msdn.com
http://on10.net/
http://www.visitmix.com/
http://edge.technet.com/

No Comments