European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

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 > 0)
      {
         window.location.href = '/api/SysReport?Report=PurchaseInvoice?Id=' + $Id;
      }
}

Hope this blog helpful.



FREE Trial ASP.NET MVC 5.1.2 Hosting - Germany :: What's New in ASP.NET MVC 5.1.2?

clock May 21, 2014 08:02 by author Scott

Just check on Microsoft site and Microsoft has launched new ASP.NET MVC 5.1.2. Microsoft also announces the availability ASP.NET 4.5.2. Just check the preview of ASP.NET 4.5.2 here and Microsoft official site.

So, what’s new in ASP.NET MVC 5.1.2?

You can download the packages through NuGet. You can get the latest ASP.NET MVC 5.1.2 version. The release also includes corresponding localized packages on NuGet.

You can install or update to the released NuGet packages by using the NuGet Package Manager Console:

Install-Package Microsoft.AspNet.Mvc -Version 5.1.2

Interesting Feature in ASP.NET MVC 5.1.2:

Attribute routing improvements

Attribute routing now supports constraints, enabling versioning and header based route selection. Many aspects of attribute routes are now customizable via the IDirectRouteFactory interface and RouteFactoryAttribute class. The route prefix is now extensible via the IRoutePrefix interface and RoutePrefixAttribute class.

Enum support in views

1. New @Html.EnumDropDownListFor() helper methods.
2. New EnumHelper.GetSelectList() methods which return an IList<SelectListItem>.

If you want to see how to implement this new feature, please see the complete example here.

Bootstrap support for editor templates

ASP.NET MVC 5.1.2 allow passing in HTML attributes in EditorFor as an anonymous object.

Unobtrusive validation for MinLengthAttribute and MaxLengthAttribute

Client-side validation for string and array types will now be supported for properties decorated with the MinLength and MaxLength attributes.

Supporting the ‘this’ context in Unobtrusive Ajax

The callback functions (OnBegin, OnComplete, OnFailure, OnSuccess) will now be able to locate the invoking element via the this context.

Cheap hosting for ASP.NET MVC 5.1.2

If you want to try out this new feature of ASP.NET MVC 5.1.2, you can start your affordable ASP.NET MVC 5.1.2 hosting with us. We have also launches new packages which is more affordable and start from only €1.29/month. For more information about our hosting plan, please visit our official site at http://hostforlife.eu/ASPNET-Shared-European-Hosting-Plans.



HostForLIFE.eu offers €1.29/month Affordable and High Performance Windows & ASP.NET Shared Hosting Plan

clock May 20, 2014 11:53 by author Peter

European Windows and ASP.NET hosting specialist, HostForLIFE.eu, has officially launched the new Windows & ASP.NET Shared Hosting Plan offered from as low as €1.29/month only. This LITE Windows & ASP.NET Hosting packages combine generous or 1 website, 1 GB disk space, 10 GB bandwidth, Support UTF-8 Domains, Dedicated Pool, etc. As the market for hosted solutions continues to grow, the new hosting range is designed to exceed the growing technical demands of businesses and IT professionals.

HostForLIFE.eu  is confident that their new LITE shared hosting plans will surely appeal to the personal across the world, besides the website owners and companies owning websites. The new web hosting plans will meet the requirement of high performance web hosting where one can easily update the content of a website on a regular basis. This plan is designed more for the web hobbiest needing affordable, high availability, hosting and easy backend management of windows and ASP.NET with powerful Plesk control panel.

Every day thousands of people decide to set up a website for business or personal use. New business owners and the average consumer don’t always have access to unlimited budgets. HostForLIFE.eu understand the importance of reliable hosting but are not always prepared to pay the exorbitant prices that reliable hosts charge.

For additional information about LITE Shared Hosting Plan offered by HostForLIFE.eu, please visit http://hostforlife.eu

About HostForLIFE.eu:

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

HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see www.microsoft.com/web/hosting/HostingProvider/Details/953). Their service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, They have also won several awards from reputable organizations in the hosting industry and the detail can be found on their official website.



FREE ASP.NET MVC 5 Cloud Hosting Belgium - HostForLIFE.eu :: About DataAnnotations, MVC and LINQ To Entities

clock May 6, 2014 07:18 by author Peter

In this blog I will be covering some useful features called DataAnnotations which one can use when using LINQ To Entities, together with ASP.NET MVC 5 Hosting. The outcomes of this blog are

  1. Understand and learn how you can create DataAnnotations on your LINQ To Entities generated model
  2. Understand how these annotations link with MVC Views which are then used to modify database data
  3. Understand how validators are then utilized automatically by ASP.NET following the annotations you create

The prerequisites of this blog are

  1. Have some understanding of LINQ To Entities
  2. Have some understanding of MVC and how you can create records using ASP.NET MVC
  3. Have SQL Server Express installed and have a database containing a Products table.

Whenever you create an ASP.NET MVC Template Project using Visual Studio an AccountModel inside the Models folder will be automatically generated. If you open this class you will note that there are some very useful properties which ASP.NET MVC uses to validate data inputted by the user. Let’s take a simple example.

public class LoginModel
 {
 [Required]
 [Display(Name = "User name")]
 public string UserName { get; set; }
[Required]
 [DataType(DataType.Password)]
 [Display(Name = "Password")]
 public string Password { get; set; }
[Display(Name = "Remember me?")]
 public bool RememberMe { get; set; }
 }

If you examine the above code you will note that on some specific fields there are what so called DataAnnotations. These DataAnnotations are
Display (line 4,9 and 12)
DataType (line 8)
Required (line 3 and 7)

What are these DataAnnotations and why are they used? These DataAnnotations basically give MVC some extra information on what you expect from the user when inputting data in an MVC View. For example, the Required DataAnnotation basically ensures that the specific field cannot be left empty. That would mean that a user would not be allowed to leave the field empty when inputting data. Thus, in the example shown above, the Username and Password fields are both required.The Display DataAnnotation, on the other hand, is used so that the label associated with the field, when displayed in an ASP.NET MVC View, will display the relevant Display information.

The DataType DataAnnotation will provide information on the DataType of that specific field. So for example, the Password field is in our case a Password field. This means that whenever you will be creating a View which accepts a LoginModel class, the Password field will be displayed as an HTML Input Type = password field.

The example which the ASP.NET MVC template project is very useful to let use understand how DataAnnotations can be used. However, what happens when you are using LINQ To Entities and you would have your classes already specified in your model. How can you use these very useful DataAnnotations and apply them to your LINQ To Entities model?

Basically my main aim is not to create DataAnnotations and apply them on a LINQ To Entities model which we have created in this blog. Thus, from now on I will assume that you have a LINQ To Entities class named Product which basically stores products information.

The first thing you will have to do is to create a partial class with the same name as your LINQ To Entities class. So ,in our example we will name our partial class Product. We would then create another class which will contain the MetaData containing all the fields in our LINQ To Entities Product model which we would like to apply DataAnnotations on. This code is shown underneath.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
namespace MVCForBlog.Models
{
[MetadataType(typeof(ProductMetaData))]
 public partial class Product
 {
 }
public class ProductMetaData
 {
 [Required(ErrorMessage = "Product Name is required")]
 [Display(Name="Product Name")]
 [DataType( System.ComponentModel.DataAnnotations.DataType.Text)]
 public string ProductName { get; set; }
 [Required(ErrorMessage = "Product Description is required")]
 [DataType( System.ComponentModel.DataAnnotations.DataType.MultilineText)]
 [Display(Name = "Product Description")]
 public string ProductDescription { get; set; }
}
}

Before I go into the detail of what the above code does I will have to make some points very clear
To use DataAnnotations you should Add A Reference to the System.ComponentModel if this has not already been added
You should ensure that the partial class is in the SAME namespace as your LINQ To Entities model. THIS IS CRITICAL TO MAKE ANNOTATIONS WORK AS EXPECTED.
The fields you create in your class should have the SAME name as the field name specified in the LINQ To Entities model.

If you investigate the code listed you will note the following
From line 8 to line 11 we are creating a partial class with the same name as the class found in our LINQ To Entities model. We are then specifying that it will be using the MetaData created in a separate class named ProductMetaData

The ProductName field specified in line 17 has several data annotations applied. These include Required, which means that the user would not be able to leave the field empty, DisplayName which means that the field which will be displayed near the textbox will be shown as Product Name, and finally DataType which basically specifies what type of data the user should be inputting. In our case the ProductName is a string and thus we are specifying Text as the DataType.

The ProductDescription found in line 22, has the same DataAnnotations as in the previous field. However the DataType for this field is MultiLine text. Thus when this field will be displayed in an ASP.NET MVC View a TextArea will be shown.

Now let’s see how these annotations will affect the ASP.NET MVC View which will be used to create a new product to our database.

Create an ASP.NET MVC View which will create a new product to the database as shown in Figure 1. You will note that when you run your application and try to create a new product, the fields and GUI elements which will be created will reflect the DataAnnotations specified.



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in