Friday, October 08, 2010

NHibernate


What is NHibernate?

NHibernate is an ORM (Object Relational Mapping) system. Providing an xml file which maps table schema to the class members, NHibernate is capable of managing a persistent data objects for respective mapped classes. As we already realised there is a gap between object oriented entity modal and relational data modal. NHibernate fills this gap providing HQL (Hibernate Query Language) to query objects rather than relational queries.

How it works?

Key object is ISession. ISession holds a persistent pool of data objects. ISessionFactory is the origin of ISession. ISessionFactory uses XML mappings (as a first level cache) and connection provider to create ISession. Connection provider uses IDriver to create connections. IDriver uses NHibernate configuration (XML file containing database query string and NHibernate settings) to create client specific connection string and manage optimistic behaviour based on the client.



  1. ISessionFactory:
    1. Factory for Session
    2. Client of IConnection Provider
    3. Has immutable cache compiled mappings (level1) derived from XML mappings
    4. Optional second level cache of data which might be useful between transactions.
  2. ISession:
    1. Short lived objects between application and data store.
    2. Factory for transaction.
    3. First level cache of persistent objects
    4. Used in object graphs and navigating
    5. Can expand across multiple transactions
    6. In the session all the persistent objects get associated with a CLR identity in the object map which is equivalent to the persistent identity. 
  3. ITransaction:
    1. A short lived object that perform unit of work
    2. In meaning of it terms data update/Inset or delete
    3. While transaction is on progress all the underline relations are read-only
    4. Get generated from ISession
    5. ISession might span several ITransactions
  4. ITransactionFactory:
    1. Not exposed to the application but can be extended by the developer
    2. IConnectionProvider:
    3. Factory for ADO.NET connections/commands
    4. Abstracts application from vender specific implementation of IDbConnection/IDbCommand.
      Can be extended by developer
  5. IDriver:
    1. Abstracts capabilities of different Ado.NET providers
    2. Handles parameter naming / type conversions and other supported Ado.NET features.
Configuration

NHibernate settings and appropriate connection string to the data store. Includes driver classes, dialect

Example:
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string_name">SqlServer</property>
    <property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory</property>
    <property name="show_sql">true</property>
  </session-factory>
</hibernate-configuration>

Mappings

In a formal notation, mappings are the relationship between relation structure and class structure. In simple terms mappings are the relationship between class name and table name plus table columns and class properties.

Example:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"                    
                   assembly="ActiveTest"                    
                   namespace="ActiveTest">
  <class name="Product">
    <id name="Id" />
    <property name="Name" />
    <property name="Description" />    
  </class>
</hibernate-mapping>

Table:


Objects and collection states:
  1. Transient: - The transient has not and never been associated with a NHibernate session (persistent context). It has no identity (primary key value)
  2. Persistent: - Data objects that are currently associated with NHibernate session (persistent context) called as persistent objects. They are associated with primary key value. Object may represent a row of a relation. Single primary key value can represent one and only one object in the persistent context. For a persistent object NHibernate guarantees that the persistent identity is equivalent to the CLR identity.
  3. Detached: - Objects been associated with persistent context but now the context is closed. For detached objects NHibernate makes no guarantees about the association between persistent context identity and the CLR identity.
References:
  1. NHibernate Architecture
  2. NHibernate Architecture

Thursday, October 07, 2010

How to serve files located out the virtual folder

  1. Serving an Image
  2. Serving a PDF file

How to serve pdf file located outside the virtual folder

We can use a Generic Hanlder for this:
Markup:
<a href="GenericHandler.ashx?f=Application" title="Application">View Application</a>
Generic Handler:
public class GenericHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string f = context.Request.QueryString.Get("f");
        ///
        /// Option 1: from server location.
        ///
        f = @"\\servername\documents\" + f + ".pdf";
        ///
        /// Option 2: from disk location
        ///
        f = @"c:\data\documents\" + f + ".pdf";
        context.Response.Clear();
        context.Response.ContentType = "Application/pdf";
        context.Response.WriteFile(f);
        HttpContext.Current.ApplicationInstance.CompleteRequest();
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

How to serve image located outside the virtual folder

You can use GenericHander for this:
Markup:
<img src="GenericHandler.ashx?f=Thumbnail" alt="Thumbnail" />
Generic Handler:
public class GenericHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string f = context.Request.QueryString.Get("f");
        ///
        /// Option 1: from server location.
        ///
        f = @"\\servername\images\" + f + ".jpg";
        ///
        /// Option 2: from disk location
        ///
        f = @"c:\data\images\" + f + ".jpg";
        System.Drawing.Image image = System.Drawing.Image.FromFile(f);
        context.Response.Clear();
        context.Response.ClearHeaders();
        image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
        context.Response.ContentType = "image/jpeg";
        HttpContext.Current.ApplicationInstance.CompleteRequest();
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

How to apply styles to menu items (Asp.net 3.5 Menu)

Demo:

With Basic Styles:

<%@ Page Language="C#" %>
<html>
<head id="Head1" runat="server">
    <style> 
        .StaticItem { background:#eeeborder:solid 1px #0f0margin:1px; }
        .DynamicItem { background-color:#eeeborder:solid 1px #00fmargin:1pxz-index:100; }
        .DynamicHighlight { background-color:Aquaborder:solid 1px #f00; }
        .StaticHighlight { background-color:Yellowborder:solid 1px #f00; }
        .DyanamicSelected { background-color:Limecolor:#fff; }        
        .StaticSelected { background-color:Fuchsiacolor:#fff; } 
    </style>
    <script runat="server">
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!this.IsPostBack)
                for (int i = 0; i < 5; i++)
                {
                    MenuItem item = new MenuItem("Item" + i);
                    for (int j = 0; j < 5; j++)
                    {
                        MenuItem child = new MenuItem("Child" + j);
                        for (int k = 0; k < 5; k++)
                        {
                            MenuItem grandChild = new MenuItem("Grand Child" + k);
                            child.ChildItems.Add(grandChild);
                        }
                        item.ChildItems.Add(child);
                    }
                    this.mnuNavigation.Items.Add(item);
                }
        }
    </script>
</head>
<body>
    <form runat="server" id="form1">
        <asp:Menu runat="server" ID="mnuNavigation" CssClass="menu">
            <DynamicMenuItemStyle CssClass="DynamicItem" />
            <StaticMenuItemStyle CssClass="StaticItem" />
            <DynamicHoverStyle CssClass="DynamicHighlight" />
            <StaticHoverStyle CssClass="StaticHighlight" />
            <DynamicSelectedStyle CssClass="DyanamicSelected" />
            <StaticSelectedStyle CssClass="StaticSelected" />
        </asp:Menu>
    </form>
</body>
</html>

With image background.
Styles:
.StaticItem { background-image:url('Images/StaticItem.gif')border:solid 1px #0f0margin:1px; }
.DynamicItem { background-image:url('Images/DynamicItem.gif')border:solid 1px #00fmargin:1pxz-index:100; }
.DynamicHighlight { background-image:url('Images/DynamicHighlight.gif')border:solid 1px #f00; }
.StaticHighlight { background-image:url('Images/StaticHighlight.gif')border:solid 1px #f00; }
.DyanamicSelected { background-image:url('Images/DyanamicSelected.gif')color:#fff; }        
.StaticSelected { background-image:url('Images/StaticSelected.gif')color:#fff; } 

How to move items between two ListBoxes

Demo:

<%@ Page Language="C#" %>
<html>
<head id="Head1" runat="server">
    <script runat="server">
        protected void MoveS(object sender, EventArgs e)
        {
            this.lstSource.ClearSelection();
            if (this.lstDestination.SelectedIndex > -1)
            {
                string s = this.lstDestination.SelectedValue;
                this.lstSource.Items.Add(this.lstDestination.SelectedItem);
                this.lstDestination.Items.Remove(this.lstDestination.SelectedItem);
                this.lstSource.SelectedValue = s;
            }
        }
        protected void MoveD(object sender, EventArgs e)
        {
            this.lstDestination.ClearSelection();
            if (this.lstSource.SelectedIndex > -1)
            {
                string s = this.lstSource.SelectedValue;
                this.lstDestination.Items.Add(this.lstSource.SelectedItem);
                this.lstSource.Items.Remove(this.lstSource.SelectedItem);
                this.lstDestination.SelectedValue = s;
            }
        }
        protected void Edit(object sender, EventArgs e)
        {
            this.hdnSelection.Value = string.Empty;
            this.txtEdit.Text = string.Empty;
            if (this.lstSource.SelectedIndex > -1)
            {
                this.txtEdit.Text = this.lstSource.SelectedValue;
                this.hdnSelection.Value = "S";
                this.lstSource.Items.Remove(this.lstSource.SelectedItem);
            }
            else if (this.lstDestination.SelectedIndex > -1)
            {
                this.txtEdit.Text = this.lstDestination.SelectedValue;
                this.hdnSelection.Value = "D";
                this.lstDestination.Items.Remove(this.lstDestination.SelectedItem);
            }
            if (!string.IsNullOrEmpty(this.txtEdit.Text))
            {
                this.pnlEdit.Visible = true;
                this.pnlItems.Enabled = false;
            }
        }
        protected void Save(object sender, EventArgs e)
        {
            if (this.hdnSelection.Value.Equals("D"))
                this.lstDestination.Items.Add(new ListItem(this.txtEdit.Text));
            else if (this.hdnSelection.Value.Equals("S"))
                this.lstSource.Items.Add(new ListItem(this.txtEdit.Text));
            this.txtEdit.Text = string.Empty;
            this.hdnSelection.Value = string.Empty;
            this.pnlEdit.Visible = false;
            this.pnlItems.Enabled = true;
        }
        protected void ClearDestination(object sender, EventArgs e)
        {
            this.lstDestination.ClearSelection();
        }
        protected void ClearSource(object sender, EventArgs e)
        {
            this.lstSource.ClearSelection();
        }
    </script>
</head>
 
<body>
    <form runat="server" id="form1">
        <asp:ScriptManager runat="server" ID="pageScriptManager" />
        <asp:UpdatePanel runat="server" ID="upnlEdit">
            <ContentTemplate>
                <asp:Panel runat="server" ID="pnlItems">
                    <asp:ListBox runat="server" ID="lstSource" 
                        OnSelectedIndexChanged="ClearDestination" AutoPostBack="true">
                        <asp:ListItem>Car</asp:ListItem>
                        <asp:ListItem>Van</asp:ListItem>
                        <asp:ListItem>Truck</asp:ListItem>
                        <asp:ListItem>Bike</asp:ListItem>
                        <asp:ListItem>Cycle</asp:ListItem>
                    </asp:ListBox>
                    <asp:ListBox runat="server" ID="lstDestination" 
                        OnSelectedIndexChanged="ClearSource" AutoPostBack="true" />
                </asp:Panel>
                <hr />
                <asp:Button runat="server" ID="btnMoveD" OnClick="MoveD" Text=">>" />
                <asp:Button runat="server" ID="btnMoveS" OnClick="MoveS" Text="<<" />
                <asp:Button runat="server" ID="btnEdit" Text="Edit" OnClick="Edit" />
                <hr />
                <asp:Panel runat="server" ID="pnlEdit" Visible="false">
                    <asp:TextBox runat="server" ID="txtEdit"></asp:TextBox>
                    <asp:RequiredFieldValidator runat="server" ID="rvalEdit" 
                        ControlToValidate="txtEdit" Display="Dynamic" ErrorMessage="*" ValidationGroup="Edit" />
                    <asp:HiddenField runat="server" ID="hdnSelection" />
                    <asp:Button runat="server" ID="btnSave" OnClick="Save" Text="Save"  ValidationGroup="Edit" />
                </asp:Panel>
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>

Saturday, October 02, 2010

How to convert page to a PDF (All methods)


Many thanks to Jessica Cao who orginally publised this post in Asp.net fourm.


Solution 1: Use an open-source .NET PDF library. Sample list:  
Solution 2: Use a commercial .NET PDF library. Sample list:
Solution 3: Use activePDF WebGrabber to convert any URL output to PDF on-the-fly.
Solution 4: Use a report generator like Crystal Reports or SQL Server Reporting Services to render to PDF.

How to get/add/change html in asp.net page

  1. How to add html
  2. How to get and change rendered output html

How to write some html to asp.net page output stream

<%@ Page Language="C#" %>
<html>
<head id="Head2" runat="server">
    <script runat="server">
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ///
            /// Method 1:
            ///
            string htmlInput = "<input type=\"text\" id=\"inputId\" name=\"inputName\" value=\"Hello World\" />";                        
            this.phHtmlControl.Controls.Add(new Literal() { Text = htmlInput });
            ///
            /// Method 2:
            ///
            this.phHtmlControl.Controls.Add(
                ParseControl("<asp:CheckBox ID=\"chkDisabled\" Text=\"Disabled\" runat=\"server\" />"));            
        }
        protected void Save(object sender, EventArgs e)
        {
            ///
            /// Method 1
            ///
            string htmlInputValue = this.Request.Form.Get("inputName");
            ///
            /// Method 2
            ///
            CheckBox chkDisabled = (CheckBox)FindControl("chkDisabled");
            if (chkDisabled != null)
                bool disabled = chkDisabled.Checked;
        }
    </script>
</head>
<body>
    <form id="form2" runat="server">
        <asp:PlaceHolder runat="server" ID="phHtmlControl" />
        <asp:Button runat="server" ID="btnSave" Text="Save" OnClick="Save" />
    </form>
</body>
</html

Friday, October 01, 2010

How to show the progress of a request


Demo:

This approach is suitable if your request delays due to content downloading, such as images and other body content. Page response time cannot be predicted. For the first page load it gets all the data while subsequent responses get cached data. So if you provide constant delay on progress users may lose the joy or browser cache and improved performance by modern browsers. On the other hand, if your request gets delayed by execution of the page such as database calls, web service calls etc, you may consider handing long running operations.
  1. Simple example - only strat message and end message
  2. Detailed example - including progress bar and step processing results
Back this article. Couple of points understand:
  • At the end of the page, we have the JavaScript to hide the progress bar.
  • However, if you hide the progress bar immediately, user still notify a blank space.
  • So if you certain that page loading take a while about 2-4 seconds it is better you delay the hide statement at the end of the page.
setTimeout("document.getElementById('progress').style.display = 'none'", 5000);
 Example:
<%@ Page Language="C#" %>
<html>
<head runat="server">
    <style type="text/css">
        div.DialogueBackground 
        { 
            position:absolute; 
            width:100%; 
            height:100%; 
            top:0; 
            left:0;             
            text-align:center; 
        }
        div.DialogueBackground div.Dialogue 
        {
            width:300px; 
            height:100px; 
            position:absolute; 
            left:50%; 
            top:50%; 
            margin-left:-150px; 
            margin-top:-50px; 
            border:solid 10px #555; 
            background-color:#fff;                         
        }
        div.DialogueBackground div.Dialogue  p { padding:20px 10px; }
    </style>
    <script runat="server">
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            ///
            /// one MB size of request and resposne. 
            ///
            for (int i = 0; i < 1000; i++)
            {
                Image img = new Image() { ImageUrl = "SomeImage" + i + ".png" };
                img.Attributes.Add("style""display:none");
                this.phContent.Controls.Add(img);
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div class="DialogueBackground" id="progress">
            <div class="Dialogue">
                <p>Please wait...</p>
                <img src="::root/::images/Progress.gif" alt="Processing" />
            </div>
        </div>
        <asp:Button runat="server" ID="btnSave" Text="Save" 
            OnClientClick="javascript:document.getElementById('progress').style.display = 'block'" />
        <asp:PlaceHolder runat="server" ID="phContent" />
    </form>
    <script language="javascript" type="text/javascript">
        setTimeout("document.getElementById('progress').style.display = 'none'", 5000);
    </script>
</body>
</html>

How to handle asynchronous request errors and reqeust end event in JavaScript

<script language="javascript">
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
    function EndRequestHandler(sender, args) {
        if (args.get_error() != undefined) {
            if ((args.get_response().get_statusCode() == '12007')
                 || (args.get_response().get_statusCode() == '12029')) {
                alert('Time-out Error');
                args.set_errorHandled(true);
            }
        }
    }
</script>

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