Friday 26 June 2015

SSRS Report in ASP.NET Example

Following steps are given to create a SSRS(RDLC) Report in ASP.NET



1)      Create table "UserList" in Database

2)      Create Connection String in Web.Config
<connectionStrings>
    <add name="constr" connectionString="<Databaseconnection>" ProviderName="System.Data.SqlClient"/>
</connectionStrings>

3)      Add httphandler to web.config.
<system.web>
    <httpHandlers>
      <add path="Reserved.ReportViewerWebControl.axd" verb="*"
      type="Microsoft.Reporting.WebForms.HttpHandler,
      Microsoft.ReportViewer.WebForms, Version=10.0.0.0,
      Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" validate="false"
      />
    </httpHandlers>
</system.web>
<system.webServer>
    <handlers>
      <add name="ReportViewerWebControlHandler"
      preCondition="integratedMode"
      verb="*" path="Reserved.ReportViewerWebControl.axd"
      type="Microsoft.Reporting.WebForms.HttpHandler,
      Microsoft.ReportViewer.WebForms, Version=10.0.0.0,
      Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
      />
    </handlers>
  </system.webServer>

4)      Create empty ASP.NET Application.
5)      Crate Report Folder, Named it “Reports”
6)      Add SSRS Report(.rdlc) in report folder, Named it “MyReport”.
7)      Add Dataset (.xsd) in report folder, Named it “MyReportUser”.
8)      Design Dataset (add Datatable and add column in datatable as same in SQL Table.

9)      Open Myreport.rdlc file and add DataSet “MyReportUser” in Report Data Section.

10)   Design report as per your requirement.

11)   Add script manager and report viewer to aspx page as shown below:
<form id="form1" runat="server">
    <asp:ScriptManager runat="server">
    </asp:ScriptManager>
    <div>
    <rsweb:ReportViewer Width="100%" ShowToolBar="false" ID="rptvMyReport" runat="server">
    </rsweb:ReportViewer>
    </div>
    </form>
12) Add following namespaces

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Reporting.WebForms;
using SSRSReportExample.Reports; //To Access Reports folder Dataset

13) Add to Code Behind

string str = ConfigurationManager.ConnectionStrings["constr"].ToString();
        DataSet ds;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                getUserList();//Call report at page load
            }
        }

        private void getUserList()
        {
            SqlConnection con = new SqlConnection();//Create SQL Connection Object
            MyReportUser dsUserList = new MyReportUser();//Create DataSet Object
            try
            {
                con.ConnectionString = str;
                SqlDataAdapter sda = new SqlDataAdapter("select * from UserList", con);
                con.Open();
               
                sda.Fill(dsUserList, "UserList");//bind data to DataSet
                if (dsUserList.Tables[0].Rows.Count > 0)//if bind is successfull then execute
                {
                    rptvMyReport.ProcessingMode = ProcessingMode.Local;
                    rptvMyReport.LocalReport.ReportPath = Server.MapPath("~/Reports/MyReport.rdlc");
                    rptvMyReport.LocalReport.DataSources.Clear();//Clear previous applied Datasource
                    ReportDataSource rptDataSource = new ReportDataSource("UserList", dsUserList.Tables[0]);//Create Report Datasource and add Dataset in it.
                    rptvMyReport.LocalReport.DataSources.Add(rptDataSource);
                }
            }
            catch { }
            finally { con.Close(); }
        }
14) Build your application and check the result.


Wednesday 17 June 2015

Prevent Button Double Click ASP.NET Code Behind

Disable ASP.NET Button after click to prevent the double click and change button text to Loading/Please Wait.

Design :

<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />


Code Behind :

//Here javascript added to the button at page load.

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string strProcessScript = "this.value='Processing...';this.disabled=true;";
            Button1.Attributes.Add("onclick", strProcessScript + ClientScript.GetPostBackEventReference(Button1, "").ToString());
        }
        catch { }
    }

//After Button click method wait for 5 Second to check the result.
protected void Button1_Click(object sender, EventArgs e)
    {
       
                Thread.Sleep(5000);
   
    }


Then check you result.

If you have any issue then let me know.

Wednesday 10 June 2015

Convert String to DateTime in ASP.NET using CultureInfo

In textbox we have different different  date formats for eg. 'dd-MMM-yy','yyyy-MM-dd' etc.
this format sometime throw errors like 
string was not recognized as a valid datetime.

And for this type of error we are using following code which can convert all the date format into given Culture.


GetCultureInfo():Retrieves a cached, read-only instance of a culture using the specified culture name


Convert.ToDateTime(TextBoxID.Text,System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);

Thursday 4 June 2015

Show Bootstrap Modal popup using ASP.NET

Design:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="BootstrapModal.aspx.cs" Inherits="BootstrapModal_ASPNET.BootstrapModal" %>

<!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>Bootstrap Example</title>
    <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="container">
          <h2>Modal Example</h2>
          <!-- Trigger the modal with a button -->
          <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
          <!--ASP.NET Button -->
            <asp:Button ID="btnOpenModal" runat="server" CssClass="btn btn-info btn-lg" Text="Open with ASP Button" onclick="btnOpenModal_Click" />
      
          <!-- Modal -->
          <div class="modal fade" id="myModal" role="dialog">
            <div class="modal-dialog">
   
              <!-- Modal content-->
              <div class="modal-content">
                <div class="modal-header">
                  <button type="button" class="close" data-dismiss="modal">&times;</button>
                  <h4 class="modal-title">Modal Header</h4>
                </div>
                <div class="modal-body">
                  <p>Some text in the modal.</p>
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                  <asp:Button ID="btnCloseModal" CssClass="btn btn-default"  runat="server" Text="Close & Reopen"
                    onclick="btnCloseModal_Click" />
                </div>
              </div>
     
            </div>
          </div>
 
        </div>
    </form>
</body>
</html>



Code Behind:

protected void btnOpenModal_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myModal", "$('#myModal').modal();", true);
        }

        protected void btnCloseModal_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myModalHide", "$('#myModal').hide();", true);
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myModalAgainShow", "$('#myModal').modal();", true);
        }


Note : If sometime we want to hide parent modal and want to show child modal then we have to add following code to hide Modal.
and If bootstrap modal-backdrop doesn't disappear

ScriptManager.RegisterStartupScript(Page,Page.GetType(), "myModalHide""$('body').removeClass('modal-open');$('.modal-backdrop').remove();$('#myModal').hide();"true);


Outoput:



Tuesday 2 June 2015

Open Link in Disabled Window using JavaScript

Below code is to open the link with disabled address bar and toolbar using javascript.

We have window.open() method to get the link in new window and before this we set some attributes to new window in strWindowFeatures.

Also, you can use this code for ASP.NET Hyperlink tag.

Copy this code and  save it as filename.html to get the result.

<html>
<head>
<script>
var windowObjectReference;
var strWindowFeatures="height="+screen.height+",width="+screen.width+",fullscreen=yes,menubar=no,location=no,resizable=no,scrollbars=yes,status=no";

function openRequestedPopup()
{
windowObjectReference=window.open("http://www.google.co.in/","Google",strWindowFeatures);
}
</script>
</head>

<body>
  <form>
    <a href="#" onClick="openRequestedPopup()">Click</a>
  </form>
</body>

</html>