Blogger Widgets
  • Sharing Photos using SignalR
  • TFS Extenstion - allows copy work items between projects
  • Displaying jquery progressbar with ajax call on a modal dialog
  • Managing windows services of a server via a website
  • Exploring technologies available to date. TechCipher is one place that any professional would like to visit, either to get an overview or to have better understanding.

Search This Blog

Wednesday 25 September 2013

Using ASP.NET Web API for streaming pictures

ASP.NET Web API 2.0 provides various new features and one of which is Attribute Routing. Attribute routing allows custom configuration for routing by assigning attribute to the web method.

Get latest version of ASP.NET Web API 2.0 via Nuget package
Install-Package Microsoft.AspNet.WebApi.WebHost
Update WebApiConfig to include config.MapHttpAttributeRoutes()
 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
The [HttpGet] attribute defines an HTTP GET method. Now create RESTful endpoint using web api
[HttpGet("api/invoice/scan/{id}")]
public HttpResponseMessage GetScannedInvoiceById(string id)
{
 HttpResponseMessage result = new HttpResponseMessage();
 string isPath = GetInoviceScanPath(id);
        result.Content = new StreamContent(new FileStream(isPath, FileMode.Open));
 result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
 return result;
}
http://localhost/csharptechies/api/invoice/scan/1908765 will now get the image as HttpResponseMessage.

Apart from using attributes to define an uri for controller methods, Route Prefixes can be defined as a controller attribute that will become base uri for for all of the controller methods.

Do you realize if it weren't for Edison we'd be watching TV by candlelight.
Al Boliska

Saturday 21 September 2013

Server Side MVC vs Client Side MVC

MVC (Model–view–controller) is an architecture patterns that addresses separation of concerns, test driven development, statelessness, extensibility, SEO, REST and many more. Choosing MVC pattern for developing web application is a very easy decision, but that is just the beginning. Rest of decision is deciding how to design, develop and implement the web application.Now deciding on "Server Side MVC" or "Client Side MVC" is not any easy job as there are number of options available.

Server Side MVC

Overview

Server side MVC is a combination of server-side framework and javascript/jquery. There are various server-side framework's available depending on the platform you are developing. Here is a list of few of them

Why

Various benefits of using Server Side MVC are
  • Mature (been there for year)
  • Routing decided by Server
  • Server renders the views
  • Server binds model to views
  • View request can return html, json, xml, text, binary etc
  • CRUD managed by Controller & Data Models on Server
  • Code security
  • Routing decided on application start
  • Supports multi-page application

Client Side MVC

Overview

Client Side MVC is a combination of js frameworks and REST API. Partially still relies on server side application for providing REST API. There are various client-side framework's available depending on your choice of coding style. Here is a list of few of them

Why

  • Recently introduced but got more attention now (look at the list of examples where backbone.js is used
  • Routing decided by Client
  • Client renders the views
  • Client binds model to views via javascript frameworks
  • Uses REST API for getting data from server
  • CRUD managed by Controller & Data Models on Client via REST API
  • Started with single-page application, but now various frameworks support multi-page application
  • Routing can be modified dynamically as it is maintained on client


Look at TODO MVC for more options on Client Side MVC.

Also you could use mixture of both Server Side MVC and Client Side MVC. I have used this combination ASP.NET MVC + KnockoutJS on Techcipher.

Think? Why think! We have computers to do that for us.
Jean Rostand

Sunday 15 September 2013

Streaming millions of rows as a csv in ASP.NET MVC

Generating reports using the data from the database is something any project will generally have, but to be able to actually download all of the data as a csv is not easy. Not just thousands of rows but if database has millions of rows then challange will be to decide best approach. Consider following approaches

1. Generate the report on server and then stream the file to clients machine

2. Stream data in batches onto client machine

First approach is not a good idea as there is no feedback to the user when download will actually start, but with second option user will actually see the streaming immediately.

So let's look at option 2 and how that can be achieved

1. Define a custom result that derives from FileResult
public class CsvResult : FileResult
{
   protected override void WriteFile(HttpResponseBase response)
   {
            response.Clear();
            response.ClearContent();
            response.BufferOutput = false;
            var streamWriter = new StreamWriter(response.OutputStream, Encoding.UTF8);
            //write the header line first
            streamWriter.WriteLine("InvoiceDate,InvoiceNumber,Quantity,Price");
            long count = GetInvoiceRecCount();
            
            long batchSize = 10000;
            long numberOfBatches = count / batchSize;
            long startRow = 0;
            for (int i = 0; i < numberOfBatches; i++)
            {
                startRow = i * batchSize;
                //Get batch of rows
                var invoiceRows = GetInvoiceRows(startRow, batchSize);
                foreach(DataRow row in invoiceRows)
                {
                    //write data 
                    streamWriter.WriteLine(dataLine);
                }

                streamWriter.Flush();
            }

            if (startRow + batchSize < count)
            {
                batchSize = count - startRow;
                //Get batch of rows
                var invoiceRows = GetInvoiceRows(startRow, batchSize);
                //write final batch
                foreach (DataRow row in invoiceRows)
                {
                    //write data 
                    streamWriter.WriteLine(dataLine);
                }

                streamWriter.Flush();
            }
   }

}
2. Now write controller action
public ActionResult ExportInvoicesToCsv()
{
   CsvResult csvResult = new CsvResult();
   csvResult.FileDownloadName = "InvoiceReport.csv";
   return csvResult;
}
And that's it all done. Now when user tries to download millions of rows as csv they are batches in the size of 10000 and will be streamed to users machine.

Technology is just a tool. In terms of getting the kids working together and motivating them, the teacher is the most important.
Bill Gates
Copyright © 2013 Template Doctor . Designed by Malith Madushanka - Cool Blogger Tutorials | Code by CBT | Images by by HQ Wallpapers