Angular JS with ASP.NET MVC – Part 2

In the first part we just configured angular JS application in ASP.NET MVC. You may have noticed that we accessed the scope variables of DemoController using $ sign. This time we will use the $route variable to route and open different views in a single page container where ng-view will be defined.

$ is a prefix that could be a property, method, variable that part of the core of AngularJS. When naming services controllers etc. it is recommended to not use $ prefix with your custom object names to avoid conflicting issues.

In this exercise we will add routing module in the MyApp.js, configure routing statements and open the ASP.NET MVC views inside a div on a single page container.

  1. First of all add the Angular Route package from NuGet Manager.
  2. Add a reference using NuGet Package Manager and search angular js route. You will see the AngularJS Route package in the Manage NuGet Packages windows. Just add it.1
  3. Now in the MyApp add ngRoute module
  4. Add the Angular-route.min.js in the BundleConfig.cs file under App_Start folder
  5. 4
  6. Edit the MyApp.js file and add ngRoute as belo
  7. This tells the angular app to use the routing module.
  8. Let’s add three actions in HomeController namely Test1, Test2 and Test3
  9. Add views to these actions, Note: all view should be partial
  10. In order to add view, just right click the Test1 function and select Add View
  11. It opens up the window where you can specify the name Test1 and check on “Create as partial view”2
  12. Once added, do these steps for ou can specify the name Test1 and check on foldera div on a single page container. d confilcting rest two methods as well namely Test2 and Test3.
  13. Now, inorder to open these view from angular we have to add a routing.
  14. In the MainApp.js we can add a routing as below3
  15. After adding this, we need to add a div on our landing page. In last post, Home/Index was our landing page (that acts as a single page container)
  16. Now add a div with ng-view attribute on it. Angular automatically opens up the page on all the containers like div, body etc where the ng-view is defined on the landing page container.5
  17. Now add, these links that opens up the page inside div6
  18. You can put any content in the partial view
  19. Let’s build and run. Click on link1 and it opens up the page inside div where ng-view is defined.7
  20. Click on second link
  21. 8
  22. At last, Click on third link 9

This covers up our second part where we used the routing feature of Angular JS. In the next post we will create factories to access database using Web API and Entity Framework as data access persistence.

AngularJS in ASP.NET MVC – Part 1

This is the first part from the series of posts I have planned for AngularJS in which I will provide an in-depth knowledge about AngularJS and how to use that in developing business applications with ASP.NET MVC, WEB API and Entity framework

In this post we will discuss about the core features of AngularJS and bootstrap with ASP .NET MVC using Visual Studio. I assume that the readers should have an in depth knowledge of ASP.NET MVC and Web APIs as I would mostly focus on the AngularJS features.

What is AngularJS

AngularJS is a web framework developed by Google tp provide responsive UI on web. It is supported for Single Page Applications where the landing page remains the same and single or multiple view can render inside it with usage of server side functions asynchronously and updating the model and control values dynamically.

You can check out the complete tutorial over here https://angularjs.org

Step by Step exercise of configuring Angular JS in ASP.NET MVC application

  1. Start Visual Studio
  2. Select ASP.NET Web Application and then MVC as project template
  3. Add references to AngularJS through NuGet
  4. Search AngularJS on the Package Manager console
  5. And then Select AngularJS Core and install

11

6. After adding AngularJS Core, add the bundle

bundles.Add(new ScriptBundle(“~/bundles/angular”)

.Include(“~/Scripts/angular.js”));

7.  Now add these bundles in the HTML head section of _Layout.cshtml

@Scripts.Render(“~/bundles/angular”)

8. Now In order to bootstrap angular JS in our MVC app we have to define the ngApp on the page body or html tag. ngApp reference to the application JS file where you can define routing, controllers etc. ngApp is a directive to auto-bootstrap an AngularJS application. Also, note that only one ngApp can be used per HTML document.

9. Let’s create two JavaScript files, one MyApp.js and the other DemoController.js

10.  Create an app folder under root in MVC project

11. Add a new JavaScript file named as MyApp.js

12. Inside MyApp.js write following snippet

var MyApp = angular.module(‘MyApp’,[]);

13. This line initialize the application level global object of angular app and a central point where you can add modules like routing, ui etc. Through this object you can add controllers, directives etc and access it globally.

14. Now specify “MyApp” to the ng-App attribute in html tag.

<html ng-app=”MyApp”>

15. Now, let’s add a DemoController.js file in your project under app folder.

16. Add following snippet in DemoController.js

MyApp.controller(‘DemoController’, [‘$scope’,

function DemoController($scope) {

$scope.Name = “ovais mehboob”;

}]);

17. Now add a div tag inside Home/Index.cshtml file and specify ng-controller as DemoController

<div ng-controller=”DemoController”>

<h1>{{Name}}</h1>

<input type=”text” ng-model=”Name” />

</div>

18. In the above code, I have specified DemoController in div tag and access scope varialbes that were defined under DemoController. Using “double curly braces” {{ }} you can access the scope variables throughout controller.

19. In order to bind the values of scope variables with input fields like textbox etc you can use ng-model and ng-bind to bind with other controls like span etc.

20. Add MyApp.js and DemoController.js inside BundleConfig.cs

bundles.Add(new ScriptBundle(“~/bundles/angular”)

.Include(“~/Scripts/jquery-1.10.2.js”,

“~/Scripts/angular.js”,

“~/app/MyApp.js”,

“~/app/DemoController.js”));

21. Let’s build and run the application

44

In the next post I will discuss about routing and rendering views inside a single page application.

Buy eBooks and Videos in Just $5 – By Packt Publishing

Being an active participant in reviewing Packt Publishing books related to Software discipline, I would like to announce a “$5 eBook Bonanza”. It’s an exciting offer to buy any book or video in just $5.

Go to this link and buy as many as you can. This offer is valid till 6th Jan 2015.

Understanding OWIN by developing a custom OWIN middleware component

OWIN stands for Open Web Interface for .NET that decouples the Web Application from Web Server through an interface. In this article I will try to show some basic example of creating custom OWIN middle ware component and using it in self-host console application. The idea is to clarify the working of OWIN and what we can achieve with this new paradigm.

OWIN classifies web application into 4 parts

  1. Host
  2. Server
  3. Middleware
  4. Application
    ASP.Net MVC web application Fully OWIN compatible web applications
    Host IIS Any application Console App, Windows Service, IIS etc.
    Server IIS An application that hooks up the HTTP Listener to listen for a request.
    Middleware IHTTP Modules OWIN Middleware
    Application ASP.NET MVC 5 in IIS ASP.NET vNext, Web API 2 etc.

How is the request processed by OWIN Host?

When the request comes in to the OWIN server, the request properties like query string, path, content type, and so many others added into the IDictionary<string, object> object. This dictionary object is then sent to the request pipeline and then middleware components in the request pipeline can use this dictionary object and process accordingly.

OWIN expose following interface

System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;

Func is a new way of defining delegates in .NET framework. The first parameter denotes the input parameter and second as a return parameter. Here we have IDictionary<string,object> as input and Task as the resultant output.

When the request comes to the server, OWIN host calls the Invoke method of all the middleware components defined in order and pass the dictionary object. Each middleware component gets the complete request properties as dictionary object.

Startup.cs class is an entry point to build the request pipeline. In the Startup class, Configuration method is mandatory that takes IAppBuilder as a parameter. Using IAppBuilder you can add the OWIN based middleware and define the request pipeline. Developers can develop their own pipeline for incoming request. In IIS there are many components configured through which the request is passed through and for simple or mid-sized applications that seems to be an overkill. With OWIN based host it is quite easy to use only those OWIN extensions or middleware components that are required for your web application.

In order to elaborate, let’s create a simple OWIN middleware that logs the incoming request message into the console application and host the OWIN server in console application itself.

  1. Open Visual studio 2013 and create a new Console Application project
  2. Add OWIN NuGet references using NPM
  3. We need to add three NPM packages i.e.
    1. Microsoft.Owin – contains helper types and abstractions for simplifying the creation of OWIN components
    2. Microsoft.Owin.Host.HttpListener – OWIN server used for self-hosting
    3. Microsoft.Owin.Hosting– provides infrastructure types for hosting
  4. These libraries are part of Katana project, an implementation of OWIN by Microsoft
  5. In order to use OWIN on IIS, you can use Microsoft.Owin.Host.SystemWeb. Normally in IIS the request pipeline consists of HttpModules that are subscribes to events like BeginRequest, AuthenticateRequest etc. When you add this assembly in ASP.Net web applications you can define the OWIN based middle ware components in your Startup.cs and at runtime the Katana runtime mapped each of the middleware component to PreExecuteRequestHandler that corresponds to the PreRequestHandlerExecute event. Thus, the middleware components are invoked by the IIS integrated HTTP pipeline. This is not supported with classic HTTP pipeline.
  6. Once these references are added, we have to create a Startup.cs class and add Configuration method as below

    public void Configuration(IAppBuilder app){ }

7. Now let’s create a custom logging component to log incoming HTTP Request

      public class LoggingMiddleware

         {

              private AppFunc appFunc;

              public LoggingMiddleware(System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task> func)

           {

                 this.appFunc = func;

            }

            public async Task Invoke(IDictionary<string,object> env)

{

                  Console.WriteLine(“Request method is “+ env[“owin.RequestMethod”]);

                  var task = appFunc.Invoke(env);

}

}

8. Add this logging middleware in the configuration method using IAppBuilder use method

public void Configuration(IAppBuilder app)

{

app.Use<LoggingMiddleware>();

}


9. In the Main method of console app start the server using following WebApp.Start

Microsoft.Owin.Hosting.WebApp.Start<Startup>(http://localhost:12345&#8221;);

Console.ReadLine();


Following is a complete code

     

public class Startup

{

public void Configuration(IAppBuilder app)

{

app.Use<LoggingMiddleware>();

}

}

public class LoggingMiddleware

{

private AppFunc appFunc;

public LoggingMiddleware(System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task> func)

{

this.appFunc = func;

}

public async Task Invoke(IDictionary<string,object> env)

{

Console.WriteLine(“Request method is “+ env[“owin.RequestMethod”]);

var task = appFunc.Invoke(env);

}

}

class Program

{

static void Main()

{

Microsoft.Owin.Hosting.WebApp.Start<Startup>(http://localhost:12345&#8221;);

Console.ReadLine();

}

}

}

10. Now run the application and access the URL http://localhost:5555

11. You will see the logging on your console app.

Reviewed book “Bootstrap for ASP.NET MVC” by Pieter van der Westhuizen

I have gotten this opportunity to review the book named “Bootstrap for ASP.NET MVC” from Packt (UK based publishing company specializing in focused IT books).

Following is a review I made for this book

This book is a perfect guide to learn about using Bootstrap in ASP.NET MVC applications. Pieter does not only provided the basic information about incorporating Bootstrap in ASP.NET MVC but for almost each topic there are steps provided with code snippets that helps the reader to perform hands-on on the fly.

 

Developing and Self-Hosting Simple ASP.Net vNext Application using Command Line Tools

In this post I will walk you through the latest version of ASP.Net i.e. ASP.Net vNext and talk about some core characteristics as well as some command line tooling options that allows developers to build, run and manage ASP.NET Applications.

ASP.Net vNEXT

ASP.Net vNext is the next version of ASP.Net that comes with some major changes when compared to ASP.NET. It’s open source and comes under .Net Foundation. Now the developers can contribute and get a clone from https://github.com/aspnet

Core characteristics of ASP.Net vNEXT

  • Single programming model for websites (MVC, Web Pages) and services (Web APIs). No more APIController base class for Web API and unified Controller class that serves both MVC Controller and Web API Controller.
  • Introduced Project.json file where developers can define assemblies followed with versions, commands and versions of ASP.Net. Assemblies resolved by the Visual Studio CTP 14 immediately once you save the file and downloaded via NuGet. On the other hand if working in non Visual Studio environment you can use command line KPM restore command to download dependencies.
  • There is no dependency of System.Web.dll.
  • ASP.Net vNEXT is a Cloud optimized framework which is more robust and less in size. The full version of .Net is around 200 MB whereas the cloud optimized one is only 11 MB in size.
  • Dynamic compilation is a big feature provided in Roslyn (.Net Compiler Platform). Now developers can change code and refresh the browser without building the whole project.
  • Side by side support to deploy own version of .NET framework with each application. Each application have its own .net framework version running side by side on single machine.

In ASP.Net vNext, you have an option to run, compile and manage application versions etc. using different command line tooling options. First of all, in order to setup environment for executing KVM, KPM and K commands you have to execute the below powershell script.

@powershell -NoProfile -ExecutionPolicy unrestricted -Command “iex ((new-object net.webclient).DownloadString(‘https://raw.githubusercontent.com/aspnet/Home/master/kvminstall.ps1&#8217;))”

Following are the command line tools ASP.NET vNext provides

  • KRE (K Runtime)
  • KVM (K Version Manager)
  • KPM (K Package Manager)
  • K (To run commands)

What is KRE (K Runtime)?

K Runtime contains the SDK tools, compilation system and CLR hosts. It’s an actual ASP.Net vNext runtime that visual studio itself uses to provide intellisense, compilation errors etc.

What is KVM (K Version Manager)?

KVM stands for K Version Manager. This is used to get the K Runtime (KRE) to host ASP.Net vNext applications. This also allows managing the default version on app to app basis. KVM is essential when you want to self-host ASP.Net vNext application and running the self-host web listener using command line tool.

You can install KVM by running this command via command prompt

KVM install 1.0.0-alpha4

On installing KVM, all the kvm files are copied into the current users directory i.e. %windir%:\Users\%username%\.kre folder. It also places the environment variables on windows PATH so you can execute commands without directing to the KVM folder path.

Some widely used KVM commands

  • kvm upgrade

Checks the latest KRE version if available and install it on the machine

By default, we are running full .Net Framework but you can switch to the cloud optimized one using kvm upgrade –runtime CoreCLR

  • kvm list

To list the installed version of KRE the * denotes the active version and you can choose another version on app to app basis using kvm use version command

What is KPM (K Package Manager)?

KPM is the K Package Manager tool that you can use after installing KVM. Through this tool you can restore packages defined in the project.json file.

  • kpm restore

To restore the packages defined in the project.json file of your ASP.Net vNext application.

What is K?

K is the command line tool to run ASP.Net vNext application. You can use K run to run the HTTP listener to listen for the incoming request specified in the project.json file.

  • k web

Let’s do some Action!

In this exercise we will develop a simple ASP.Net vNext application without using Visual Studio 14.

  • Create a folder named “SampleKProject” in any of your machine drive.
  • Now create the project.json file inside that folder and copy below content.

    {

    “webroot” : “wwwroot”,

    “exclude”: “wwwroot/**/*.*”,

    “dependencies”: {

    “Microsoft.AspNet.Diagnostics”: “0.1-alpha-build-0682”,

    “Microsoft.AspNet.Hosting”: “0.1-alpha-build-0572”,

    “Microsoft.AspNet.Server.WebListener”: “0.1-alpha-build-0520”

    },

    “commands”: {

    “web”: “Microsoft.AspNet.Hosting –server Microsoft.AspNet.Server.WebListener –server.urls http://localhost:8090&#8221;

    },

    “frameworks”: {

    “aspnet50”: {},

    “aspnetcore50”: {}

    }

    }

    If you see the project.json, there are several sections namely webroot, dependencies, exclude, commands, frameworks etc.

webroot To specify the web server root folder where all the static files should be placed. In above code snippet we have specified wwwroot which means all the static files will be placed under wwwroot folder.
dependencies List all the dependent assemblies name followed with version information. All the dependencies will be loaded using kpm restore and downloaded via NuGet.
exclude You can provide folder path to exclude files from compilation
commands When running K command you can pass the name of a command to execute it. For example K web where web is the command name
frameworks To define the target frameworks that will be build or the dependencies that are specific to configuration.
  • Now create the Startup.cs file that is the starting point for ASP.Net vNext application. In this class you can configure the components for the application pipeline. The Startup class must contain a method named “Configure” that takes IAppBuilder as a parameter. Following is a full code snippet of the Startup class.

    using System;

    using Microsoft.AspNet.Builder;

    namespace WebApplication5

    {

    public class Startup

    {

    public void Configure(IBuilder app)

    {

    app.UseWelcomePage();

    }

    }

    }

    app.useWelcomePage adds a middleware component that shows the welcome page on navigating the URI

  • After creating project.json and Startup.cs files, open up a command prompt and go to the root folder that we created earlier i.e. SampleKProject and run kpm restore. When running the kpm restore it searches the project.json file and resolves the dependencies by downloading them via NuGet.

  • Once this is done you can run k web to start the self-host web listener.

Hint: web server can be stopped by using Ctrl+C and typing ‘Y’

Writing Diagnostic with Code Fix using Roslyn (.NET Compiler Platform)

Since the preview version of Roslyn (.Net Compiler Platform) released this year, developers can use compiler as a services APIs that provides an object model to develop tools to extend the development of “Visual studio” using code analysis, refactoring and writing custom diagnostics. In this post I will walk you through the steps of developing an extension of Visual Studio using Roslyn Diagnostic with Code Fix project template.

Background

Before going into action, Roslyn is a set of open source compilers for C# and VB languages. It’s an open source project comes under .Net Foundation (Open Source Foundation for .Net). Due to the open source model developers from all around the world can contribute. Apart from contributing to the Roslyn project they can also use Roslyn “Compiler as a service” APIs to extend Visual Studio and applications in specific needs.

Writing Simple Diagnostic with Code Fix

In Visual Studio 13 or Visual Studio CTP 14 you can get the template of writing your own Diagnostic with Code Fix for Visual Studio. You can download the Roslyn preview from https://connect.microsoft.com/VisualStudio/Downloads

Through “Diagnostic with Code Fix” you can actually develop your own diagnostic tool that is loaded into the Visual Studio and checks your code Syntax, Symbols etc. When you select and create a project you will see the DiagnosticAnalyzer and CodeFIxProvider classed created by default.

DiagnosticAnalyzer class implements ISymbolAnalyzer but there are other interfaces as well like ISyntaxAnalyzer to analyze language syntax, ISemanticModelAnalyzer to analyze semantics etc.

CodeFIxProvider is used to fix the code when the diagnostic has been made. GetFixesAsync get the list of fixes and then we can develop a method to fix those changes accordingly.

On running the project, a new Visual Studio instance will be loaded and then you can create new project and test your newly diagnostic tool by writing some code.

In this post, we will do a simple example of using “Diagnostic with code fix” that will analyze the naming case of Property and check if the first character is upper case or not.

  • Create a new project “Diagnostic with Code Fix” in Visual Studio 2013
  • Modify the DiagnosticAnalyzer and implement interface ISyntaxNodeAnalyzer
  • There are many interfaces provided for specific reason like suppose if you want to diagnose symbols you can use ISymbolAnalyzer and for Syntax Trees use ISyntaxTreeAnalyzer and so on.
  • Here, we have implemented ISyntaxNodeAnalyzer to analyze the syntax node.

    * What is Syntax Node? Syntax node represents the syntactic constructs such as declarations, statements, clauses, and expressions. Each category of syntax nodes is represented by a separate class derived from SyntaxNode.

    In Syntax Tree API, each node can be a compilation unit, type declaration, method declaration, property declaration, parameter list etc.

  • When you implement ISyntaxNodeAnalyzer, you have implement the property SyntaxsKindOfInterest and AnalyzeNode which is invoked when you write a code in Visual Studio, selecting any project template. In the SyntaxKindOfInterest you can specify the SyntaxKind. In my code, I have specified the SyntaxKind.PropertyDeclaration to analyze the Properties but you can add as many syntax kinds in the ImmutableArray. In the AnalyzeNode method we can check the property first character if it is Upper case or lower case. Here is a complete code.

[DiagnosticAnalyzer]

[ExportDiagnosticAnalyzer(DiagnosticId, LanguageNames.CSharp)]


public
class
DiagnosticAnalyzer : ISyntaxNodeAnalyzer<SyntaxKind>

{


internal
const
string DiagnosticId = “Diagnostic1”;


internal
const
string Description = “Property Name contains lower case letters”;


internal
const
string MessageFormat = “Property Name ‘{0}’ contains lowercase letters”;


internal
const
string Category = “Naming”;


internal
static
DiagnosticDescriptor Rule = new
DiagnosticDescriptor(DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Warning);


public
ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return
ImmutableArray.Create(Rule); } }


public
ImmutableArray<SyntaxKind> SyntaxKindsOfInterest

{


get

{


return
ImmutableArray.Create(SyntaxKind.PropertyDeclaration);

}

}


public
void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)

{


var localDescription = (PropertyDeclarationSyntax)node;


string propName = localDescription.Identifier.Text;

propName = propName.Substring(0, 1);


if (propName == propName.ToLower()) {

addDiagnostic(Diagnostic.Create(Rule, node.GetLocation(), “Property first character should be in Upper case”, DiagnosticSeverity.Warning, 1, true));

}

}

}

  • When you run the application and if you declare any property having lower case Name you will get the green line and shows as warning.
  • Now, when the user take an action on the code snippet to fix the code, GetFixesAsync method is called by the Roslyn API which then change the code by calling CodeAction.Create method. Following is a full code snippet of CodeFixProvider that resolves the naming issue.

[ExportCodeFixProvider(DiagnosticAnalyzer.DiagnosticId, LanguageNames.CSharp)]


internal
class
CodeFixProvider : ICodeFixProvider

{


public
IEnumerable<string> GetFixableDiagnosticIds()

{


return
new[] { DiagnosticAnalyzer.DiagnosticId };

}


public
async
Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)

{


var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);


// TODO: Replace the following code with your own analysis, generating a CodeAction for each fix to suggest


var diagnosticSpan = diagnostics.First().Location.SourceSpan;


// Find the type declaration identified by the diagnostic.


var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<PropertyDeclarationSyntax>().First();


// Return a code action that will invoke the fix.


return
new[] { CodeAction.Create(“Fix Property naming convention”, c => FixPropertyNaming(document, declaration, c)) };

}


private
async
Task<Solution> FixPropertyNaming(Document document, PropertyDeclarationSyntax declaration, CancellationToken cancellationToken)

{


// Compute new uppercase name.


var identifierToken = declaration.Identifier;


var newName = identifierToken.Text;

newName = newName.Substring(0, 1).ToUpper() + newName.Substring(1);


// Get the symbol representing the type to be renamed.


var semanticModel = await document.GetSemanticModelAsync(cancellationToken);


var typeSymbol = semanticModel.GetDeclaredSymbol(declaration, cancellationToken);


// Produce a new solution that has all references to that type renamed, including the declaration.


var originalSolution = document.Project.Solution;


var optionSet = originalSolution.Workspace.GetOptions();


var newSolution = await
Renamer.RenameSymbolAsync(document.Project.Solution, typeSymbol, newName, optionSet, cancellationToken).ConfigureAwait(false);


// Return the new solution with the now-uppercase type name.


return newSolution;

}

}

  • That’s all, build the project and run
  • When you hit F5 a new instance of Visual Studio open up and you can test your diagnostic utility by writing some code.
  • Following is the screen shot showing the green line for Property that have lower case name.

  • If I hover the cursor on this line I will get my custom message.

  • On the left side I can see the bulb icon

  • By clicking on the popup menu, code fix will be applied

Creating custom HTML Helper Extension to generate Grid in ASP.NET MVC

In this article I will show the way of writing a custom HTML helper in ASP.NET MVC project to generate grid at runtime. Although, there are many JQuery controls and third party controls available that provide grid management functionalities but in certain cases you have to design controls to handle specific logic and conditions.

In one of my project I designed a grid control using TagBuilder that generates a grid at runtime on html page. I used Knockout and Knockout extensions to generate view model from the model associated to the view page. (Please note: in the below code snippets I have used Knockout and followed Knockout syntax for data binding and grid generation. You can learn knockout here)

First of all I created an HTMLExtension class marked as static. In ASP.NET MVC there are some out of the box HTML helpers provided like TextBoxFor, LabelFor etc. In order to generate our own HTML tags that work just like the standard HTML helpers provided in ASP.NET MVC framework we have to meet below conditions

  1. Class containing the HTML Helper method should be static
  2. First parameter should be preceded with this HtmlHelper;     indicates the HtmlHelper class that the extension method extends

Following is a code snippet of the custom Grid generation Html Helper method

 


public
static
IHtmlString GridFor<TModel>(this
HtmlHelper<TModel> htmlHelper, String modelView, Type type)

{

 


TagBuilder controlBuilder = new
TagBuilder(“table”);

controlBuilder.Attributes.Add(“style”, “border:1px;”);


var properties = type.GetProperties();

 

#region Header


TagBuilder thead = new
TagBuilder(“thead”);


TagBuilder rowHeader = new
TagBuilder(“tr”);


foreach (var property in properties)

{


var attrHeader = property.CustomAttributes.Where(i => i.AttributeType == typeof(Common.Facade.GridColumnAttribute)).ToList();


if (attrHeader.Count != 0)

{


var attributeHeader = attrHeader[0];


if (Convert.ToBoolean(attributeHeader.ConstructorArguments[1].Value) == false)

{


TagBuilder col = new
TagBuilder(“td”);

col.InnerHtml = attributeHeader.ConstructorArguments[0].Value.ToString();

rowHeader.InnerHtml += col.ToString();

}

}

}

thead.InnerHtml += rowHeader.ToString();

controlBuilder.InnerHtml = thead.ToString();

#endregion

 

#region Rows and Columns

 


TagBuilder tbody = new
TagBuilder(“tbody”);

tbody.Attributes.Add(“data-bind”, “foreach: “ + modelView);

tbody.Attributes.Add(“style”, “width:100”);


TagBuilder row = new
TagBuilder(“tr”);


foreach (var property in properties)

{


var attr = property.CustomAttributes.Where(i => i.AttributeType == typeof(Common.Facade.GridColumnAttribute)).ToList();


if (attr.Count != 0)

{


var attribute=attr[0];


if (Convert.ToBoolean(attribute.ConstructorArguments[1].Value) == false)

{


TagBuilder col = new
TagBuilder(“td”);

col.Attributes.Add(“data-bind”, “text: “ + property.Name);

row.InnerHtml += col.ToString();

}

}

}

tbody.InnerHtml += row.ToString();

controlBuilder.InnerHtml += tbody.ToString();

#endregion

 


return
MvcHtmlString.Create(controlBuilder.ToString());

}

 

On the index.cshtml page I have used Knockout to create view models on the fly

<script
type=”text/javascript”>

ModelService.Persons = @Html.Raw(Json.Encode(ViewBag.Persons));

</script>

 

ModelService.Persons represents the collection view model of the list shipped in ViewBag

 

Finally, you can place following line on your html page to render Grid at runtime.

 

@Html.GridFor(“ModelService.Persons”,typeof(Person))

 


In order to change the look and feel of the plain grid, you can define styles using css to the table rows and columns.

The above grid HTML helper method generates the column name based on the property name. In order to define custom column names we can define custom attribute and annotate that on each property of the properties Class. Below is a sample code snippet of the custom attribute containing few properties.

[AttributeUsage(AttributeTargets.Property)]


public
class
GridColumnAttribute : Attribute

{

 


public
string GridColName { set; get; }

 


public
bool IsHidden { set; get; }

 


public GridColumnAttribute(String Name, bool isHidden)

{


this.GridColName = Name;


this.IsHidden = isHidden;

}

 

}

We can annotate this attribute on our Person class like below (Note: Person is our Model class)


public
class
Person

{

[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; }

 

[GridColumn(“Department”, false)]


public
string Department{set;get;}

 

 


public
String EditLink { get { return
“Person/Edit/” + Id; } }

 


public
String DeleteLink { get { return
“Person/Delete/” + Id; } }

}

In the above code the EditLink and DeleteLink properties are defined to provide row level edit and delete options.

The extended version of the custom Grid HTML Helper method that supports row level editing, deleting and user defined column naming is as follows

 

public
static
IHtmlString GridFor<TModel>(this
HtmlHelper<TModel> htmlHelper, String modelView, Type type)

{

 


TagBuilder controlBuilder = new
TagBuilder(“table”);

controlBuilder.Attributes.Add(“style”, “border:1px;”);


var properties = type.GetProperties();

 

#region Header


TagBuilder thead = new
TagBuilder(“thead”);


TagBuilder rowHeader = new
TagBuilder(“tr”);


foreach (var property in properties)

{


var attrHeader = property.CustomAttributes.Where(i => i.AttributeType == typeof(Common.Facade.GridColumnAttribute)).ToList();


if (attrHeader.Count != 0)

{


var attributeHeader = attrHeader[0];


if (Convert.ToBoolean(attributeHeader.ConstructorArguments[1].Value) == false)

{


TagBuilder col = new
TagBuilder(“td”);

col.InnerHtml = attributeHeader.ConstructorArguments[0].Value.ToString();

rowHeader.InnerHtml += col.ToString();

}

}

}

thead.InnerHtml += rowHeader.ToString();

controlBuilder.InnerHtml = thead.ToString();

#endregion

 

#region Rows and Columns

 


TagBuilder tbody = new
TagBuilder(“tbody”);

tbody.Attributes.Add(“data-bind”, “foreach: “ + modelView);

tbody.Attributes.Add(“style”, “width:100”);


TagBuilder row = new
TagBuilder(“tr”);


foreach (var property in properties)

{


var attr = property.CustomAttributes.Where(i => i.AttributeType == typeof(Common.Facade.GridColumnAttribute)).ToList();


if (attr.Count != 0)

{


var attribute = attr[0];


if (Convert.ToBoolean(attribute.ConstructorArguments[1].Value) == false)

{


TagBuilder col = new
TagBuilder(“td”);

col.Attributes.Add(“data-bind”, “text: “ + property.Name);

row.InnerHtml += col.ToString();

}

}

}

 


TagBuilder editTd = new
TagBuilder(“td”);


TagBuilder editLink = new
TagBuilder(“a”);

editLink.Attributes.Add(“data-bind”, “attr: {href: EditLink}”);

editLink.InnerHtml = “Edit”;

editTd.InnerHtml += editLink.ToString();

 

row.InnerHtml += editTd.ToString();

 


TagBuilder deleteTd = new
TagBuilder(“td”);


TagBuilder deleteLink = new
TagBuilder(“a”);

deleteLink.Attributes.Add(“data-bind”, “attr: {href: DeleteLink}”);

deleteLink.InnerHtml = “Delete”;

deleteTd.InnerHtml += deleteLink.ToString();

 

row.InnerHtml += deleteTd.ToString();

 

tbody.InnerHtml += row.ToString();

 

controlBuilder.InnerHtml += tbody.ToString();

#endregion

 


return
MvcHtmlString.Create(controlBuilder.ToString());

}

 

Now when you run the extended version following Grid will be generated.

Hope this helps!

Signing Outgoing Messages in BizTalk Server using AS2 protocol

In this article I will show to send encrypted and signed message to destination trading partner in BizTalk Server.

I was working on some project earlier this month in which we have to send EDI documents using AS2 protocol. I will not go into the detail of setting up an AS2 protocol and targeting to the audience who are already familiar with BizTalk Server EDI messaging and protocols like AS2 and X12.

For each source and destination trading partners we have to create two parties one for source and one for destination and using those parties you can create agreements. When creating an agreement you have a choice whether to use X12, AS2 or EDIFACT protocol. Here I have used AS2 protocol. Each protocol have different set of attributes and methods to send messages.

Message can be signed using Certificates in BizTalk. You can create a test certificate using Visual Studio command line utility makecert. Certificate is a combination of private/public key pairs. For all outgoing messages BizTalk uses the private key to sign the messages and public key to encrypt the messages.

  • The private key .pfx file has to be imported in the Current User/Personal/Certificates folder.
  • The public key .cer file has to be imported in the Local Computer/Other People/Certificates folder.

Now you have to enable the encryption and sign options on the Validation tab of the Agreement window.

 

 

Make sure to restart the application instance. The message will be encrypted and signed using the private public key of the certificates.