Friday, 29 May 2015

Displaying SSRS Report in MVC using MvcReportViewer -Part II

Embedding a Local Report


In my previous post we discussed how to install the MVCReportViewer package via Nuget into your application to avail of the helpers to embed SSRS reports into your MVC views.

In this article we will discuss using the MVCReportViewer  package and helpers to embed local reports.

Most often people want to embed SSRS reports from the server into thier views, but sometimes we just want to create a simple local report in Visual Studio and display that in our view. This is the scenario we will discuss below.

Creating reports in Visual Studio 2012/2013

Visual Studio 2012/2013 comes with reporting capibilites out of the box. Simply right click in your solution explorer in Visual Studio and Add Item/ Reporting and you can see you have the option to add a Report or use the Report Wizard.



















This provides you with good basic reports, it's like a pared down version of the tools and controls you get with real SSRS. If this suits your needs you need go no further. However if you need more capilibilites than whats on offer here you will need to install the SQL Server Data Tools – Business Intelligence tools  for Visual Studio 2012/2013.

SQL Server Data Tools – Business Intelligence for Visual Studio 

Currently the URL to download Microsoft Visual Studio Tools for Applications component for Visual Studio 2012 can be found here:

http://www.microsoft.com/en-ca/download/details.aspx?id=38807

Once you have install it, you will be able to create and work with SSRS reports within Visual Studio. Here are the basic steps for setting up a new SSRS report project:

Open up Visual Studio

  • Select File –> New –> Project
  • You will now see a new project template option called Business Intelligence
  • Expand this project template and select the Reporting Services option.
  • You can now either choose to use the setup wizard or just a plain project template.


Regardless of whether your requirements necessitate the use of the Business Intelligence tools or the standard out of the box reporting tools in Visual Studio, lets now disucss adding a basic report to your project so you can embed it in your MVC view.

DataSets

Before creating your report, you need to define your dataset. Lets create a Report folder in our project. It is a good idea to organise your folder structure within your application in a logical manner , so we will use this folder for all our Datasets and reports.

Using the standard out of the box reporting functionality in Visual Studio 2012/2013, right-click in your Report folder and Add New item.

Go to Data-> and select Dataset. Call it 

Displaying SSRS Report in MVC using MvcReportViewer -Part I

In this article we will discuss installing the MVCReportViewer package into your MVC application to get it ready to embed reports. 

In Part 2 , we will discusss embedding local reports into your MVC application and in Part 3 we will discuss the changes needed to embed reports from yourn SSRS server.

Embedding SSRS or indeed local RDLC reports into a  view in an ASP.NET MVC application is easy using the MVCReportViewer package , and the HTML Helpers it comes with.

The first step to get the MVCReportViewer package installed into your project , to do this you can use the Package manager console in Visual Studio , using the following command:

PM> Install-Package MvcReportViewer
This will add the relevant scripts, Web.Config app settings and report viewer appx to your MVC Application which are needed to embed your reports into your views.

After sucessfully installing the MVCReportViewer package you will notice some changes to your application. 

The following App settings for the report viewer have been added to your Web.Config:


<add key="MvcReportViewer.AspxViewer" value="/MvcReportViewer.aspx" />
<add key="MvcReportViewer.AspxViewerJavaScript" value="~/Scripts/MvcReportViewer.js" />
<add key="MvcReportViewer.ErrorPage" value="~/MvcReportViewerErrorPage.html" />
<add key="MvcReportViewer.ShowErrorPage" value="true" />

<add key="MvcReportViewer.ReportServerUrl" value="http://localhost/Reportserver_SQLEXPRESS" />
<add key="MvcReportViewer.Username" value="" />
<add key="MvcReportViewer.Password" value="" />
<add key="MvcReportViewer.EncryptParameters" value="false" />
<add key="MvcReportViewer.IsAzureSSRS" value="false" />

<add key="MvcReportViewer.LocalDataSourceProvider" value="MvcReportViewer.SessionLocalDataSourceProvider, MvcReportViewer" />


Key settings to note here , are the AspxViewer setting, which points to the aspx page which has also been installed by the NuGet package . It is this page that will be used to display our report in an iframe. 

The ReportServerUrl and LocalDataSourceProvider settings are important depending on wehther you want to embed a server report or a local one. I will use both later on when i give examples of both scenarios.

And that's it, now you are ready to embed a server or local report into your MVC views. See the following articles for examples of both.


Monday, 16 February 2015

Know It, Prove It

Anyone else doing the "Know It, Prove It" challenge on the Microsoft Virtual Academy site this February ? I'm half way through the Web Development challenge and really enjoying it.

Image result for know it prove it challenge

http://www.microsoftvirtualacademy.com/LearningPaths/Dashboard.aspx

Even if you're not taking part in the challenge, all the courses on the Virtual Academy are free and i highly recommend watching Learn-html5-with-javascript-css3-jumpstart-training with Michael Palermo and Jeremy Foster if you have a hour or two to spare. Its also recommended viewing for the Microsoft Exam 70-480 Programming in HTML5 with JavaScript and CSS3 if you're taking this Certification.

Thursday, 8 January 2015

Output Caching in ASP.NET MVC4

You can dramatically improve the performance of your ASP.NET MVC application very easily by taking advantage of the built-in output caching attributes. If you have an application that gets alot of traffic on a specific page , or returns a large list of records from a database you can use the output caching mechanism to cache the content returned by a controller action. And in doing so the same content does not need to be generated each and every time the same controller action is invoked causing unnecessary database hits and slowing down your page.

Most Output caching can be implemented very easily in MVC4 by using the standard OutputCacheAttribute class without having to go down the route of building a custom output cache provider. By decorating your controller actions with the outputcache attributes , you can maintain control over the duration of the cache of your actions.

First off , it's important to note that by default actions in asp.NET MVC have a cache-control of private.Which you can see by creating a simple action like the one below :

public JsonResult Details(int id)
{


////code here to get your results for your id


return Json(result, JsonRequestBehavior.AllowGet);

}


And then checking the header in the response in Fiddler or your tool of choice , and  you will see the cache-control :

Cache-Control:private
Connection:Close
Content-Length:81836
Content-Type:application/json; charset=utf-8
Date:Mon, 29 Oct 2012 08:08:44 GMT
Server:ASP.NET Development Server/11.0.0.0
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:3.0

This means that the browser might cache such ajax request made by a JavaScript client, which most of the time might not be desired. And can result in unexpected behaviour , especially in IE which is cache hungry. So often it is desirable to control what is cached and when yourself just to have some confidence in what is going on.


ASP.NET MVC Build-in caching mechanism

 You can control output caching by using the build-in output cache in asp.NET MVC. To do this you can decoration your controller actions with the outputcache attribute as follows.

[OutputCache(Duration = 6)]


public ActionResult Search(string searchText)
{


return Json(SearchWebService.MyWebServiceInstance.AutocompleteSearchClient(searchText),JsonRequestBehavior.AllowGet);

}

Now if we check our headers again , we can see our cache-control change :

Cache-Control: public, max-age=6
Expires: Mon, 29 Oct 2012 09:18:37 GMT
Last-Modified: Mon, 29 Oct 2012 09:18:34 GMT
Connection:Close
Content-Length:81836
Content-Type:application/json; charset=utf-8
Date:Mon, 29 Oct 2012 08:08:44 GMT
Server:ASP.NET Development Server/11.0.0.0
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:3.0

To see it in action for yourself , create a simple action like the one above , at first without the caching attribute and put a breakpoint in your controller action , you will note when you F5 the page , that it will hit the breakpoint every time.After decorating your action with the atttribute above , if you then run up your application , and F5 your page again , you can see that after the initial breakpoint being hit , the contents are cached and the breakpoint isnt hit again until your cache duration times out.

VaryByParam

The VaryByParam allows you to have different cached versions of the very same content. This property enables you to create different cached versions of the very same content for example when a query string parameter varies. By setting the VaryByParam property to “none” ,when the action is invoked, the same cached version of the action is returned i.e. any query string parameters are ignored , so usually if we have an action for a particular id , we'd want this to be cached based on the id , so we dont get the same results back.

If we have a number of params , and we want them all to be noted in the cache , we can either specific them semi-colon seperated list, or use the * in the VaryByParam value. E.G in the action which populates a grid below , we dont want the paging , sort and id queryparams to be ignored.

[OutputCache(Duration = 1, VaryByParam = "*")]
public ActionResult Index(int accountId, string page, string sort, string sortdir)
{

///code to get all accounts



return PartialView("_AccountsList", data);

}

File upload in MVC3/4

Those new to MVC or coming from classic ASP.NET might be a little daunted when first tasked with uploading a file in MVC , as there's no concept of the fileupload control (or any server side control for that matter)?

Thanks to Darin Dimitrov for the great example here:

Your controller

public class HomeController : Controller
{
// This action renders the form
public ActionResult Index()
{
return View();
}
// This action handles the form POST and the upload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
}


The view


@using (Html.BeginForm("Index""Home"FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />

<input type="submit" value="OK" />
}

Thursday, 4 September 2014

Mimicing Arrays or dynamic lists in SQL Server 2008

Often we might need to use arrays or dynamic lists in SQL server , we use them all the time in other programming languages without a second thought but we can replicate something similar by using table variables.  

Thanks to Pinal Dave for this great article on same.


This works in SQL server 2008 and upwards. To store a list of ints :

DECLARE @ListofIDs TABLE(IDs int);
INSERT INTO @ListofIDs
VALUES(1),(2),(3),(4),(5),(6);
SELECT IDs FROM @ListofIDs;
GO
Or strings:
DECLARE @ListofIDs TABLE(IDs VARCHAR(100));
INSERT INTO @ListofIDs
VALUES('a'),('10'),('20'),('c'),('30'),('d');
SELECT IDs FROM @ListofIDs;
GO
Or even to replicate a mulit-dimensional array :
DECLARE @Array TABLE(IDs int , Description VARCHAR(100));
INSERT INTO @Array
VALUES(1, 'Sydney'),(2,'Toyoko'),(3,'Dublin'),(4, 'London'),(5,'Madrid'),(6,'Paris');
SELECT FROM @Array;
GO

Very handy indeed ! For any version earlier than 2008 , since they don't support table variables , you'll have to use unions :

DECLARE @ListofIDs TABLE(IDs VARCHAR(100), ID INT IDENTITY(1,1));
INSERT INTO @ListofIDs
SELECT 'a'
UNION ALL
SELECT '10'
UNION ALL
SELECT '20'
UNION ALL
SELECT 'c'
UNION ALL
SELECT '30'
UNION ALL
SELECT 'd';
SELECT IDs FROM @ListofIDs;
GO

Tuesday, 3 June 2014

Interview resources


Reverse a number
using System;  
  public class ReverseExample  
   {
     public static void Main(string[] args)  
      {
       int  n, reverse=0, rem;           
       Console.Write("Enter a number: ");      
       n= int.Parse(Console.ReadLine());     
       while(n!=0)      
       {   
        rem=n%10;     
        reverse=reverse*10+rem;   
        n/=10;   
       }   
       Console.Write("Reversed Number: "+reverse);       
    }
  }
  

reverse a string #1

  static void Main() {

      string myStr, rev;

      myStr = "Tom";
      rev ="";

      Console.WriteLine("String is {0}", myStr);

      // find string length
      int len;
      len = myStr.Length - 1;

      while (len >= 0) {
         rev = rev + myStr[len];
         len--;
      }
      Console.WriteLine("Reversed String is {0}", rev);
      Console.ReadLine();
   }

Reverse a string #2

 public static string ReverseString(string s)
    {
        char[] arr = s.ToCharArray();
        Array.Reverse(arr);
        return new string(arr);
    }

Reverse a string #3 with loop


public static string ReverseStringDirect(string s)
    {
        char[] array = new char[s.Length];
        int forward = 0;
        for (int i = s.Length - 1; i >= 0; i--)
        {
            array[forward++] = s[i];
        }
        return new string(array);
    }

Reverse a string with extension method

string s = "olleh";
s.Reverse();
They also use the ToCharArray/Reverse combination that other answers to this question suggest. The source code looks like this:
public static string Reverse(this string input)
{
    char[] chars = input.ToCharArray();
    Array.Reverse(chars);
    return new String(chars);
}


FibonacciExample  :

using System;  
  public class FibonacciExample  
   {  
     public static void Main(string[] args)  
      {  
         int n1=0,n2=1,n3,i,number;    
         Console.Write("Enter the number of elements: ");    
         number = int.Parse(Console.ReadLine());  
         Console.Write(n1+" "+n2+" "); //printing 0 and 1    
         for(i=2;i<number;++i) //loop starts from 2 because 0 and 1 are already printed    
         {    
          n3=n1+n2;    
          Console.Write(n3+" ");    
          n1=n2;    
          n2=n3;    
         }    
      }  
   } 


calculate steps
public static class CalculateSteps
    {
        public static int CalculateTotalStrides(int[] flights, int stepsPerStride)
        {
            //1. You will be given the number of strpes in each fight in an integer[] flights.
            //2. you will be given an integer StairsPerStride 
             Validate(flights, stepsPerStride);
           
            int numberOfStrides = 0;
 
            //loop through each flight in
            foreach (int flight in flights)
            {
                //Get numbner of strides per each flight and add it to totasl
                numberOfStrides += (flight / stepsPerStride);
 
                //check for remiander and add one if any remaining for extra stride
                if (flight % stepsPerStride != 0)
                {
                    numberOfStrides++;
                }
            }
            //add on the 2 steps for the landing for each floor
            var totalStrides = (numberOfStrides + (flights.Length - 1) * 2);
            return totalStrides;
        }
 
        private static void Validate(int[] stairs, int stride)
        {
 
            //Rule 1: staircase is between 1 and 50 stairs inclusive
            if (stairs.Length < 1 || stairs.Length > 50)
            {
                throw new ArgumentOutOfRangeException("flights are out of range.");
            }
            //rule 2: flight of stairs between 5 and 30 steps
            if (stairs.Any(nextFlight => nextFlight < 5 || nextFlight > 30))
            {
                throw new ArgumentOutOfRangeException("Stairs are out of range.");
            }
            // rule 3: stepsPerStride is between 2 and 5
            if (stride >= 2 && stride <= 5)
                throw new ArgumentOutOfRangeException("Stride is out of range.");
        }


call run up stairs


//Run Up the stairs 
           int[] flights = new int[7];
           flights[0] = 5;
           flights[1] = 11;
           flights[2] = 9;
           flights[3] = 13;
           flights[4] = 8;
           flights[5] = 30;
           flights[6] = 14;
           var result = CalculateSteps.CalculateTotalStrides(flights, 3);
 
          Console.Write(result);
           Console.ReadLine();

unit tests 

[TestMethod]
public void CalculateTotalStrides_StaircaseIsValid_Max50()
{
    int[] flights = new int[0];
 
    // Act
    var actual = CalculateSteps.CalculateTotalStrides(flights, 3);
 
    // Assert
    var expected = "flights are out of range.";
    Assert.AreEqual(expected, actual);
}
 
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void CalculateTotalStrides_StaircaseIsValid_Min1()
{
 
    // Arrange
    //min amount of staircases is 1
    int[] flights = new int[51];
 
    // Act
    var actual = CalculateSteps.CalculateTotalStrides(flights, 3);
 
    // Assert
   var expected = "flights are out of range.";
   Assert.AreEqual(expected, actual);
}

Adding

///Adding this , adding that
            var first = new byte[] { 1, 1, 255 };
            var sec = new byte[] { 0, 0, 1 };
            var result = AddingThisAddingThat.AddRecursive(first, sec);
 
            Console.Write(result);
            Console.ReadLine();


public static byte[] AddRecursive(byte[] a, byte[] b)
        {
            //#1
            //byte[] ret = new byte[first.Length + second.Length];
            //Buffer.BlockCopy(first, 0, ret, 0, first.Length);
            //Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
            //return ret;
 
            //#2
            //List<byte> list1 = new List<byte>(first);
            //List<byte> list2 = new List<byte>(second);
            //list1.AddRange(list2);
            //byte[] sum2 = list1.ToArray();
            //return sum2;
 
            //#3
            if (a.Length == 0) return new byte[] { };
 
            return
                new byte[] { (byte)(a[0] + b[0]) }.Concat(
                AddRecursive(a.Skip(1).ToArray(), b.Skip(1).ToArray())
                ).ToArray();
        }

[TestClass]
  public class AddingThisAddingThat_Test
  {
      [TestMethod]
 
     public void Add_UsingARecursiveAlgorithm_ValuesAreAdded()
        {
            //First Test
            byte[] expectedResult = AddingThisAddingThat.AddRecursive(new byte[] { 1, 1, 1 }, new byte[] { 1, 1, 1 }).Reverse().ToArray();
            Assert.AreEqual(expectedResult, new byte[] { 2, 2, 2 });
            //Sec Test
            expectedResult = AddingThisAddingThat.AddRecursive(new byte[] { 1, 1, 255 }, new byte[] { 0, 0, 1 }).Reverse().ToArray();
            Assert.AreEqual(expectedResult, new byte[] { 1, 1, 0 });
            //Third Test
            expectedResult = AddingThisAddingThat.AddRecursive(new byte[] { 255, 255, 255 }, new byte[] { 255, 255, 255 }).Reverse().ToArray();
            Assert.AreEqual(expectedResult, new byte[] { 255, 255, 254 });
        }
  }

More sample unit tests 

[TestMethod] public void Withdraw_ValidAmount_ChangesBalance() { // arrange double currentBalance = 10.0; double withdrawal = 1.0; double expected = 9.0; var account = new CheckingAccount("JohnDoe", currentBalance); // act account.Withdraw(withdrawal); double actual = account.Balance; // assert Assert.AreEqual(expected, actual); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void Withdraw_AmountMoreThanBalance_Throws() { // arrange var account = new CheckingAccount("John Doe", 10.0); // act account.Withdraw(20.0); // assert is handled by the ExpectedException }


Refactor the code under test

First, define two constants for the error messages at class scope. Put these in the class under test, BankAccount:

public const string DebitAmountExceedsBalanceMessage = "Debit amount exceeds balance";
public const string DebitAmountLessThanZeroMessage = "Debit amount is less than zero";

Then, modify the two conditional statements in the Debit method:

if (amount > m_balance)
    {
        throw new ArgumentOutOfRangeException("amount", amount, DebitAmountExceedsBalanceMessage);
    }

    if (amount < 0)
    {
        throw new ArgumentOutOfRangeException("amount", amount, DebitAmountLessThanZeroMessage);
    }

or

[[TestMethod]
public void Debit_WhenAmountIsMoreThanBalance_ShouldThrowArgumentOutOfRange()
{
    // Arrange
    double beginningBalance = 11.99;
    double debitAmount = 20.0;
    BankAccount account = new BankAccount("Mr. Bryan Walton", beginningBalance);

    // Act
    try
    {
        account.Debit(debitAmount);
    }
    catch (ArgumentOutOfRangeException e)
    {
        // Assert
        StringAssert.Contains(e.Message, BankAccount.DebitAmountExceedsBalanceMessage);
        return;
    }

    Assert.Fail("The expected exception was not thrown.");
}
Links to resources
https://www.c-sharpcorner.com/UploadFile/dacca2/fundamental-of-unit-testing-understand-mock-object-in-unit/

https://docs.microsoft.com/en-us/visualstudio/test/quick-start-test-driven-development-with-test-explorer?view=vs-2019

http://www.srimanjavagroup.com/thread/java-se-faq-8217-s-and-interview-questions-java-se/5273/interview-questions-state-street-corporation.htm

https://www.javatpoint.com/fibonacci-series-in-csharp

https://www.javatpoint.com/wcf-interview-questions

https://www.csharpstar.com/csharp-program-to-reverse-a-number-check-if-it-is-a-palindrome/
https://www.geeksforgeeks.org/count-set-bits-in-an-integer/

Delegate
Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.
An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.
That works well in most situations. Sometimes, however, we don't want to call a function directly - we'd like to be able to pass it to somebody else so that they can call it. This is especially useful in an event-driven system such as a graphical user interface, when I want some code to be executed when the user clicks on a button, or when I want to log some information but can't specify how it is logged.
By defining a delegate, you are saying to the user of your class "Please feel free to put any method that match this signature here and it will be called each time my delegate is called".
Lambda

A delegate will allow us to specify what the function we'll be calling looks like without having to specify which function to call

A delegate is a reference to a method. Whereas objects can easily be sent as parameters into methods, constructor or whatever, methods are a bit more tricky. But every once in a while you might feel the need to send a method as a parameter to another method, and that's when you'll need delegates.


A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions.
To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side. For example, the lambda expression x => x * x specifies a parameter that’s named x and returns the value of x squared. You can assign this expression to a delegate type,