European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET MVC Hosting - HostForLIFE.eu :: Custom Model Binders in ASP.NET MVC

clock December 22, 2016 06:31 by author Scott

In ASP.NET MVC, our system is built such that the interactions with the user are handled through Actions on our Controllers. We select our actions based on the route the user is using, which is a fancy way of saying that we base it on a pattern found in the URL they’re using. If we were on a page editing an object and we clicked the save button we would be sending the data to a URL somewhat like this one.

Notice that in our route that we have specified the name of the object that we’re trying to save. There is a default Model Binder for this in MVC that will take the form data that we’re sending and bind it to a CLR objects for us to use in our action. The standard Edit action on a controller looks like this.

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
    try
    {
        // TODO: Add update logic here
 
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

If we were to flesh some of this out the way it’s set up here, we would have code that looked a bit like this.

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
    try
    {
        Profile profile = _profileRepository.GetProfileById(id);

        profile.FavoriteColor = collection["favorite_color"];
        profile.FavoriteBoardGame = collection["FavoriteBoardGame"];

        _profileRepository.Add(profile);

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

What is bad about this is that we are accessing the FormCollection object which is messy and brittle. Once we start testing this code it means that we are going to be repeating code similar to this elsewhere. In our tests we will need to create objects using these magic strings. What this means is that we are now making our code brittle. If we change the string that is required for this we will have to go through our code correcting them. We will also have to find them in our tests or our tests will fail. This is bad. What we should do instead is have these only appear on one place, our model binder. Then all the code we test is using CLR objects that get compile-time checking. To create our Custom Model Binder this is all we need to do is write some code like this.

public class ProfileModelBinder : IModelBinder
{
    ProfileRepository _profileRepository = new ProfileRepository();

    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        int id = (int)controllerContext.RouteData.Values["Id"];
        Profile profile = _profileRepository.GetProfileById(id);

        profile.FavoriteColor = bindingContext
            .ValueProvider
            .GetValue("favorite_color")
            .ToString();


        profile.FavoriteBoardGame = bindingContext
            .ValueProvider
            .GetValue("FavoriteBoardGame")
            .ToString();

        return profile;
    }
}

Notice that we are using the form collection here, but it is limited to this one location. When we test we will just have to pass in the Profile object to our action, which means that we don’t have to worry about these magic strings as much, and we’re also not getting into the situation where our code becomes so brittle that our tests inhibit change. The last thing we need to do is tell MVC that when it is supposed to create a Profile object that it is supposed to use this model binder. To do this, we just need to Add our binder to the collection of binders in the Application_Start method of our GLobal.ascx.cs file. It’s done like this. We say that this binder is for objects of type Profile and give it a binder to use.

ModelBinders.Binders.Add(typeof (Profile), new ProfileModelBinder());

Now we have a model binder that should let us keep the messy code out of our controllers. Now our controller action looks like this.

[HttpPost]
public ActionResult Edit(Profile profile)
{
    try
    {
        _profileRepository.Add(profile);

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

That looks a lot cleaner to me, and if there were other things I needed to do during that action, I could do them without all of the ugly binding logic.

 



European ASP.NET MVC Hosting - Greece :: How to Remove IIS Header Bloat in ASP.NET MVC

clock June 26, 2014 09:30 by author Scott

Hi All, how do you do? In this post I will share little bit about how to remove IIS Header Bloat on IIS. This is default ASP.NET project’s response to a request for a page:

Cache-Control:private

Content-Encoding:gzip

Content-Length:3256

Content-Type:text/html; charset=utf-8

Date:Thu, 26 Jun 2014 09:07:59 GMT

Server:Microsoft-IIS/8.0

Vary:Accept-Encoding

X-AspNet-Version:4.0.30319

X-AspNetMvc-Version:4.0

X-Powered-By:ASP.NET

The first thing you need to do is remove X-AspNetMvc-Version header. How? Please just open your Global.asax.cs file to Application_Start, and add this code at the top

MvcHandler.DisableMvcResponseHeader = true;

Then, you can also eliminate the “Server” header by adding a handler to PreSendRequestHeaders event like this:

        protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            if (app != null &&
                app.Context != null)
            {
                app.Context.Response.Headers.Remove("Server");
            }
        }

Then, remove the “X-AspNet-Version" header by adding a config key to Web.Config. Here is the key to add (under <system.web>):

    <httpRuntime enableVersionHeader="false" />

The last is remove the X-Powered-By by adding another confing key to Web.Config (under<system.webserver>):

    <httpProtocol>

      <customHeaders>

        <remove name="X-Powered-By" />

      </customHeaders>

    </httpProtocol>

After doing all of this, we end up with a nice and clean response:

Cache-Control:private

Content-Encoding:gzip

Content-Length:3256

Content-Type:text/html; charset=utf-8
Date:Wed, 26 Jun 2014 09:17:09 GMTServer:Microsoft-IIS/8.0

Vary:Accept-Encoding



FREE Trial Cloud ASP.NET MVC Hosting - France :: Creating PDF Report Using ITextPDF in ASP.NET MVC Project

clock May 28, 2014 09:24 by author Scott

In this blog you will see how easy it is to build a report in an ASP.Net MVC application using a free IText PDF libraries.  By the way,  this project is still ASP.Net Webforms MVC 2, if you are already using Razor don’t just cut and paste the sample code, just get the jest and re-write it to suite to your project.

The first step is to add the libraries in your Visual Studio 2013 project by simply using the Manage NuGet Packages.

Once the libraries are installed, just create a controller.  In my example, I named my controller SysReport because I want it to be a generic report controller for all my reporting needs.  The code contains one GET method and a bunch of private methods that returns a PDF MemoryStream created by ITextPDF.

using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http; 

namespace wfmis.Controllers
{
    public class SysReportController : ApiController
    {
        public HttpResponseMessage Get()
        {
            NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query);
            string Report = nvc["Report"].ToString();
            Int64 Id = Convert.ToInt64(nvc["Id"]);
            var response = new HttpResponseMessage(HttpStatusCode.OK); 

            switch (Report)
            {
                case "PurchaseOrder":
                    response.Content = new StreamContent(this.PurchaseOrder(Id));
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

                    break;
                case "PurchaseInvoice":
                    response.Content = new StreamContent(this.PurchaseInvoice(Id));
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                    break;
                case "Disbursement":
                    response.Content = new StreamContent(this.Disbursement(Id));
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                    break;
                case "SalesOrder":
                    response.Content = new StreamContent(this.SalesOrder(Id));
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                    break;
                case "SalesInvoice":
                    response.Content = new StreamContent(this.SalesInvoice(Id));
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                    break;
                case "Collection":
                    response.Content = new StreamContent(this.Collection(Id));
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                    break;
                case "JournalVoucher":
                    response.Content = new StreamContent(this.JournalVoucher(Id));
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                    break;
                case "StockIn":
                    response.Content = new StreamContent(this.StockIn(Id));
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                    break;
                case "StockOut":
                    response.Content = new StreamContent(this.StockOut(Id));
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                    break;
                case "StockTransfer":
                    response.Content = new StreamContent(this.StockTransfer(Id));
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                    break;
            } 

            return response;
        }
    }
}

The second part of the controller is the method that creates the report itself.  Noticed that in the above code I highlighted two lines, the first line, calls the method that creates the byte stream while the second line informs the controller what is the content type, those are the methods.  I cannot paste the entire code that contains all the methods because it will take a lot of typing space, what I can paste is just one sample method, PurchaseInvoice.

private MemoryStream PurchaseInvoice(Int64 Id)
{
    var doc = new Document(PageSize.LETTER, 50, 50, 25, 25);
    var stream = new MemoryStream(); 

    try
    {
        BaseFont BaseFontTimesRoman = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
        Font TitleFont = new Font(BaseFontTimesRoman, 18, Font.BOLD);
        Font SubTitleFont = new Font(BaseFontTimesRoman, 14, Font.BOLD);
        Font TableHeaderFont = new Font(BaseFontTimesRoman, 10, Font.BOLD);
        Font BodyFont = new Font(BaseFontTimesRoman, 10, Font.NORMAL);
        Font EndingMessageFont = new Font(BaseFontTimesRoman, 10, Font.ITALIC); 

        PdfWriter writer = PdfWriter.GetInstance(doc, stream); 

        writer.PageEvent = new PDFHeaderFooter("Purchase Invoice"); 

        var PurchaseInvoices = from d in db.TrnPurchaseInvoices where d.Id == Id select d; 

        doc.Open(); 

        var HeaderTable = new PdfPTable(2);
        HeaderTable.HorizontalAlignment = 0;
        HeaderTable.SpacingBefore = 20;
        HeaderTable.SpacingAfter = 10;
        HeaderTable.DefaultCell.Border = 0;
        HeaderTable.SetWidths(new int[] { 2, 6 }); 

        HeaderTable.AddCell(new Phrase("PI Number:", TableHeaderFont));
        HeaderTable.AddCell(new Phrase(PurchaseInvoices.First().PINumber, BodyFont));
        HeaderTable.AddCell(new Phrase("PI Date:", TableHeaderFont));
        HeaderTable.AddCell(new Phrase(PurchaseInvoices.First().PIDate.ToShortDateString(), BodyFont));
        HeaderTable.AddCell(new Phrase("Supplier:", TableHeaderFont));
        HeaderTable.AddCell(new Phrase(PurchaseInvoices.First().MstArticle.Article, BodyFont));
        HeaderTable.AddCell(new Phrase("Term:", TableHeaderFont));
        HeaderTable.AddCell(new Phrase(PurchaseInvoices.First().MstTerm.Term, BodyFont));
        HeaderTable.AddCell(new Phrase("Document Reference:", TableHeaderFont));
        HeaderTable.AddCell(new Phrase(PurchaseInvoices.First().DocumentReference, BodyFont)); 

        doc.Add(HeaderTable); 

        var DetailTable = new PdfPTable(7);
        DetailTable.HorizontalAlignment = 0;
        DetailTable.SpacingAfter = 10;
        DetailTable.DefaultCell.Border = 0;
        DetailTable.SetWidths(new int[] { 2, 2, 6, 3, 3, 3, 3 });
        DetailTable.WidthPercentage = 100;
        DetailTable.DefaultCell.Border = Rectangle.BOX; 

        DetailTable.AddCell(CreateCenterAlignedCell("Qty", TableHeaderFont, 1));
        DetailTable.AddCell(CreateCenterAlignedCell("Unit", TableHeaderFont, 1));
        DetailTable.AddCell(CreateCenterAlignedCell("Item", TableHeaderFont, 1));
        DetailTable.AddCell(CreateCenterAlignedCell("Particulars", TableHeaderFont, 1));
        DetailTable.AddCell(CreateCenterAlignedCell("Cost", TableHeaderFont, 1));
        DetailTable.AddCell(CreateCenterAlignedCell("Tax", TableHeaderFont, 1));
        DetailTable.AddCell(CreateCenterAlignedCell("Amount", TableHeaderFont, 1)); 

        decimal TotalAmount = 0;
        if (PurchaseInvoices.First().TrnPurchaseInvoiceLines.Any())
        {
            foreach (var Line in PurchaseInvoices.First().TrnPurchaseInvoiceLines)
            {
                DetailTable.AddCell(CreateRightAlignedCell(Line.Quantity.ToString("#,##0.#0"), BodyFont,1));
                DetailTable.AddCell(new Phrase(Line.MstUnit.Unit, BodyFont));
                DetailTable.AddCell(new Phrase(Line.MstArticle.Article, BodyFont));
                DetailTable.AddCell(new Phrase(Line.Particulars, BodyFont));
                DetailTable.AddCell(CreateRightAlignedCell(Line.Cost.ToString("#,##0.#0"), BodyFont,1));
                DetailTable.AddCell(new Phrase(Line.MstTax.TaxCode, BodyFont));
                DetailTable.AddCell(CreateRightAlignedCell(Line.Amount.ToString("#,##0.#0"), BodyFont,1)); 

                TotalAmount = TotalAmount + Line.Amount;
            }
        } 

        DetailTable.AddCell(CreateCenterAlignedCell("TOTAL", TableHeaderFont, 6));
        DetailTable.AddCell(CreateRightAlignedCell(TotalAmount.ToString("#,##0.#0"), TableHeaderFont, 1)); 

        doc.Add(DetailTable); 

        var SignatureTable = new PdfPTable(3);
        SignatureTable.HorizontalAlignment = 0;
        SignatureTable.SpacingBefore = 10;
        SignatureTable.SpacingAfter = 10;
        SignatureTable.SetWidths(new int[] { 6, 6, 6 });
        SignatureTable.WidthPercentage = 100;
        SignatureTable.DefaultCell.Border = Rectangle.BOX; 

        SignatureTable.AddCell(CreateLeftAlignedCell("Prepared By:", TableHeaderFont, 1));
        SignatureTable.AddCell(CreateLeftAlignedCell("Checked By: ", TableHeaderFont, 1));
        SignatureTable.AddCell(CreateLeftAlignedCell("Approved By:", TableHeaderFont, 1)); 

        PdfPCell cell1 = new PdfPCell(new Phrase(PurchaseInvoices.First().MstUser.FullName, BodyFont)) { HorizontalAlignment = PdfPCell.ALIGN_CENTER, VerticalAlignment = PdfPCell.ALIGN_BOTTOM };
        PdfPCell cell2 = new PdfPCell(new Phrase(PurchaseInvoices.First().MstUser1.FullName, BodyFont)) { HorizontalAlignment = PdfPCell.ALIGN_CENTER, VerticalAlignment = PdfPCell.ALIGN_BOTTOM };
        PdfPCell cell3 = new PdfPCell(new Phrase(PurchaseInvoices.First().MstUser2.FullName, BodyFont)) { HorizontalAlignment = PdfPCell.ALIGN_CENTER, VerticalAlignment = PdfPCell.ALIGN_BOTTOM }; 

        cell1.FixedHeight = 50f;
        cell2.FixedHeight = 50f;
        cell3.FixedHeight = 50f; 

        SignatureTable.AddCell(cell1);
        SignatureTable.AddCell(cell2);
        SignatureTable.AddCell(cell3); 

        doc.Add(SignatureTable); 

        doc.Close();
    }
    catch { } 

    byte[] file = stream.ToArray();
    MemoryStream output = new MemoryStream();
    output.Write(file, 0, file.Length);
    output.Position = 0; 

    return output;
}

Now it may look gruesome at first, because it is 100% hardcore code to create a report, but once you start writing it down you will get a familiarity of the ITextPDF libraries, which is very powerful and customizable, the code will be clearer and understandable.  I hightlighted a single line above because this line is optional, it is just merely overloading the PdfPageEventHelper class to create a header and footer of the report.  I will discuss this soon in my future blogs.

In order also to fully understand the code, below is the sample actual output report created by the code.

And the last step is to call the controller in your views, it turns out, it is very simple as shown in the sample Javascript code below.

function cmdPrint_onclick()
   {
      if ($Id &gt; 0)
      {
         window.location.href = '/api/SysReport?Report=PurchaseInvoice?Id=' + $Id;
      }
}

Hope this blog helpful.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in