Thursday, 27 February 2014

Crystal Reports Customization

Introduction

What Is Crystal Reports?

"In simplest terms, Crystal Reports is a report design tool that allows you to create reports capable of retrieving and formatting a result set from a database or other data source. In addition to simply reading data from a data source, Crystal Reports has its own formula language for creating calculations and includes a number of features that can be used to turn raw data into presentation-quality reports, with graphs, charts, running totals, and so on." (David McAmis, Professional Crystal Reports for Visual Studio .NET, 2nd edition)
We give this option to users to download there on copy of result what they want from search result.

Sqlserver Part

Create a Simple Table Name as PersonInfo:
create Table PersonInfo
(
PersonID int primary key IDENTITY(1,1) NOT NULL,
PersonName Nvarchar(100) NULL,
PersonAge int NULL,
PersonAddress Nvarchar(100) NULL,
PersonProfession nvarchar(100) NULL
)



Inserting Records  

Insert Records into Table from backend

 
Selecting Records for displaying on report Using StoredProcedure
CREATE Proc Usp_getPersonRecords
as
SELECT * FROM PersonInfo   
Create a new ASP.NET Web Application Project.






Add New Web form -> Name it as ExportRecords.aspx.



Adding Crystal Report





When this Screen appears in front of you, just select (Standard) and Press Ok button.



The Standard Report Creation Wizard will pop



Select Create New Connection.
  1. Inside That OLE DB
  2. A new Wizard will pop up OLE DB (ADO)



  3. It will ask for Provider
  4. Select (Microsoft OLE DB Provider for SQL Server)
  5. Click Next Button


Connection Information Wizard will appear.
Just enter your SQL Server details here.


Then click on Next button


After click on Finish this wizard will appear.


  1. First select your Database where you have created table.
  2. Inside that you will find 3 options  
    1. dbo  
    2. INFORMATION_SCHEMA
    3. Sys  
  3. Select dbo (Here you will see 2 options)
    1. Tables
    2. Stored procedures
  4. Select Store procedures from it.
(Because we will bind Store procedures to report to display information)

 
The Store procedures Usp_getPersonRecords will appear in the list of data sources, add the Store procedures to selected table list by clicking on the right arrow.
Click Next button
This wizard will appear.


Select all columns and then clicking on the right arrow to move in Fields to Display


Click on Next Button


We will not perform Grouping Just click Next Button
This wizard will appear.


We will not perform Record Filter Just click Next Button
This wizard will appear.


Select Standard from it and click Finish.
After Finishing the crystal report will appear to you.

 
Just Save it.
Let’s Move from sql to Web forms now. (ExportRecords.aspx)

On Page Add Crystal Report viewer and three images buttons

(I have add images to buttons)
<form id="form1" runat="server">
<div style="margin: 0px; overflow: auto;">
<table width="100%">
<tr>
<td align="center">

<asp:ImageButton ID="Img1" Height="50px" ImageUrl="~/Images/PdfImage.jpg"
runat="server" onclick="Img1_Click" />

<asp:ImageButton ID="img2" Height="50px" ImageUrl="~/Images/index.jpg"
runat="server" onclick="img2_Click" />

<asp:ImageButton ID="img3" Height="50px" ImageUrl="~/Images/docx.png"
runat="server" onclick="img3_Click" />

<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="true" />

</td>
</tr>
</table>
</div>
</form>
Like this View you will see


On load for Binding crystal Report i have created Method GenerateReport().
You need to add Connection string above Page load.
SqlConnection con = new SqlConnection<br />(ConfigurationManager.ConnectionStrings["Myconstr"].ToString());
And add Connection string In Web.config.
For doing connection with database you need to add connection string to database Here is example of it.
Just replace here with your database value.
Data source
Database
User id
Password
<connectionStrings>
   <add name="Myconstr" connectionString="data source=SAI-PC; Database=MotorTraining;  user id=sa; password=Pass$123 ;" providerName="system.data.sqlclient"/>
</connectionStrings>
Here I have bind crystal report on page load event.
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GenerateReport();
            }
        }
This is method which I am using for binding crystal report on page load.
protected void GenerateReport()
        {
            SqlCommand cmd = new SqlCommand("Usp_getPersonRecords", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataTable datatable = new DataTable();
            da.Fill(datatable); // getting value according to imageID and fill dataset

            ReportDocument crystalReport = new ReportDocument(); // creating object of crystal report
            crystalReport.Load(Server.MapPath("~/CrystalPersonInfo.rpt")); // path of report 
            crystalReport.SetDataSource(datatable); // binding datatable
            CrystalReportViewer1.ReportSource = crystalReport;
        }

How It Works

On button click we are going to Export crystal report in pdf, Excel, html, format.
We are bringing all data from sql server into dataset and binding dataset to crystal report data source.
Creating object of report document
ReportDocument crystalReport = new ReportDocument();
After creating object we are going to load crystal report by giving its path.
crystalReport.Load(Server.MapPath("~/CrystalPersonInfo.rpt"));
Here we are assigning format to export.
crystalReport.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, 
    Response, true, "PersonDetails");

First Button (Img1 for exporting records in PDF format)

On button click we are going to Export crystal report in PDF format.
protected void Img1_Click(object sender, ImageClickEventArgs e)
        {
            SqlCommand cmd = new SqlCommand("Usp_getPersonRecords", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataTable datatable = new DataTable();
            da.Fill(datatable); // getting value according to imageID and fill dataset

            ReportDocument crystalReport = new ReportDocument(); // creating object of crystal report
            crystalReport.Load(Server.MapPath("~/CrystalPersonInfo.rpt")); // path of report 
            crystalReport.SetDataSource(datatable); // binding datatable
            CrystalReportViewer1.ReportSource = crystalReport;

            crystalReport.ExportToHttpResponse
            (CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Response, true, "PersonDetails");
            //here i have use [ CrystalDecisions.Shared.ExportFormatType.PortableDocFormat ] to Export in PDF

        }

First Second (Img2 for exporting records in Excel format)

On button click we are going to Export crystal report in Excel format.
protected void img2_Click(object sender, ImageClickEventArgs e)
        {
            SqlCommand cmd = new SqlCommand("Usp_getPersonRecords", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataTable datatable = new DataTable();
            da.Fill(datatable); // getting value according to imageID and fill dataset

            ReportDocument crystalReport = new ReportDocument(); // creating object of crystal report
            crystalReport.Load(Server.MapPath("~/CrystalPersonInfo.rpt")); // path of report 
            crystalReport.SetDataSource(datatable); // binding datatable
            CrystalReportViewer1.ReportSource = crystalReport;

            crystalReport.ExportToHttpResponse
            (CrystalDecisions.Shared.ExportFormatType.ExcelRecord, Response, true, "PersonDetails");
            //here i have use [ CrystalDecisions.Shared.ExportFormatType.ExcelRecord ] to Export in Excel
        }

First Third (Img3 for exporting records in Word format)

On button click we are going to Export crystal report in Word format
protected void img3_Click(object sender, ImageClickEventArgs e)
        {
            SqlCommand cmd = new SqlCommand("Usp_getPersonRecords", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataTable datatable = new DataTable();
            da.Fill(datatable); // getting value according to imageID and fill dataset

            ReportDocument crystalReport = new ReportDocument(); // creating object of crystal report
            crystalReport.Load(Server.MapPath("~/CrystalPersonInfo.rpt")); // path of report 
            crystalReport.SetDataSource(datatable); // binding datatable
            CrystalReportViewer1.ReportSource = crystalReport;

            crystalReport.ExportToHttpResponse
            (CrystalDecisions.Shared.ExportFormatType.WordForWindows, Response, true, "PersonDetails");
            //here i have use [ CrystalDecisions.Shared.ExportFormatType.WordForWindows ] to Export in Word
        }
Now save and run project.
All records will appear on Crystal report.
With five buttons to Export.


On clicking of PDF button.


On clicking Excel button.



On clicking of Word button.




On clicking of HTML button.


On clicking of RTF button


Making Easy to Understand

Wednesday, 26 February 2014

Data table function Crystal Report

***************crystal report by date**************
data table

*********************
  public DataTable retrivedata(string val)
        {
           
            SqlConnection con = new SqlConnection(path);
          
            SqlCommand cmd = new SqlCommand();
            DataSet ds = null;
            SqlDataAdapter adapter;
            try
            {
                con.Open();
                //Stored procedure calling. It is already in sample db.
                cmd.CommandText = "sp_slectDatabyDate";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@ActivationDate", val);
                cmd.Connection = con;
                ds = new DataSet();
                adapter = new SqlDataAdapter(cmd);
                adapter.Fill(ds, "Sheet1");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                cmd.Dispose();
                if (con.State != ConnectionState.Closed)
                    con.Close();
            }
            return ds.Tables[0];

        }

**************form button behind coe*************
 CrystalReport2 crp = new CrystalReport2();
            crp.SetDataSource(new MyProc().retrivedata(val));
            CrystalReportViewer1.ReportSource = crp;

Tuesday, 25 February 2014

ajax multipal file uploads using ajax control tool kit

************************Ajax file Upload Web.config****************

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
    <system.web>

    <httpHandlers>
      <add verb="*" path="AjaxFileUploadHandler.axd" type="AjaxControlToolkit.AjaxFileUploadHandler, AjaxControlToolkit"/>
    </httpHandlers>
        <compilation debug="true" targetFramework="4.0">
            <assemblies>
                <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
                <add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
                <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /></assemblies></compilation>
    <pages>
      <controls>
        <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
      </controls>
    </pages></system.web>
</configuration>
***************************form Design*********************
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ajaxfileupload.WebForm1" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ToolkitScriptManager ID="srp" runat="server"></asp:ToolkitScriptManager>
    <div>
     <asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server" OnUploadComplete="File_Upload" AllowedFileTypes="jpg,jpeg,png" MaximumNumberOfFiles="3"/>
     </div>
    </form>
   
  
</body>
</html>
****************form Code**************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;

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

        }
        protected void File_Upload(object sender, AjaxFileUploadEventArgs e)
        {

            string filePath = "~/Images/" + e.FileName;
           // filePath = filePath.Split('\\').Last();

            AjaxFileUpload1.SaveAs(MapPath(filePath));

        }
    }
}

Monday, 10 February 2014

Wednesday, 5 February 2014

Implementing the Membership and Role Provider

Introduction

ASP.NET 2.0 provides built in controls to manage Membership in Web Applications. All these controls use ASP.NET providers that are loaded via web.config file. Membership provider and Role provider allow a complete system to maintain users information, authenticate and authorize the users. This article demonstrates how to use and configure the default Member ship and Role provider.

Implementing the Membership and Role Provider

Initially by using the Visual Studio 2005/2008/2010, create an ASP.NET website/web application. If you are using Visual Studio 2010, login and registration pages are available by default in the application. Create Registration page and then drag the Create User Wizard control from the Login controls section of the Toolbox. Now to store the user information, we need to create the database in the SQL Server. Follow the steps given below to use built in user store schema for maintaining the user information.
  1. Go to Visual Studio, Visual Studio tools and then open the Visual Studio Command Prompt.
  2. Use the aspnet_regsql.exe command to run the ASP.NET SQL Server Setup Wizard.
  3. Check the option “Configure SQL Server for application services”.
  4. Select the Server Instance and the database name for the application, if the database name is not provided, default aspnetdb database is created.
  5. Click the confirm settings and finish button to create the database store.
Step 1:
Step 2:
Step 3:
Step 4:
Step 5:
Preparing to build the security system for use in application, we need to configure the membership provider in web.config file. The following settings for Forms Authentication, Membership and Role provider are applied in the web.config file.

Forms Authentication Settings

The authentication mode under system.web tag is set to “Forms” and the elements included in are loginUrl, defaultUrl, timeout, cookieless and protection which specifies the login page URL, default page URL, cookie expiration time and protection level respectively. The settings in web.config file would look similar to the code shown below:
<authentication mode="Forms">
     <forms cookieless="UseCookies" defaultUrl="HomePage.aspx" 
 loginUrl="UnAuthorized.aspx" protection="All" timeout="30">
          </forms>
</authentication>    

Membership Provider Settings

Some of the important elements to be considered in the Membership provider are name – name of the provider, type – namespace of the provider, connectionStringName – name of the connectionstring and the most important password format. The password format is available in three formats, Hashed, Encrypted and Clear. Hashed format provides one way of storing password in encrypted format which cannot be brought back to original state, whereas Encrypted format provides both to encrypt and decrypt the password.
<membership defaultProvider="Demo_MemberShipProvider">
 <providers>
  <add name="Demo_MemberShipProvider"
      type="System.Web.Security.SqlMembershipProvider"
      connectionStringName="cnn"
      enablePasswordRetrieval="false"
      enablePasswordReset="true"
      requiresQuestionAndAnswer="true"
      applicationName="/"
      requiresUniqueEmail="false"
      passwordFormat="Hashed"
      maxInvalidPasswordAttempts="5"
      minRequiredPasswordLength="5"
      minRequiredNonalphanumericCharacters="0"
      passwordAttemptWindow="10" passwordStrengthRegularExpression="">
 </providers>
</membership>

Role Provider Settings

The similar way is to specify the settings for default Provider under system.web tag of the web.config file as shown below. The settings are simple and self explanatory.
<roleManager enabled="true" cacheRolesInCookie="true" 
 cookieName="TBHROLES" defaultProvider="Demo_RoleProvider">
              <providers>
                  <add connectionStringName="dld_connectionstring"
                  applicationName="/" name="Demo_RoleProvider"
                  type="System.Web.Security.SqlRoleProvider, System.Web,
                  Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
             </providers>
</roleManager>
In the login.aspx and Registration.aspx pages, we need to use the providers to complete the membership system for the application.

Registering the Users

Registration page for the users can be easily created by using the available create user wizard and the following event handlers:
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
     MembershipCreateStatus p = MembershipCreateStatus.Success;
     Membership.CreateUser(CreateUserWizard1.UserName,  
  CreateUserWizard1.Password, CreateUserWizard1.Email,
     CreateUserWizard1.Question, CreateUserWizard1.Answer, true, out p);
}

protected void CreateUserWizard1_ContinueButtonClick(object sender, EventArgs e)
{
  Response.Redirect("login.aspx");
} 

Authenticate the Users

The users can be authenticated by using the login_Authenticate event of the Login control. The code to authenticate users goes here:
protected void Login1_Authenticate(object sender,AuthenticateEventArgs e)
{
 if (Membership.ValidateUser(Login1.UserName, Login1.Password) == true)
    {
        Login1.Visible = true;
        Session["user"] = User.Identity.Name;
        FormsAuthentication.RedirectFromLoginPage(Login1.UserName, true);
    }
 else
    {
        Response.Write("Invalid Login");
    }
}

Creating the Admin Panel

In the Admin Panel, the features to Add, Edit, Delete and Assign Roles to users are provided to the administrator.

Creating the Roles

The following code snippet shows you how to create Roles:
Public void createRoles()
{
    try
    {
        if (!Roles.RoleExists(txtrolename.Text))
        {
            Roles.CreateRole(txtrolename.Text);
            BindUsers();
            BindRoles();
            Label1.Text = "Role(s) Created Successfully";
        }
        else
        {
            Label1.Text = "Role(s) Already Exists";
        }
    }
    catch (Exception ex)
    {
        Label1.Text = ex.Message;
    }
}
BindRoles
The BindRoles method is used to bind the available roles in the store to the user control.
public void BindRoles()
{
    SqlDataAdapter da = new SqlDataAdapter("select RoleName from aspnet_Roles", cnn);
    DataSet ds = new DataSet();
    da.Fill(ds, "Roles");
    lstRoles.DataSource = ds;
    lstRoles.DataTextField = "RoleName";
    lstRoles.DataValueField = "RoleName";
    lstRoles.DataBind();
}
BindUsers
The BindUsers method is used to bind the available users in the store to the user control.
public void BindUsers()
{
    SqlDataAdapter da = new SqlDataAdapter("select UserName from aspnet_users", cnn);
    DataSet ds = new DataSet();
    da.Fill(ds, "Roles");
    lstusers.DataSource = ds;
    lstusers.DataTextField = "UserName";
    lstRoles.DataValueField = "RoleName";
    lstusers.DataBind();
}
The following methods take username and rolename as parameters.

Assign Roles To User

The available roles can be assigned to the user in the following way:
private void AssignRoles()
    {
        try
        {
            if (!Roles.IsUserInRole(lstRoles.SelectedItem.Text))
            {
                Roles.AddUserToRole(lstusers.SelectedItem.Text, 
    lstRoles.SelectedItem.Text);
                BindUsers();
                BindRoles();
                Label1.Text = "User Assigned To User Successfully";
            }
            else
            {
                Label1.Text = "Role(s) Already Assigned To User";
            }
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }
    }

Remove Roles from the User

You can remove the user from a role in the following manner:
private void RemoveuserFromRole()
{
    try
    {
        Roles.RemoveUserFromRole(lstusers.SelectedItem.Text, lstRoles.SelectedItem.Text);
        BindUsers();
        BindRoles();
        Label1.Text = "User Is Removed From The Role Successfully";
    }
    catch (Exception ex)
    {
        Label1.Text = ex.Message;
    }
}

Delete Roles

The code is used to delete the existing Roles, if they are not in use.
public void RemoveRole()
{
 try
        {
            Roles.DeleteRole(lstRoles.SelectedItem.Text);
            BindUsers();
            BindRoles();
            Label1.Text = "Role(s) Removed Successfully";
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }
}
Restrict the users depending on the roles by using web.config settings as follows:
<authorization
        <allow roles ="Admin"/>
        <deny users ="*"/>
</authorization>        
In the above code, if you write deny users =”*” and then allow roles =”Admin”, there seems to be no difference, but the code wouldn’t work for you because writing the deny user =”*” at the beginning would even restrict the admin to access the folders.
Show/Hide The Menu Items to The Users Depending on Roles
if (Roles.IsUserInRole("Admin"))
{
    Menu1.Items[0].Text = "Admin";
}
else
{
    Menu1.Items[0].Text = "";
}