Pages

Friday, March 23, 2012

Save View State in Session Variable

ViewState can be customized to be stored in a Session or Cache object. It
is done by overriding the 'SavePageStateToPersistenceMedium' and
'LoadPageStateFromPersistenceMedium' methods.


Add Following Two Override Method in to code behind file:

Step 1:

  Protected Overrides Function LoadPageStateFromPersistenceMedium() As Object
        If Session("ViewState") <> Nothing Then
            Return (New LosFormatter().Deserialize(DirectCast(Session("ViewState"), String)))
        End If
    End Function

Step 2:

    Protected Overrides Sub SavePageStateToPersistenceMedium(ByVal state As Object)
        Dim los As New System.Web.UI.LosFormatter()
        Dim sw As New System.IO.StringWriter()
        los.Serialize(sw, state)
        Dim vs As String = sw.ToString()
        Session("ViewState") = Nothing
        Session("ViewState") = vs
    End Sub


Advantage of Moving ViewState object to Session Variable :

If the ViewState size is large, it increases the page size when it load in the browser and results in an increase in response time to load page performance.
Saving the
ViewState to a Session  can result in an improved response time as it reduce the ViewState object to Session but it use the server resource to store session information, so need to improve hardware information.

Sunday, February 26, 2012

ReOrder List in ASP.NET using AJAX


ReorderList is an ASP.NET AJAX control that implements a bulleted, data-bound list with items that can be reordered interactively. To reorder the items in the list, the user simply drags the item's control bar to its new location. Graphical feedback is shown where the item will be placed as it is dragged by the user. The data source is updated after the item is dropped in its new location.

When bound to data, the ReorderList control will behave like many other databound controls. If the data you are displaying has a field that determines sort order (e.g. the select query is sorted by this column), and that column is of an integer type, the ReorderList can automatically perform reorders if its SortOrderField property is set. The ReorderList can also bind to any data source that implements IList (such as Arrays).

The ReorderList control is different than the other samples here because it is an ASP.NET server control that is aware of ASP.NET AJAX behaviors. Rather than extending existing controls on the page, it delivers a rich client experience directly and still has a traditional post-back server model for interacting with the application.

The ReorderList can handle reorders in two ways, either via a callback or via a postback. For a callback, no page postback happens on a reorder. This is useful if the data is only to be ordered. If the data items are to be deleted or edited, a full postback needs to occur to sync the server side state with the client side state. The PostbackOnReorder property enables this.


Step 1: Create Stylesheet (CSS)




    <style type="text/css">
        .DragHandleClass
        {
            width: 20px;
            height: 20px;
            background-color: red;
            color: white;
            cursor: move;
        }
       
        .ajaxOrderedList li
        {
            list-style: none;
        }
    </style>



Step 2: Add Reorder List Control and SQL Data source

<asp:SqlDataSource ID="sds" runat="server" ConnectionString="<%$ ConnectionStrings:dbConnectionString %>"
        OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT [ID], [Product_Kid], [CatName], [Product_Name], [Product_Image], [Brand_Name], [Product_Description],  ISNULL(SortOrder,99999)  [SortOrder],Product_Code FROM [RecentProducts] ORDER BY [SortOrder]"
        UpdateCommand="UPDATE [RecentProducts] SET [SortOrder] = @SortOrder WHERE [ID] = @original_id"
        DeleteCommand="DELETE FROM [RecentProducts] WHERE [ID] = @original_id">
        <DeleteParameters>
            <asp:Parameter Name="original_id" Type="Int32" />
        </DeleteParameters>
        <UpdateParameters>
            <asp:Parameter Name="SortOrder" Type="Int32" />
            <asp:Parameter Name="original_id" Type="Int32" />
        </UpdateParameters>
    </asp:SqlDataSource>
    <br />
    <div class="ajaxOrderedList">
        <table style="font-weight: bold">
            <tr>
                <td style="width: 180px">
                    &nbsp;
                </td>
                <td style="width: 150px">
                    Product
                </td>
                <td style="width: 80px">
                    Brand
                </td>
                <td style="width: 80px">
                    Product Code
                </td>
                <td width="130px">
                    Description
                </td>
            </tr>
        </table>
        <cc1:reorderlist id="rl1" runat="server" allowreorder="True" sortorderfield="SortOrder"
            datakeyfield="ID" datasourceid="sds" postbackonreorder="True">

                                    <DragHandleTemplate>

                                        <div class="DragHandleClass">

                                        </div>

                                    </DragHandleTemplate>

                                    <ItemTemplate>

                                        <table style="vertical-align: top; width: ">

                                            <tr>

                                                <td style="width: 35px">

                                                    <asp:ImageButton ID="btnDelete" CommandName="Delete" ImageUrl="~/Images/del3.jpg"

                                                        OnClientClick="javascript:return confirm('Are you sure about deleting this record?');"

                                                        runat="server" />

                                                    </InsertItemTemplate>

                                                </td>

                                                <td>

                                                    <b>

                                                        <asp:Label ID="lblSrNo" runat="server" Text="" /></b>

                                                </td>

                                                 <td style="width: 65px">

                                                    <asp:Image ID="imgdynProd" Height="40" Width="60" runat="server" Style="border: 1px solid gray;

                                                        text-align: center;" AlternateText='<%# DataBinder.Eval(Container.DataItem, "Product_Image") %>'

                                                        ImageUrl='<%# "/Atcomaart/Upload Image/Product Image/UploadImages/"+ DataBinder.Eval(Container.DataItem, "Product_Image") %>'

                                                        onclick="Pop(this,30,'');" />

                                                </td>

                                                <td style="width: 150px">

                                                    <asp:Label ID="Label1" runat="server" Text='<%#Eval("Product_Name") %>' />

                                                </td>

                                                <td style="width: 80px">

                                                    <asp:Label ID="Label2" runat="server" Text='<%#Eval("Brand_Name") %>' />

                                                </td>

                                                <td style="width: 8px">

                                                    <b>&nbsp;<asp:Label ID="lblProduct_Code" runat="server" Text='<%#Eval("Product_Code") %>' /></b>

                                                </td>

                                                <td style="width: 150px">

                                                    &nbsp;<asp:Label ID="ItemLabel" runat="server"

                                                        Text='<%# Eval("Product_Description") %>' />

                                                </td>

                                             

                                            </tr>

                                        </table>

                                        <hr />

                                    </ItemTemplate>

                                    <InsertItemTemplate>

                                        <asp:Panel ID="pnlInsert" runat="server" DefaultButton="btnInsert">

                                            <span>Porduct Code: </span>

                                            <asp:TextBox ID="txtItemCode" runat="server"></asp:TextBox>

                                            <asp:RequiredFieldValidator ID="rfvItemCode" runat="server" ValidationGroup="1" ControlToValidate="txtItemCode"

                                                ErrorMessage="Product code is required."></asp:RequiredFieldValidator>

                                            <br />

                                            <asp:Button ID="btnInsert" Text="Submit" runat="server" CommandName="Select" ValidationGroup="1"

                                                OnClick="btnInsert_Click" />

                                        </asp:Panel>

                                    </InsertItemTemplate>

                                </cc1:reorderlist>
    </div>




Step 3:  Add Insert Command for Insert Method

 Protected Sub btnInsert_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        lblMessage.Text = ""
        Dim txtControl As New TextBox
        For i As Integer = 0 To rl1.Items.Count
            If (rl1.Items(i).FindControl("txtItemCode") IsNot Nothing) Then
                txtControl = DirectCast(rl1.Items(i).FindControl("txtItemCode"), TextBox)
                Exit For
            End If
        Next

        If (txtControl IsNot Nothing And txtControl.Text <> "") Then
            If (ProductCheck(txtControl.Text)) Then
                If (InsertRecentProductNew(txtControl.Text)) Then
                    txtControl.Text = ""
                    CreateMessageAlert(Me, "Product Added Sucessfully", "Success")
                    sds.DataBind()
                    rl1.DataBind()
                Else
                    CreateMessageAlert(Me, "Product Already Exists.", "Already")
                End If
            Else
                CreateMessageAlert(Me, "Invalid Product Code", "InValidProductCode")
            End If
        End If
    End Sub

 Public Sub CreateMessageAlert(ByRef aspxPage As System.Web.UI.Page, ByVal strMessage As String, ByVal strKey As String)
        Try

            If (Not aspxPage.IsStartupScriptRegistered(strKey)) Then
                ScriptManager.RegisterStartupScript(aspxPage, aspxPage.GetType, "StrKeyVal", "alert('" & strMessage & "')", True)
            End If

        Catch ex As Exception

        End Try
    End Sub 


Friday, September 9, 2011

How to Convert Html to PDF in ASP.NET , C# Using iTextsharp

There are many solutions can convert html to PDF.

However they have different effects. As far as I know, the simplest solution that I ever seen is using iTextsharp and the code as below:

 Sample Code:

         string FilePath = Server.MapPath("") + "/OrderconfirmationMail.htm";
         System.IO.StreamReader myFile =new System.IO.StreamReader(FilePath);
         string myString = myFile.ReadToEnd();
         myFile.Close();
         string ImagePath = Server.MapPath("") + "\\Images\\";
        myString = myString.Replace("src=\"Images/", ImagePath);
         StringReader sr = new StringReader(myString);
         iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 2f, 2f, 2f, 2f);
         HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
         string filename = Server.MapPath("") + "\\WordDoc\\parsetest3.pdf";
       

         if (File.Exists(filename))
         {
             File.Delete(filename);
         }
         PdfWriter.GetInstance(pdfDoc, new FileStream(filename, FileMode.Create));
         pdfDoc.Open();
         htmlparser.Parse(sr);
         pdfDoc.Close();
         Response.Write(pdfDoc);


I found some links where you can find details:

  • http://stackoverflow.com/questions/2822843/itextsharp-html-to-pdf
  • http://hamang.net/2008/08/14/html-to-pdf-in-net/
  • http://forums.asp.net/t/1596224.aspx/1
  • http://aspdotnetcodebook.blogspot.com/2008/07/how-to-export-content-of-gridview-to.html
  • http://channel9.msdn.com/Forums/TechOff/117199-ASPNET-and-iTextSharp-free-PDF-Generator-for-NET

Wednesday, September 2, 2009

Set Session variable in javascript function


How can I set session variables with JavaScript ?

Sample Code In Java script:
<script language="javascript" type="text/javascript">
          function SendRequest() {
          var MySessionvalue = '<%= Session["EMP_C"] %>';
          var MyColocn = '<%= Session["COLOCN_C"] %>';
          alert(MySessionvalue);           
          }
< /script>

#How can I set session variables with JavaScript
#Assigning Session variable from Javascript
#How do i set a session variable using javascript?

Tuesday, August 11, 2009

OPENING NEW WINDOWS

var newwindow;
function openwindow(url)
{
newwindow=window.open(url,'name','height=800,width=600');
if (window.focus) {newwindow.focus()}
}

ShareThis

Welcome

Welcome to Rajesh Prajapati, asp.net blog.
Here you can find some useful code and information about asp.net., c#, VB.net, SQL Server, Web Service, Web Designing etc