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.



European Cloud ASP.NET MVC Hosting - Spain :: Pipeline in ASP.NET MVC

clock April 22, 2014 09:49 by author Scott

In this article, I will write simple tutorial about detail pipeline of ASP.NET MVC.

Routing

Routing is the first step in ASP.NET MVC pipeline. typically, it is a pattern matching system that matches the incoming request to the registered URL patterns in the Route Table.

The UrlRoutingModule(System.Web.Routing.UrlRoutingModule) is a class which matches an incoming HTTP request to a registered route pattern in the RouteTable(System.Web.Routing.RouteTable).

When ASP.NET MVC application starts at first time, it registers one or more patterns to the RouteTable to tell the routing system what to do with any requests that match these patterns. An application has only one RouteTable and this is setup in the Application_Start event of Global.asax of the application.

public class RouteConfig
   {
   public static void RegisterRoutes(RouteCollection routes)
   {
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

   routes.MapRoute(
   name: "Default",
   url: "{controller}/{action}/{id}",
   defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
   );
   }
   }


protected void Application_Start()
{
   //Other code is removed for clarity
   RouteConfig.RegisterRoutes(RouteTable.Routes);
}

When the UrlRoutingModule finds a matching route within RouteCollection (RouteTable.Routes), it retrieves the IRouteHandler(System.Web.Mvc.IRouteHandler) instance(default is System.Web.MvcRouteHandler) for that route. From the route handler, the module gets an IHttpHandler(System.Web.IHttpHandler) instance(default is System.Web.MvcHandler).

public interface IrouteHandler
{
   IHttpHandler GetHttpHandler(RequestContext requestContext);
}

Controller Initialization

The MvcHandler initiates the real processing inside ASP.NET MVC pipeline by using ProcessRequest method. This method uses the IControllerFactory instance (default is System.Web.Mvc.DefaultControllerFactory) to create corresponding controller.

protected internal virtual void ProcessRequest(HttpContextBase httpContext)
{
   SecurityUtil.ProcessInApplicationTrust(delegate {
   IController controller;
   IControllerFactory factory;
   this.ProcessRequestInit(httpContext, out controller, out factory);
   try
   {
   controller.Execute(this.RequestContext);
   }
   finally
   {
   factory.ReleaseController(controller);
   }
   });
}

Action Execution

1. When the controller is initialized, the controller calls its own InvokeAction() method by passing the details of the chosen action method. This is handled by the IActionInvoker.

public virtual bool InvokeAction(ControllerContext controllerContext, string actionName)

2. After chosen of appropriate action method, model binders(default is System.Web.Mvc.DefaultModelBinder) retrieves the data from incoming HTTP request and do the data type conversion, data validation such as required or date format etc. and also take care of input values mapping to that action method parameters.

3. Authentication Filter was introduced with ASP.NET MVC5 that run prior to authorization filter. It is used to authenticate a user. Authentication filter process user credentials in the request and provide a corresponding principal. Prior to ASP.NET MVC5, you use authorization filter for authentication and authorization to a user.

By default, Authenticate attribute is used to perform Authentication. You can easily create your own custom authentication filter by implementing IAuthenticationFilter.

4. Authorization filter allow you to perform authorization process for an authenticated user. For example, Role based authorization for users to access resources.

By default, Authorize attribute is used to perform authorization. You can also make your own custom authorization filter by implementing IAuthorizationFilter.

5. Action filters are executed before(OnActionExecuting) and after(OnActionExecuted) an action is executed. IActionFilter interface provides you two methods OnActionExecuting and OnActionExecuted methods which will be executed before and after an action gets executed respectively. You can also make your own custom ActionFilters filter by implementing IActionFilter.

6. When action is executed, it process the user inputs with the help of model (Business Model or Data Model) and prepare Action Result.

Result Execution

1. Result filters are executed before(OnResultnExecuting) and after(OnResultExecuted) the ActionResult is executed. IResultFilter interface provides you two methods OnResultExecuting and OnResultExecuted methods which will be executed before and after an ActionResult gets executed respectively. You can also make your own custom ResultFilters filter by implementing IResultFilter.

2. Action Result is prepared by performing operations on user inputs with the help of BAL or DAL. The Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and EmptyResult.

3. Various Result type provided by the ASP.NET MVC can be categorized into two category- ViewResult type and NonViewResult type. The Result type which renders and returns an HTML page to the browser, falls into ViewResult category and other result type which returns only data either in text format, binary format or a JSON format, falls into NonViewResult category.

View Initialization and Rendering

1. ViewResult type i.e. view and partial view are represented by IView(System.Web.Mvc.IView) interface and rendered by the appropriate View Engine.

public interface Iview
{
  
void Render(ViewContext viewContext, TextWriter writer);
}

2. This process is handled by IViewEngine(System.Web.Mvc.IViewEngine) interface of the view engine. By default ASP.NET MVC provides WebForm and Razor view engines. You can also create your custom engine by using IViewEngine interface and can registered your custom view engine in to your Asp.Net MVC application as shown below:

protected void Application_Start()
{
  
//Remove All View Engine including Webform and Razor
   ViewEngines.Engines.Clear();
   //Register Your Custom View Engine
   ViewEngines.Engines.Add(new CustomViewEngine());
   //Other code is removed for clarity
}

3. Html Helpers are used to write input fields, create links based on the routes, AJAX-enabled forms, links and much more. Html Helpers are extension methods of the HtmlHelper class and can be further extended very easily. In more complex scenario, it might render a form with client side validation with the help of JavaScript or jQuery.



Free ASP.NET 5 MVC Belgium Hosting - HostForLIFE.eu :: Implementing Validation Mechanism in ASP.NET MVC

clock April 16, 2014 07:17 by author Peter

In this article I will walk you through the steps of implementing validation in the ASP.NET 5 MVC project using jquery.validate.unobtrusive.js

What is Unobtrusive JavaScript?

Unobtrusive JavaScript is the best practices to separate the JavaScript code from presentation or html.

For example
<input type=”button”
id=”btn”
onclick=”alert(‘hello world’)“
/>

The above code is obtrusive as we have called the JavaScript alert method within the html control’s input tag. In order to make this unobtrusive we can create a separate JavaScript file and with the help of jQuery we can register a click event for this button like this.

$(document).ready(function () {
$(‘#btn’).click(function (e) {
    alert(‘hello world’);
}
});

For validation there is a JavaScript named jquery.validate.unobtrusive.js which can automatically attach validation with all the input controls that you have in your html file. But those controls should have data-val attribute to true. Otherwise the validation for that particular control does not applied. By default, when we use these methods in our code, depending on the data annotation attributes we have used in our Model it automatically applies the validation at the time of rendering the html control.

For example. If our model is:

public
class
Person : Message
{
[GridColumn("Id", true)]
public
int Id { set; get; }
[Required]
[GridColumn("Name", false)]
[StringLength(10, ErrorMessage="Length cannot exceed to 10 character")]
public
string Name { set; get; }
}

In ASP.Net MVC we can associate a model while adding a view and in that view we can call HTML helper functions like this
@Html.EditorFor(model => model.Name)

This will generates an html as follows

<input data-val=”true” data-val-length=”Length cannot exceed to 10 character” data-val-length-max=”10″ data-val-required=”The Name field is required.” id=”Name” name=”Name” type=”text” value=”Ovais” />

1. You can see that depending on the model it has automatically added the data-val-* properties in the html. You have to add a jquery.validation.unobtrusive.js in your project.

2. Then add the file path in the bundle like this:

bundles.Add(new
ScriptBundle(“~/bundles/jqueryval”).Include(
“~/Scripts/jquery.validate*”)); 

3. Then add the script reference in the page as within the script section like this.

@section scripts{
@Scripts.Render(“~/bundles/jqueryval”)

}

4. Make sure you have controls place inside a form.

Handling validation in AJAX calls

When using server side post back in ASP.Net MVC validation works smooth. But for example if you want to invoke some AJAXified request on any button click and wanted to know if the form is validated or not you can add a code like this.

$(‘#Save’).click(function (e) {
var $val = $(this).parents(‘form’);
if (!($val.valid()))
return
false;
else alert(‘form have no errors’);

}



Europe FREE ASP.NET MVC 5 Hosting - UK :: ASP.NET MVC 5 Hosting with HostForLIFE.eu

clock April 11, 2014 08:17 by author Scott

ASP.NET MVC 5.0 Overview

What's Asp.net MVC 5.0? Asp.net MVC 5.0 is is the latest version of the popular ASP.NET MVC technology that enables you to build dynamic websites using the Model-View-Controller technology, with an emphasis on a clean architecture, test-driven development and extensibility.

What're the new features from Asp.net mvc 5.0?

The ASP.NET MVC 5 Framework is the latest update to Microsoft’s popular ASP.NET web platform. It provides an extensible, high-quality programming model that allows you to build dynamic, data-driven websites, focusing on a cleaner architecture and test-driven development.

ASP.NET MVC 5 contains a number of improvements over previous versions, including some new features, improved user experiences; native support for JavaScript libraries to build multi-platform CSS and HTML5 enabled sites and better tooling support.

Below are some of new ASP.NET MVC 5 feature:

  • Scaffolding
  • ASP.NET Identity 
  • One ASP.NET 
  • Bootstrap 
  • Attribute Routing 
  • Filter Overrides

Best ASP.NET MVC 5.0 hosting service

If you read over the asp.net official web pages you should have found the mvc 5.0 is still developer preview release but not final product. If you're web developers you can simply get it installed on local and take all the advantages, however you might find it hard to find a real hosting service for it. Why? Because reliability is final purpose for production server, most hosting providers would not take the risk using some beta version softwares because they need to be responsible to all clients. Any potential security hole may destroy the entire server. But, you don’t need to worry, HostForLIFE.eu will provide ASP.NET MVC 5 hosting on our shared hosting environment. You can test drive this new feature with only €3.00/month.

More about Asp.net MVC 5.0 Hosting with HostForLIFE.eu

Asp.net MVC 5.0 will be a simple support by all leading asp.net hosting providers as long as it's officially released. There's no special requirement to get MVC 5.0 working but just a simple installation on server end. However it doesn't mean every service will be as good as advertised. For best performance and security purpose, you should always host your mvc application with a reputable service where the hosting servers are setup with powerful hardware and windows OS(windows server 2008 R2 is minimum requirement). The hosting service must be easy to use with friendly hosting control panel. The crucial point is you can always view your website online so 99% uptime must be offered.

HostForLIFE.eu offering super cheap hosting solutions and leading hosting features, you get unlimited disk space and unlimited bandwith in same hosting account. You also get dedicated application pools per site and free domain name opportunity. With standard websitepanel you can manage website files/database/email accounts and all other asp.net website configurations without professional skills. HostForLIFE.eu is by far the best choice for cheap and reliable asp.net mvc 5 hosting.



HostForLIFE.eu Proudly Announces Microsoft SQL Server 2014 Hosting

clock April 7, 2014 11:09 by author Peter
HostForLIFE.eu was established to cater to an under served market in the hosting industry; web hosting for customers who want excellent service. HostForLIFE.eu a worldwide provider of hosting has announced the latest release of Microsoft's widely-used SQL relational database management system SQL Server Server 2014. You can take advantage of the powerful SQL Server Server 2014 technology in all Windows Shared Hosting, Windows Reseller Hosting and Windows Cloud Hosting Packages! In addition, SQL Server 2014 Hosting provides customers to build mission-critical applications and Big Data solutions using high-performance, in-memory technology across OLTP, data warehousing, business intelligence and analytics workloads without having to buy expensive add-ons or high-end appliances. 

SQL Server 2014 accelerates reliable, mission critical applications with a new in-memory OLTP engine that can deliver on average 10x, and up to 30x transactional performance gains. For Data Warehousing, the new updatable in-memory column store can query 100x faster than legacy solutions. The first new option is Microsoft SQL Server 2014 Hosting, which is available to customers from today. With the public release just last week of Microsoft’s latest version of their premier database product, HostForLIFE has been quick to respond with updated their shared server configurations.For more information about this new product, please visit http://hostforlife.eu/European-SQL-Server-2014-Hosting

About Us:
HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see http://www.microsoft.com/web/hosting/HostingProvider/Details/953). Our 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, we have also won several awards from reputable organizations in the hosting industry and the detail can be found on our official website.


Free UK ASP.NET MVC Hosting - HostForLIFE.eu :: Using Bower in ASP.NET

clock March 25, 2014 07:43 by author Peter

Today, I’d like to show you how you can use this awesome tool in ASP.NET MVC projects. First of all, unlike nuget bower runs on node, so if you haven’t installed it go and grab the installer from nodejs.org. After that, the installation is really easy—just type the following command.

npm install -g bower

Great, we have installed bower and now we need to configure our dependencies in the ASP.NET MVC project. For this purpose go to the project root (not the solution, but MVC project root) and create a file called .bowerrc, and in this file we are going to specify the directory where to put components.

{

"directory" : "Content/components"

}

You can place this file to your home folder and all your projects will use this configuration, but I prefer project specific settings. Next step is defining the dependencies with bower.json file. Put it in your project root folder as well.

{

  "name": "Bonobo Git Server",

  "dependencies": {

    "pure": "0.4.2",

    "font-awesome": "4.0.3"

}

}

This is my configuration file for Bonobo Git Server. At the moment, I use two libraries—Pure CSS framework and Font Awesome. Change them to the ones you wish to use in your project. There is a useful package explorer is on the bower homepage. Excellent, we have configured the dependencies and are ready to install them. Open a command prompt or PowerShell and navigate to the root of your MVC project and run the following command.

bower install

After that, all your dependencies will be installed under Content\components directory and there is one last thing you need to do to start use them in your project. You have to include them in your project file and for this we are going to use solution explorer inside Visual Studio. Firstly, turn on the option Show All Files.

Secondly, locate the Content\components folder and include it into your project. This can be done by right-clicking on the folder or file and clicking on Include In Project.

Personally, I include only the files I need, because lots of packages comes with chatty sources and other development stuff. For example, for Pure framework I include only the pure-min.css file. And that’s it. From now, you can use the libraries in your project.



ASP.NET MVC 5 Germany Hosting - HostForLIFE.eu :: Bundling and Minification

clock March 10, 2014 07:13 by author Peter

While this article may be very simple and straightforward, there are a few concepts here I think are important to note. In my next article will be looking more in depth on the idea of creating a customized Web.config, but for now with this article, I just want to look at activating the bundling and minification feature by using the xml tags inside a MVC's Web.config. This feature is only available in ASP.NET 4.5 and above.

The First Problem

With the following inside your Web.config.

<location>

    <system>

      <compilation debug="true" targetframework="4.5"></compilation>

    </system>

</location>

And with either of the following inside your build config or customized Web.config (I.E. Web.Release.config)

<system>

    <compilation xdt:transform="RemoveAttributes(debug)"></compilation>

</system>

This also can be achieved by doing the following

<system>

 <compilation debug="false" xdt:transform="SetAttributes(debug)">

 </compilation>

</system>

In both snippets of code you do not need to use the "xdt:Locator" attribute (used only in cases where there are multiples elements of the same name.  What you may not see is that in the Web.config we have the "location" tag wrapped around the "system" tag. This is important and something I missed when debugging the problem. So by wrapping my snippet of code with "location" tag this corrects the problem, and started up the bundling and minification in mvc. It is important to note that by default if the debug attribute is not specified it is false and will start up the bundling and minification.

The Second Problem

Now everything looks good, but wait the main css isn't working! Thanks to this feature there are warnings in the actually css or javascript files! They will appear as comments for example I saw the following:

/* Minification failed. Returning unminified contents.(1779,2): run-time error CSS1062: 
Expected semicolon or closing curly-brace, found ' '(1785,2): run-time error CSS1062: 
Expected semicolon or closing curly-brace, found ' '(1790,2): run-time error CSS1062: 
Expected semicolon or closing curly-brace, found ' ' */

The cause of this was actually a issue created by the repository's character notation and not being cleaned up before being checked in (Git uses '*' to note a change). The issue existed for a while but since most browser work around issue nothing appeared out of the order. I normally disable css warnings on chrome because it gets a little annoying but in this case it made me miss the issue (ops). Either way a good catch and now everything is working like it should. Remember to actually check your bundling and minification!



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