Thursday, October 15, 2015

Using WebForms ReportViewer Control Inside AngularJS Single Page Application

WebForms ReportViewer control can be used to render reports deployed to SQL Server Reporting Servcies (SSRS) Report Server or reports which exists in local machine inside a web application. In this post, let’s see how we can use the WebForms ReportViewer control inside a AngularJS Single Page Application to render reports deployed in SSRS Report Server.

I have a SPA running with Visual Studio created using one of my previous posts “Creating an Empty ASP.NET Project Powered by AngularJS using Visual Studio”. And I have set of reports deployed to SSRS Report Server already (Here I am not going to explain how you can deploy reports to SSRS Report Server). Let’s extend the the same application to include the ReportViewer inside Home page. My plan is to add a ReportViewer control inside ASP.NET Web Form and embed that particular page inside home page using an iframe.

So for that let’s start by adding a WebForm to the project. In my example, I am creating a folder inside App folder named pages and adding the WebForm there and naming it as Viewer.aspx.
image
Add WebForm
Now on the designer of Viewer.aspx, I am adding a ReportViewer control, from the Visual Studio Toolbox.
image
ReportViewer
So this is how my Viewer.aspx looks like after adding the ReportViewer.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Viewer.aspx.cs" Inherits="AngularJSSample.App.pages.Viewer" %> 

<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %> 

<!DOCTYPE html> 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
 
        <div style="height: 600px;">
            <rsweb:ReportViewer ID="reportViewer" runat="server" Width="100%" Height="100%"></rsweb:ReportViewer>
        </div>
    </form>
</body>
</html>
I have done some styling here, you can also apply whatever the styles you need. Also I have added a script manager, because the ReportViewer web control requires a script manager on the web form. Now inside the Viewer.aspx code behind, we need to add the code for processing the report.
public partial class Viewer : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                string reportId = Request.QueryString["id"].ToString();
 

                string reportServerUrl = ConfigurationManager.AppSettings["ReportServerURL"];
                string domain = ConfigurationManager.AppSettings["rsDomain"];
                string userName = ConfigurationManager.AppSettings["rsUserName"];
                string password = ConfigurationManager.AppSettings["rsPassword"];
                string reportPath = ConfigurationManager.AppSettings["ReportPath"];
 
                reportViewer.ServerReport.ReportServerUrl = new Uri(reportServerUrl);
                reportViewer.ServerReport.ReportServerCredentials = new ReportCredentials(userName, password, domain);
                reportViewer.ServerReport.ReportPath = string.Format(reportPath, reportId);
                reportViewer.ProcessingMode = ProcessingMode.Remote;
                reportViewer.ShowCredentialPrompts = false;
                reportViewer.ServerReport.Refresh();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}
Here the page will receive a URL parameter through a query string which specifies the report id to render. Basically the report id would be the report name which is deployed to SSRS Report Server. And I am retrieving following values from the web.config file.
<appSettings>
    <add key="ReportServerUrl" value="REPORT_SERVER_URL" /> <!--http://localhost/ReportServer etc.-->
    <add key="rsDomain" value="DOMAIN" />
    <add key="rsUserName" value="USERNAME" />
    <add key="rsPassword" value="PASSWORD" />
    <add key="ReportPath" value="/PATH_TO_REPORT_FOLDER/{0}" />
</appSettings>
You can find your ReportServerUrl from the SQL Server Reporting Services Configuration Manager.

image
SQL Server Reporting Services Configuration Manager
For ReportServerCredentials, I have the following the class ReportCredentials which is an  implementation of IReportServerCredentials.
public class ReportCredentials : IReportServerCredentials
{
    public ReportCredentials(string userName, string password, string domain)
    {
        UserName = userName;
        Password = password;
        Domain = domain;
    }
 
    public WindowsIdentity ImpersonationUser
    {
        get
        {
            return null;
        }
    }

    public ICredentials NetworkCredentials
    {
        get
        {
            return new NetworkCredential(UserName, Password, Domain);
        }
    }
 
    private string UserName { get; set; }
    private string Password { get; set; }
    private string Domain { get; set; }
 
    public bool GetFormsCredentials(out Cookie authCookie, out string userName, out string password, out string authority)
    {
        authCookie = null;
        userName = password = authority = null;
        return false;
    }
}
Here since I am not using any impersonation, ImpersonationUser is null and since I am not using forms authentication GetFormsCredentials method is returning false.

Next step is to show the list of reports and embed the Viewer.aspx web form inside the html page.
<div>
    <div ng-repeat="report in reports">
        <input type="button" ng-click="openReport(report.id)" value="{{report.name}}" />
    </div>
    
    <form class="form-horizontal" style="height: 100%;">
        <div style=" height:100%; background-color: transparent">
            <iframe src="{{'http://localhost:29986/App/pages/Viewer.aspx?id=' + reportId | trustAsResourceUrl}}" style="width:100%;height:600px"></iframe>
        </div>
    </form>
</div>
Here I have set of reports where I am ng-repeating and when clicking on an item, I am invoking the openReport method. Basically it will assign the report id to the model variable which I am passing as a query parameter to Viewer.aspx. On click on report items, it will make the iframe source different, which will load the particular report.
.controller('homeController', function ($scope) {
    $scope.message = "Now viewing home!";
 
    $scope.reports = [
       {
           id: 'Report1',
           name: 'Report 1'
       },
       {
           id: 'Report2',
           name: 'Report 2'
       },
    ]; 

    $scope.reportId = $scope.reports[0].id; 

    $scope.openReport = function (reportId)
    {
        $scope.reportId = reportId;
    }
})
Even you can get the available reports by calling the SSRS Report Server Web Service.

I have the following directive as well, to make Strict Contextual Escaping for the web forms absolute url.
.filter('trustAsResourceUrl', ['$sce', function ($sce) {
    return function (val) {
        return $sce.trustAsResourceUrl(val);
    };
}]);

So that’s it. Now let’s run the application.
image
Report 1
image
Report 2
I am uploading the full code sample to my OneDrive. Do check that out!
https://1drv.ms/f/s!Ao4_b-zu7IRfiK0oBxpxFOiUYQcTXg

Happy Coding.

Regards,
Jaliya

Sunday, September 20, 2015

Visual C# Technical Guru - August 2015

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category.

The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - August 2015
Happy Coding.

Regards,
Jaliya

Tuesday, September 15, 2015

Wrote a TNWiki Article Spotlight at Official Blog of TechNet Wiki

In this week’s TNWiki Article Spotlight, I wrote a post highlighting an article won the July month's TechNet Guru Awards under Windows Presentation Foundation (WPF) Category, an article created by Andy ONeill titled WPF: Inheriting Property Values Considered.

image
TNWiki Article Spotlight - WPF: Inheriting Property Values Considered
Read the post on,
TNWiki Article Spotlight - WPF: Inheriting Property Values Considered

Happy Coding.

Regards,
Jaliya

Wednesday, September 9, 2015

ReadOnlyCollection<T> in C#, Is It Really Read Only?

With .NET 2.0 ReadOnlyCollection<T>  was introduced and I have seen this question “Is ReadOnlyCollection<T> really read only?”. Well the simple answer is, it is, but you need to understand how this works and otherwise you will be surprised with some results. In this post, let’s see how  ReadOnlyCollection<T> works.

For example, let’s take following List of type string.
List<string> strings = new List<string>()
{
    "Visual Studio 2010","Visual Studio 2012","Visual Studio 2013"
};
So basically there is two ways that I can create a ReadOnlyCollection<T> from this.
ReadOnlyCollection<string> readOnlyStrings = strings.AsReadOnly();
// or
ReadOnlyCollection<string> readOnlyStrings = new ReadOnlyCollection<string>(strings);
One from calling List<T>.AsReadOnly() method which will return a ReadOnlyCollection<T> or by calling the constructor of ReadOnlyCollection<T>. Both of this will achieve the same.

Now if you try to modify the readOnlyStrings collection, you can’t. Because it is read only. But what about modifying strings collection which is of type List<T>. Well you should be able to modify it for example by adding a new item.
strings.Add("Visual Studio 2015");
Now let’s see what do we have on the readOnlyStrings collection.
foreach (string item in readOnlyStrings)
{
    Console.WriteLine(item);
}
image
Result
Surprisingly you will see that your readOnlyStrings collection has been modified. But did you add an item to readOnlyStrings, No, but you did add an item to strings.

So what happened here is nicely described on MSDN.

“An instance of the ReadOnlyCollection<T> generic class is always read-only. A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes.”

Now let’s take another scenario.

Here I have a simple class named VisualStudio and there I have a helper method which will return new instance of List<VisualStudio>.
class VisualStudio
{
    public string Version { get; set; }
 
    public static List<VisualStudio> GetVisualStudios()
    {
        return new List<VisualStudio>()
        {
            new VisualStudio() { Version = "Visual Studio 2010" },
            new VisualStudio() { Version = "Visual Studio 2012" },
            new VisualStudio() { Version = "Visual Studio 2013" },
        };
    }
}
Now I have the following ReadOnlyCollection<T> where T is VisualStudio.
ReadOnlyCollection<VisualStudio> readOnlyVisualStudios = new ReadOnlyCollection<VisualStudio>(VisualStudio.GetVisualStudios());
Now let’s try to modify an item in the readOnlyVisualStudios and see the content of readOnlyVisualStudios.
readOnlyVisualStudios[0].Name = "Microsoft Visual Studio 2010";
 
foreach (VisualStudio item in readOnlyVisualStudios)
{
    Console.WriteLine(item.Name);
}
image
Result
Again it seems readOnlyVisualStudios has been modified. This shows another feature of ReadOnlyCollection<T>. That is when the T in ReadOnlyCollection<T> is a complex type, the individual items of ReadOnlyCollection<T> can be modified either by changing the values of it’s properties or by calling the methods of complex type. But the following is illegal and will throw an error.
readOnlyVisualStudios[0] = null;
// or
readOnlyVisualStudios[0] = new VisualStudio() { Name = "Microsoft Visual Studio 2010" };

So that’s it.  Keep in mind that when working with ReadOnlyCollection<T>, you need to make sure, you are not letting the underline collection to be modified or only let the class that contains the underline collection to modify  it and not others for instance like below.
private List<string> strings;
public ReadOnlyCollection<string> Strings
{
    get { return new ReadOnlyCollection<string>(strings); }
}
If you want your strings which is of List<T> to be read only, make it private so you (containing class) can do what ever you want and expose as a public ReadOnlyCollection<T> to consumers.

Hope this helps.

Happy Coding.

Regards,
Jaliya

Sunday, August 30, 2015

Received Microsoft Community Contributor (MCC) Badge for the First Time!

Today I just noticed that I have received the Microsoft Community Contributor (MCC) badge for the first time and Thank you Microsoft!
2015-08-31_12-38-24
Microsoft Community Contributor
And if you want to become one, read the following to know how.

MICROSOFT COMMUNITY CONTRIBUTOR (MCC)

PROCESS: Microsoft automatically reviews the contributions of participants who offer their time and energy to online technical communities such as Microsoft Answers/Community, MSDN, and TechNet to identify those who make notable contributions for possible recognition as a Microsoft Community Contributor. Microsoft employees cannot become MCCs, but MVPs can become MCCs. MCC is an automatic reward (nobody can help you win it by nominating you). 

REWARD: The reward is a "small benefit": the award status in your profile on the online community (MSDN, TechNet, etc.) and your name on a list of MCC award recipients. The MCC badge ends after ninety days (three months) from the date found within the welcome email.

Tips to becoming an MCC (based on the FAQ)
1) Make an impact in the community, using tools like TechNet and MSDN Forums. Maintain quality and quantity in your contributions.
2) Rule the Forums. Find a technology's forum (on MSDN or TechNet) where there's a huge need for moderation and answerers. Become an expert in that technology. Then answer a ton of questions with quality answers, propose a lot of answers (especially ones that aren't from you), and then request to be made an Answerer or Moderator. See How to Become an MSDN or TechNet Forum Moderator. Try to get a lot of quality answers completed.
NOTE: This award is based on your contributions in the last 3 months. In other words, if you just started one week ago, you'll need to continue your efforts for a few more months.
NOTE: MCC is an automatic reward (nobody can help you win it by nominating you).

For more information,

Happy Coding.

Regards,
Jaliya

Thursday, August 20, 2015

Visual C# Technical Guru - July 2015

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category.

The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - July 2015
Happy Coding.

Regards,
Jaliya

Thursday, August 13, 2015

C# : String vs. string

I have seen this confusion over and over, and thought of writing a post about it. Basically String and string are both the same. If you go to definition (F12) on String or string, you will see that you will be navigated to the same String class. string is an alias for System.String.

So now you must be thinking, if these two are similar, when should we use String or string. Again there is no strict rule for which to use, but as a practice we are maintaining following standards. If you are using the string type for a variable, use string. If you accessing String classes' methods, then use String.

Let me show you what I mean.
class Program
{
    static void Main(string[] args)
    {
        string value1 = System.String.Empty;
        string value2 = System.String.Format("{0} {1}", "Hello", "World");
        string value3 = System.String.Concat("Hello", " ", "World");
 
        if (System.String.IsNullOrEmpty(value1))
        { 
            // some implementation
        }
 
        // etc.
    }
}
 
class String
{
 
}

Above code will be compiling fine. But it’s good to note one important thing. string is a reserved keyword and String is yet another class. So theoretically there is nothing wrong having an another class named String in your project. But that is highly unlikely.

Hope this helps.

Happy Coding.

Regards,
Jaliya