DotNet Friends

September 16, 2009

Crystal report with multiple sub report navigation problem in asp.net

Here I am explain the crystal report problem during the development.

I want to create Main report which having three sub reports. I create that report and call that report using asp.net but I have phase navigation problem.

Problem :

When Clicking the “Next” navigation button while on page 1 of Report Page 2 is appear, when clicking the “Next” navigation button while on page 2 , page 2 is repeated.

Solution :

Initially we write a Crystal report viewer code in to Page_Load event we move that code to Page_Init event and the Report navigation work.

Hope this help you.

thnx

August 28, 2009

PDF Viewer in asp.net

Filed under: Asp.Net 2.0, C#.net, dotnet — Tags: , — patriwala @ 1:49 pm

Here I am explaining how to create PDF Viewer in asp.net.

iPaper in asp.net

Steps:

1) create Class Library Project Here I am give name OnlinePdfViewer. Here I am using c#.net. Write below code in to file.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OnlinePdfViewer
{
    public class DisplayPdf : WebControl
    {
        private string _filepath;
        public string FilePath
        {
            get
            {
                return _filepath;
            }
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    _filepath = string.Empty;
                }
                else
                {
                    int tild = -1;
                    //check ~ symbol including in pdf path then remove
                    tild = value.IndexOf('~');
                    if (tild != -1)
                    {
                        _filepath = value.Substring((tild + 2)).Trim();
                    }
                    else
                    {
                        _filepath = value;
                    }
                }
            }
        }   

        protected override void RenderContents(HtmlTextWriter writer)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<iframe src=" + Convert.ToString(FilePath) + " ");
                //fix height and width
                sb.Append("width=800px height=500px");
                sb.Append("<View PDF: <a href=" + Convert.ToString(FilePath) + "</a></p> ");
                sb.Append("</iframe>");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                writer.Write(Convert.ToString(sb));
                writer.RenderEndTag();
            }
            catch
            {
                //If any problem in the PDF at that time display below information
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                writer.Write("PDF Control...");
                writer.RenderEndTag();
            }
        }
    }
}      

2) Run the project it generate dll –> OnlinePdfViewer.dll.

3) Create New Web Application give name – DemoPDFViewer.I have create application in asp.net with c#.

    Here I have create demo application In application User can upload PDF and View uploaded PDF in PDF viewer.

3.1) Add the Reference of OnlinePdfViewer.dll into Site.

3.2) Make PDF folder into Site.

3.3) Upload PDF Functionality

ASPX Code :

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

<%@ Register Assembly="OnlinePdfViewer" Namespace="OnlinePdfViewer" TagPrefix="PdfViewer" %>
<!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>PDF View Online</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <center>
            <table>
                <tr>
                    <td colspan="2" align="center" style="font-family: Verdana; font-size: larger">
                        Online PDF Viewer
                    </td>
                </tr>
                <tr>
                    <td>
                        Upload PDF File
                    </td>
                    <td>
                        <asp:FileUpload ID="fup" runat="server" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="lblMsg" runat="server" ViewStateMode="Disabled" Font-Bold="true" ForeColor="Red"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <asp:Button ID="btnView" Text="View PDF" runat="server" Visible="false" OnClick="btnView_Click" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2" id="pnlPDFViewer" visible="false" runat="server">
                        <asp:HyperLink ID="HyperLink1" runat="server">Open PDF into New Page</asp:HyperLink>
                        <br />
                        <PdfViewer:DisplayPdf ID="displaypdf1" runat="server" BorderStyle="Inset" BorderWidth="2px"
                            Style="height: 500px;" Width="800px" />
                    </td>
                </tr>
            </table>
        </center>
    </div>
    </form>
</body>
</html>

CS Code:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;

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

    }

    public string Uploadedfilename { get { return Convert.ToString(ViewState["filename"]); } set { ViewState["filename"] = value; } }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (fup.HasFile)
        {
            string strFilePath = Server.MapPath("PDF") + "\\";
            Uploadedfilename = Convert.ToString(Guid.NewGuid()) + ".pdf";
            strFilePath = strFilePath + Uploadedfilename;
            fup.SaveAs(strFilePath);
            lblMsg.ForeColor = Color.Blue;
            lblMsg.Text = "PDF File Upload Successfully";
            btnView.Visible = true;
        }
        else
        {
            lblMsg.Text = "Please Upload PDF File";
        }
    }
    protected void btnView_Click(object sender, EventArgs e)
    {
        pnlPDFViewer.Visible = true;
        displaypdf1.FilePath = @"~/pdf/" + Uploadedfilename;
        HyperLink1.NavigateUrl = @"~/pdf/" + Uploadedfilename;
    }
}

4) compile code and run application.

 

thnx

December 3, 2008

Convert Generic List In To DataTable

Create simple asp.net application with C#. Add new class (GenericToDataTable).

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

public class GenericToDataTable
{
/// <summary>
/// Default Constructor
/// </summary>
private GenericToDataTable()
{ }
/// <summary>
///
/// </summary>
/// <typeparam name=”T”>Custome Class </typeparam>
/// <param name=”lst”>List Of The Custome Class</param>
/// <returns> Return the class datatbl </returns>
public static DataTable ConvertTo<T>(IList<T> lst)
{
//create DataTable Structure
DataTable tbl = CreateTable<T>();
Type entType = typeof(T);

PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
//get the list item and add into the list
foreach (T item in lst)
{
DataRow row = tbl.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
tbl.Rows.Add(row);
}

return tbl;
}

/// <summary>
///
/// </summary>
/// <typeparam name=”T”>Custome Class</typeparam>
/// <returns></returns>
public static DataTable CreateTable<T>()
{
//T –> ClassName
Type entType = typeof(T);
//set the datatable name as class name
DataTable tbl = new DataTable(entType.Name);
//get the property list
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
foreach (PropertyDescriptor prop in properties)
{
//add property as column
tbl.Columns.Add(prop.Name, prop.PropertyType);
}
return tbl;
}
}

after add above class compile the code.

after compilation add new class into project (Class Name: clsUser).

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for clsUser
/// </summary>
public class clsUser
{
//create property userid
private int _UserId;
public int UserID
{
get { return _UserId; }
set { _UserId = value; }
}
//create property username
private string _UserName;
public string UserName
{
get { return _UserName; }
set { _UserName = value; }
}
/// <summary>
/// Default Constructor
/// </summary>
public clsUser()
{ }

public clsUser(int userid,string username)
{
this.UserID = userid;
this.UserName = username;
}
}

After adding this class into project go to Default.aspx page in this page type below code on Page Load event.

//create generic list of class clsUser
System.Collections.Generic.List<clsUser> obj = new
System.Collections.Generic.List<clsUser>();
//add data into list
for (int i = 0; i < 10; i++)
{
obj.Add(new clsUser(i,”a”+i.ToString()));
}
//convert list to datatable
DataTable dt= GenericToDataTable.ConvertTo<clsUser>(obj);

now check the DataTable(dt).

thnx

September 6, 2008

Embedding Resources in ASP.Net 2.0

Filed under: Asp.Net 2.0, C#.net, dotnet — Tags: — patriwala @ 5:40 am
  • embed resources

let’s start with the very basic if i tell you create the customize control (inherit the Textbox and create new Textbox MyTextBox) .

in other word you  can create customize textbox with three condition

1) Upper Case : when user selected Upper Case all enter input converted into Upper Character.

2) Lower Case : when user selected Lower Case all enter input converted into Lower Character.

3) None :  nothing to do.

now what can you do?

i am explain from my level.

1. i writen java script in the customize class.

2. i create java script and put that java script into my webapplication. i only written related function name in customize class.

above method is good but i face some problem which i explaining

1) in class i have written javascript which code is very long and unmanged from my site and the main thing is when small change occure i find into that much of code and replace and build that application.

2) in external javascript you added that javascript into the web application (this method is really good but some time if we not added that javascript then we are in trouble).

in both of the case java script is readable i have to find that thing one java script easy to manage and second thing not readable.

now i m check that thing in to the embed resource application.

  • Benifit Of embed resources :

1) manage all your dependencies into one single assembly like you identify the some stuff which are need in the application every time (like your company logo image,your company profile information).

2) especially javascript is not readable.

Steps :

1) create ClassLibrary Project In Visual Studio (Open –> File –> Project –> Class Library in C# Tag). give project Name : MyResource

2) Add Reference (go to Solution Explore –> Right Click On Reference –> select Add Reference).

2.1) select System.Web

3) change the Class Name MyTextBox

4) Inherite the TextBox Class in MyTextBox Class.

   1: public class MyTextBox : System.Web.UI.WebControls.TextBox

5) create Textbox which has different mode like when user select

1) upper then what ever they typed convered into upper

2) Lower then what ever they typed converted into lower

3) None nothing

now the main thing if you want to implement this then you want a create Java Script for this.

now add Java Script in to project.give a name MyJs.Js.

6) now Right Click On Added JavaScript and Select Property. change the Build Action –> Embedded Resource.

7) Add the Below Code in to MyTextBox Class.

   1: //enum for selection
   2:         public enum TextType
   3:         {
   4:             UpperCase,
   5:             LowerCase,
   6:             None
   7:         }
   8:
   9:         //property TextStyle
  10:         private TextType _TextStyle;
  11:         public TextType TextStyle
  12:         {
  13:             get { return _TextStyle; }
  14:             set { _TextStyle = value; }
  15:         }
  16:
  17:         public MyTextBox()
  18:         {
  19:
  20:         }
  21:
  22:         /// <summary>
  23:         /// 
  24:         /// </summary>
  25:         /// <param name="writer"></param>
  26:         protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
  27:         {
  28:             //add the attribute to in
  29:             if (this.TextStyle == TextType.LowerCase)
  30:             {
  31:                 writer.AddAttribute("onkeyup", "lower(this.id);");
  32:             }
  33:             else if (this.TextStyle == TextType.UpperCase)
  34:             {
  35:                 writer.AddAttribute("onkeyup", "upper(this.id);");
  36:             }
  37:             base.AddAttributesToRender(writer);
  38:         }
  39:
  40:         protected override void OnPreRender(EventArgs e)
  41:         {
  42:             //Register Java Script
  43:             Page.ClientScript.RegisterClientScriptInclude("MyTextBox", Page.ClientScript.GetWebResourceUrl(this.GetType(), "MyResource.MyJS.js"));
  44:             base.OnPreRender(e);
  45:         }

8 ) now in the AssemblyInfo File Add the WebResource.

   1: //Add Name Space using System.Web.UI;
   2: //your NameSpace 
   3: [assembly: WebResource("MyResource.MyJS.js", "text/javascript", PerformSubstitution = true)]

9) Now Build Project then Create WebApplication (asp.net using C#) or Add New web Site In Existing Project. here i added new web site in Existing project.

10) Add MyTextBox Dll Reference in to Newly Created WebSite.

11) Add MyTextBox In to WebPage. Set the property

12) Run Web Site And Check.

how to retriving resource (ImageFile,html file) from the embeding resource ?

steps :

1) Add Image In to your exiting Class Library Project (Image Name :MyImage.Jpg).

2) now Right Click On Added JavaScript and Select Property. change the Build Action –> Embedded Resource.

3) now in the AssemblyInfo File Add the WebResource.

   1: [assembly: WebResource("MyResource.MyImage.jpg", "img/jpg")]

4) Build the Project. and go to the WebSite Project.

5) in the web site project put the image control.

6) now in the page load event get the myimage from the dll file.

   1: //the first argument type --> give the your class name
   2:       //second is resource name
   3:       Image1.ImageUrl =
   4:            Page.ClientScript.GetWebResourceUrl(typeof(MyResource.MyTextBox), "MyResource.MyImage.jpg");

7) check code.

Now the interesting thing check the page source.

Thnx

Blog at WordPress.com.