Wednesday, October 21, 2015

How to Incorporate SSRS Report into MVC 5 Web Application

For traditional ASP.Net Web Form application, you can use ReportViewer control to show your SSRS report. However, for ASP.Net MVC application, you can't use the control in Razor page. Even you can add Web Form into MVC application, these Web Forms are difficult to have similar look and fell as your normal Razor page.

Fortunately, there is a ReportViewer for MVC tool which can help you to resolve this problem.

At first, you need to install the tool from NuGet. Run following command in the Package Manage Console to install the tool:
PM> Install-Package ReportViewerForMvc
Then add reference in your controller to Microsoft.Reporting.WebForms:
using Microsoft.Reporting.WebForms;
Create a new instance of ReportViewer:
ReportViewer reportViewer = new ReportViewer();
reportViewer.ProcessingMode = ProcessingMode.Remote;

reportViewer.ServerReport.ReportPath = "/AdventureWorks 2012/Sales_by_Region";
reportViewer.ServerReport.ReportServerUrl = new Uri("http://localhost/ReportServer/");

ViewBag.ReportViewer = reportViewer;
Above is for the situation that you put all your report on your SQL Server. However, every time your application access those reports, which usually required authorization, you would offer user name and password. To avoid this situation, you can put all your report to your local along with your web application. For this purpose, you need to change the report viewer's ProcessingMode.
        public ActionResult Report2()
        {
            SqlConnection connect = new SqlConnection(connectionString);
            SqlDataAdapter dataAdapter = new SqlDataAdapter();
            SqlCommand cmd = connect.CreateCommand();
            cmd.CommandText = 
               @"SELECT  DimOrganization.OrganizationName, DimDepartmentGroup.DepartmentGroupName, DimDate.CalendarYear, DimDate.EnglishMonthName, DimDate.MonthNumberOfYear, SUM(FactFinance.Amount) AS SubTotalAmount
                 FROM FactFinance INNER JOIN
                     DimDate ON FactFinance.DateKey = DimDate.DateKey INNER JOIN
                     DimDepartmentGroup ON FactFinance.DepartmentGroupKey = DimDepartmentGroup.DepartmentGroupKey INNER JOIN
                     DimOrganization ON FactFinance.OrganizationKey = DimOrganization.OrganizationKey
                 GROUP BY DimOrganization.OrganizationName, DimDepartmentGroup.DepartmentGroupName, DimDate.CalendarYear, DimDate.EnglishMonthName, DimDate.MonthNumberOfYear
                 Order by   DimDate.CalendarYear,  DimDate.MonthNumberOfYear";
            dataAdapter.SelectCommand = cmd;
            DataSet dataSet = new DataSet();

            connect.Open();
            dataAdapter.Fill(dataSet);
            connect.Close();
            ReportViewer reportViewer = new ReportViewer()
            {
                SizeToReportContent = true,
                Width = System.Web.UI.WebControls.Unit.Percentage(100),
                Height = System.Web.UI.WebControls.Unit.Percentage(100),
            };
            reportViewer.ProcessingMode = ProcessingMode.Local;

            reportViewer.LocalReport.ReportPath = Request.MapPath(Request.ApplicationPath) + @"Reports\Report2.rdlc";
            reportViewer.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", dataSet.Tables[0]));

            ViewBag.ReportViewer = reportViewer;

            return View();
        }
Note the report defined file is RDLC file not RDL file. You can just simply rename the file format. RDLC file and RDL file shared same XML Schema, and RDLC file may contains empty values.

Since the RDLC doesn't contain any data source information to increase the flexibility, you need to supply data source within your controller. In addition, you need to use same data set name as your SSRS report, for above code, DataSet1 is used as the SSRS report defined. Because the DataSet1 actually used sql script, so SQLConnection and SQLAdapter are applied here to fill the dataset.

To make the report view area variable for your browser, you need to add parameters when creating the ReportViewer class:
            ReportViewer reportViewer = new ReportViewer()
            {
                SizeToReportContent = true,
                Width = System.Web.UI.WebControls.Unit.Percentage(100),
                Height = System.Web.UI.WebControls.Unit.Percentage(100),
            };
The last is for the view. Add reference at first.
@using ReportViewerForMvc;
Using the building html helper the report in your page.
@Html.ReportViewer(ViewBag.ReportViewer as Microsoft.Reporting.WebForms.ReportViewer)

Resource:
https://reportviewerformvc.codeplex.com/wikipage?title=Getting%20Started
http://stackoverflow.com/questions/1079162/when-to-use-rdlc-over-rdl-reports

Tuesday, October 20, 2015

SQL Server SSRS Date Format List

Most SSRS Reports required date parameters and need to handling date format conversion. SSRS used VB style function inside their expression, which has Left, Mid, Right, Len, Trim, Ltrim, Rtrim, etc, and & to connect strings.

SSRS supports various and flexible date format which applying similar SQL style format string:

Format Code         Description                                  Example
dSingle Digit Date Format9
d Single Digit Date Format 9
dd Double Digit Date Format 9
ddd or dddd Full Day Name Wednesday
M Single Digit Month Format 2
MM Double Digit Month Format 2
MMM Three Character Month Name Feb
MMMM Full Month Name February
yy Double Digit Year Format 11
yyyy Four Digit Year Format 2011
H Single Digit “24 Hour” Hour Format 6
HH Double Digit “24 Hour” Hour Format 6
m Single Digit Minute Format 9
mm Double Digit Minute Format 9
s Single Digit Second Format 4
ss Double Digit Second Format 4
tt ante meridian (AM)/post meridian (PM) part of Time PM
zzz Time Zone Offset w.r.t. GMT +05:30

Monday, October 19, 2015

How to Create Tabbed SSRS Report

You can use SQL Server Report Designer to create Tabs for your SSRS Report. The basic idea is to create one Rectangle at first, and put several TextBox inside the Rectangle. You can treat those TextBox as Tabs, and fill them with your favorite button image as background to let them looked better. The last thing for those TextBox is adding Action property for those TextBox and put your report name to link those tab to your report.

Note if your report goes to the next page, those Tabs would be disappear. To resolve this issue, simply fill the RepeatWith property for the Rectangle with available tablix for each report.

Another issue is when we output our report with pdf or excel format, we don't want to show those tabs, thus we need to hide them. To resolve this issue, add the following expression to the hidden property to each rectangle:

=Globals!RenderFormat.IsInteractive = FALSE

You can also set the Page Name property of each tablix to the name of the tab.



Source:
https://bistuffwithdigven.wordpress.com/2013/01/20/tabbed-ssrs-reports/

Friday, October 16, 2015

How to applying Bootstrap 3 Fluid theme to ASP.Net MVC 5 Project

After you installed a fully functional ASP.Net MVC 5 template, you can use it to create a new project, which has installed Bootstrap 3 already, as following screenshot showed.

The default bootstrap template used in the template is Jumbtron, Jumbtron is not a fluid layout template, which means it has fixed screen layout, thus can't adapt for different screen size with those devices such as iPad, or smart phone. 

So the next thing is to change the css template to Justified-Nav, which is a fluid layout template from bootstrap website, will re-align itself based on the different screen size. You can get the css file from here. For doing this, you can right click on the Content folder from Solution Explorer and choose Add New Item, and choose Style Sheet file format, and paste the following content from bootstrap website into the new file, and then rename it as justified-nav.css.
body {
  padding-top: 20px;
}

.footer {
  padding-top: 40px;
  padding-bottom: 40px;
  margin-top: 40px;
  border-top: 1px solid #eee;
}

/* Main marketing message and sign up button */
.jumbotron {
  text-align: center;
  background-color: transparent;
}
.jumbotron .btn {
  padding: 14px 24px;
  font-size: 21px;
}

/* Customize the nav-justified links to be fill the entire space of the .navbar */

.nav-justified {
  background-color: #eee;
  border: 1px solid #ccc;
  border-radius: 5px;
}
.nav-justified > li > a {
  padding-top: 15px;
  padding-bottom: 15px;
  margin-bottom: 0;
  font-weight: bold;
  color: #777;
  text-align: center;
  background-color: #e5e5e5; /* Old browsers */
  background-image: -webkit-gradient(linear, left top, left bottom, from(#f5f5f5), to(#e5e5e5));
  background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e5e5e5 100%);
  background-image:      -o-linear-gradient(top, #f5f5f5 0%, #e5e5e5 100%);
  background-image:         linear-gradient(to bottom, #f5f5f5 0%,#e5e5e5 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f5f5f5', endColorstr='#e5e5e5',GradientType=0 ); /* IE6-9 */
  background-repeat: repeat-x; /* Repeat the gradient */
  border-bottom: 1px solid #d5d5d5;
}
.nav-justified > .active > a,
.nav-justified > .active > a:hover,
.nav-justified > .active > a:focus {
  background-color: #ddd;
  background-image: none;
  -webkit-box-shadow: inset 0 3px 7px rgba(0,0,0,.15);
          box-shadow: inset 0 3px 7px rgba(0,0,0,.15);
}
.nav-justified > li:first-child > a {
  border-radius: 5px 5px 0 0;
}
.nav-justified > li:last-child > a {
  border-bottom: 0;
  border-radius: 0 0 5px 5px;
}

@media (min-width: 768px) {
  .nav-justified {
    max-height: 52px;
  }
  .nav-justified > li > a {
    border-right: 1px solid #d5d5d5;
    border-left: 1px solid #fff;
  }
  .nav-justified > li:first-child > a {
    border-left: 0;
    border-radius: 5px 0 0 5px;
  }
  .nav-justified > li:last-child > a {
    border-right: 0;
    border-radius: 0 5px 5px 0;
  }
}

/* Responsive: Portrait tablets and up */
@media screen and (min-width: 768px) {
  /* Remove the padding we set earlier */
  .masthead,
  .marketing,
  .footer {
    padding-right: 0;
    padding-left: 0;
  }
}
Then you need to add the new css file into BundleConfig, find the following script:
            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/justified-nav.css",));
Add replace them with
            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css",
                      "~/Content/justified-nav.css"));
Now open _Layout.cshtml from Views folder:
Replace the section of div tag with class="navbar navbar-inverse navbar-fixed-top":

    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", null, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
with following:
    <div class="container">
        <div class="masthead">
            <h3 class="text-muted">@Html.ActionLink("Application name", "Index", "Home")</h3>
        </div>
        <ul class="nav nav-justified">
                <li>@Html.ActionLink("Home", "Index", "Home", null, new { @class = "active" })</li>
                <li>@Html.ActionLink("About", "About", "Home")</li>
                <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
        </ul>
         @Html.Partial("_LoginPartial")
    </div>
Open Index.cshtml from Views\Home, replace following tag class="col-md-4" to following tag  class="col-lg-4".

Now you can compile your project and your final output would be like this:

Source:
http://www.mytecbits.com/microsoft/dot-net/bootstrap-3-with-asp-net-mvc-5

Thursday, October 15, 2015

Applying MVC 5 on Visual Studio 2012 Express

Visual Studio 2013 has been shipped with MVC 5 along with .Net 4.5.1 2 years ago. It even included a free communication version with full functionality. Since then, it has evolved with 5 updated versions until  July 2015.

Visual Studio 2013 combines Nuget 2.7, ASP.Net MVC 5, ASP.Net Web API 2, Entity Framework 6, ASP.Net Razor, ASP.Net Scaffolding, a new code generating framework for ASP.Net web applications, and Bootstrap 3, a layout and theme framework from twitter to provide responsive design through CSS 3, etc. Such new features are exciting for all ASP.Net web developers. However, for Microsoft Database or BI developers, if they are stick to SQL Server 2012, they would better to keep their old Visual Studio 2012 as the support for BI development such as SSAS/SSRS/SSIS 2012 on Visual Studio 2013 are not perfect.

Fortunately, Microsoft announced MVC 5 for visual studio 2012. Also, Visual Studio 2012 Update 4 and ASP.Net and Web Tools 2013.1 for Visual Studio  2012 would be also required, especially for Visual Studio 2012 Express for Web.

After you installed the web tools 2013.1 for Visual Studio 2012, your Visual Studio 2012 for Web would show following new ASP.Net web templates:

Note you still can't find a fully functional ASP.Net MVC 5 Web Application template, except an empty one.

You can create a new project using ASP.Net MVC 5 Empty Project, and then right click on the project, click Add.. > New Scaffolded Item..., select MVC on the left, then MVC 5 Dependencies and choose Full dependencies from the prompt.

This will add a default layout Views\Shared\_Layout.cshtml, Content folder, Scripts folder with bootsrap, jquery, modernizer, etc, and other things the Web Application template will create.

You could get the error "CS0103: The name 'Styles' doesnot exist in the current context", just add <namespace="System.Web.Optimization"/>  under <namespaces> in Views/web.config.

To add a fully functional ASP.Net MVC 5 Web Application template, download the MVC 5 template from here. Copy the file into the following folder of your PC:
%USERPROFILE%\Documents\Visual Studio 2012\Templates\ProjectTemplates\Visual C#\Web
and then change DefaultConnection in Web.config with following format:
<connectionStrings>
    <add name="MyDBConnection" connectionString="Data Source=localhost;Initial Catalog=MyDB;
        Persist Security Info=True;User ID=MyName;Password=MyPassword"
    providerName="System.Data.SqlClient"/>
</connectionStrings>
Now you can restart you Visual Studio 2012 express for Web and enjoy the new MVC 5 template.

If during the debug, you get the error "CS0234: The type or namespace name 'Ajax' does not exist in the namespace 'System.Web.Mvc' (are you missing an assembly reference?)", simply open the reference directory of your project under solution explorer, right click on the package name, choose the property, and change the Copy Local to true.

Note after you created your MVC 5 application, if you open your web.config file, you could find following issue:

It was said "The entityframework element has invalid child element providers.". This could give warning message for your project. To resolve this warning, you need to copy following 2 files:
to folder: "C:\Program Files\Microsoft Visual Studio 11.0\Xml\Schemas":

1. EntityFrameworkCatalog.xml
<?xml version="1.0" encoding="utf-8"?>
<SchemaCatalog xmlns="http://schemas.microsoft.com/xsd/catalog">
    <Association extension="config" schema="%InstallRoot%/xml/schemas/EntityFrameworkConfig_6_1_4.xsd" />
</SchemaCatalog>
2. EntityFrameworkConfig_6_1_4.xsd
<?xml version="1.0" encoding="utf-8"?>

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="entityFramework">
    <xs:complexType>
      <xs:all>
        <xs:element name="defaultConnectionFactory" type="ElementWithTypeAndParameters_Type" minOccurs="0" maxOccurs="1" />
        <xs:element name="providers" type="ProviderList_Type" minOccurs="0" maxOccurs="1" />
        <xs:element name="contexts" type="ContextList_Type" minOccurs="0" maxOccurs="1" />
        <xs:element name="interceptors" type="InterceptorList_Type" minOccurs="0" maxOccurs="1" />
      </xs:all>
      <xs:attribute name="codeConfigurationType" type="NonEmptyString_Type" use="optional" />
      <xs:anyAttribute namespace="http://schemas.microsoft.com/XML-Document-Transform" processContents="strict"/>
    </xs:complexType>
  </xs:element>

  <xs:complexType name="ProviderList_Type">
    <xs:sequence>
      <xs:element name="provider" type="Provider_Type" minOccurs="0" maxOccurs="unbounded" />
    </xs:sequence>
    <xs:anyAttribute namespace="http://schemas.microsoft.com/XML-Document-Transform" processContents="strict"/>
  </xs:complexType>

  <xs:complexType name="Provider_Type">
    <xs:attribute name="invariantName" type="NonEmptyString_Type" use="required" />
    <xs:attribute name="type" type="NonEmptyString_Type" use="required" />
    <xs:anyAttribute namespace="http://schemas.microsoft.com/XML-Document-Transform" processContents="strict"/>
  </xs:complexType>

  <xs:complexType name="ContextList_Type">
    <xs:sequence>
      <xs:element name="context" type="Context_Type" minOccurs="0" maxOccurs="unbounded" />
    </xs:sequence>
    <xs:anyAttribute namespace="http://schemas.microsoft.com/XML-Document-Transform" processContents="strict"/>
  </xs:complexType>

  <xs:complexType name="Context_Type">
    <xs:choice>
      <xs:element name="databaseInitializer" type="ElementWithTypeAndParameters_Type" minOccurs="0" maxOccurs="1" />
    </xs:choice>
    <xs:attribute name="type" type="NonEmptyString_Type" use="required" />
    <xs:attribute name="disableDatabaseInitialization" type="SmallBoolean_Type" use="optional" />
    <xs:attribute name="commandTimeout" type="xs:int" use="optional" />
    <xs:anyAttribute namespace="http://schemas.microsoft.com/XML-Document-Transform" processContents="strict"/>
  </xs:complexType>

  <xs:complexType name="InterceptorList_Type">
    <xs:sequence>
      <xs:element name="interceptor" type="ElementWithTypeAndParameters_Type" minOccurs="0" maxOccurs="unbounded" />
    </xs:sequence>
    <xs:anyAttribute namespace="http://schemas.microsoft.com/XML-Document-Transform" processContents="strict"/>
  </xs:complexType>

  <xs:complexType name="ElementWithTypeAndParameters_Type">
    <xs:choice>
      <xs:element name="parameters" type="ParameterList_Type" minOccurs="0" maxOccurs="1" />
    </xs:choice>
    <xs:attribute name="type" type="NonEmptyString_Type" use="required" />
    <xs:anyAttribute namespace="http://schemas.microsoft.com/XML-Document-Transform" processContents="strict"/>
  </xs:complexType>

  <xs:complexType name="ParameterList_Type">
    <xs:sequence>
      <xs:element name="parameter" type="Parameter_Type" minOccurs="0" maxOccurs="unbounded" />
    </xs:sequence>
    <xs:anyAttribute namespace="http://schemas.microsoft.com/XML-Document-Transform" processContents="strict"/>
  </xs:complexType>

  <xs:complexType name="Parameter_Type">
    <xs:attribute name="value" type="NonEmptyString_Type" use="required" />
    <xs:attribute name="type" type="NonEmptyString_Type" use="optional" />
    <xs:anyAttribute namespace="http://schemas.microsoft.com/XML-Document-Transform" processContents="strict"/>
  </xs:complexType>

  <xs:simpleType name="SmallBoolean_Type">
    <xs:restriction base="xs:NMTOKEN">
      <xs:enumeration value="false" />
      <xs:enumeration value="true" />
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="NonEmptyString_Type">
    <xs:restriction base="xs:string">
      <xs:minLength value="1" />
    </xs:restriction>
  </xs:simpleType>

</xs:schema>
These 2 files can be found at this link:

Source:
http://www.asp.net/visual-studio/overview/2013/release-notes
http://stackoverflow.com/questions/19102831/how-to-install-asp-net-mvc-5-in-visual-studio-2012
http://stackoverflow.com/questions/18288215/how-can-i-add-the-mvc-5-project-template-to-vs-2012
http://stackoverflow.com/questions/20607648/no-asp-net-mvc-5-web-application-template-on-vs-2012
http://stackoverflow.com/questions/20068833/the-element-entityframework-has-invalid-child-element-entity-framework