Sunday, August 23, 2009

WCF 4.0 Simplified Service Configuration

In WCF 3.5 when we host the Service without a single Endpoint we get the exception saying we need to configure at least a single Endpoint.   But in WCF 4.0 this is not the case because Service Runtime will automatically adds defaults endpoints for us.

When Service Host application calls Open method on the ServiceHost instance that time it creates Service description from the App.Config  along with anything the host application may have configured explicitly and if the number of configured endpoints is still zero then  it calls AddDefaultEndpoints, a new public method found on ServiceHost class.

image

In the above code i have added  a single service Endpoint with WSHttpBinding and also i invoked the method  AddDefaultEndpoints to add default endpoints as well.  The AddDefaultEndpoints  method basically adds one default endpoint per base address for each service contract implemented by the service.

When I Enumerate the service endpoints i get the following list of endpoints. The Runtime added the default endpoints with basicHttpBinding  

image

[Note: The above WCF Service application do not have any configuration file.  To expose meta Data you can add App.config with following settings]

image

Thanks(Nandri)

R.SeenivasaRagavan

Friday, August 14, 2009

WS-Discovery Protocol in WCF 4.0 –Part 11 –[Announcement]

In First part of this series  Client is looking for service based on criteria such as Service type. In this post we are going to use Announcement. In this case Service will Announce themselves to the network and Clients can be configured to listen for service announcements.   

In the default case a service sends out a hello message when it comes online and a bye message when going offline. This pattern is useful when a service wants to notify a recipient without having the recipient pinging the network periodically.

On the Service side we need to add ServiceDiscovery Behavior as shown below

image  

Client side we need to Host AnnouncementService and subscribe for OnlineAnnouncementReceived and OfflineAnnouncementReceived events.

Here is the client code to host AnnouncementService   and subscribing the events.

image

OnlineAnnouncementReceived and OfflineAnnouncementReceived events implementation.

image

Now to test first Start the client application  after that Start the Service application .

when service comes to online OnlineAnnouncementReceived event handler will be executed.

image

Once service goes to offline client will receive the announcement and  OfflineAnnouncementReceived  will be executed.

image

Note: if service is aborted  then the client won’t receive Announcement message . ( This is why i close the Service host when any key is pressed and display the message saying that service is offline now)

My Service code snippet

namespace SvcHost {
    class Program {
        static void Main(string[] args)
        {
            ServiceHost svc = new ServiceHost(typeof(Service1),new Uri("http://localhost:1394/Service1.svc"));
            svc.Open();
            Console.WriteLine("Service is online Now.[Press any key to close the service.]");
            Console.ReadLine();
            svc.Close();
            Console.WriteLine("Service is offline Now");
            Console.ReadLine();

        }
    }
}

This pattern is useful when a service wants to notify a recipient without having the recipient pinging the network periodically.

Thanks(Nandri)

SreenivasaRagavan

WS-Discovery Protocol in WCF 4.0 –Part 1.

MS Windows Communication Foundation (WCF) 4.0 has lot of  new features one of the feature  called WS-Discovery. The goal of  WS-Discovery protocol is to enable client to search one or more Targeted Services. WS-Discovery protocol is a multicast discovery protocol. The main usage of this protocol is, its helps client needs to find the services on the network. Here  services  can be  SOA services or any other hardware device. For example Windows Vista implements WS-Discovery to support the Device Profile for Web Services (DPWS). DPWS provides standards-based connectivity to network devices including printers, RFID readers, wireless cameras, projectors, and more.

Here is the URL where you can download WS-Dynamic Discovery White paper http://specs.xmlsoap.org/ws/2005/04/discovery/ws-discovery.pdf

Here is the Model for  the message exchanges between a Target Service and a Client ( please download the above white paper and read that helps lot easier to understand WS-Discovery )

image

WS-Discovery protocol  defines two modes of operations  one is Ad hoc mode and Managed mode. In ad hoc mode, clients probe for services by sending multicast messages. Services that match the probe respond directly to the client. In order to minimize the need for client polling, services can also "announce" when joining or leaving the network by sending a multicast message to any clients who may be "listening". Although ad hoc discovery is the simplest form, it only works within the context of a local subnet.

Now let see how we can enable WCF service for Discovery in  WCF 4.0 and .NET 4.0 ( Note: Here i am using  .NET & WCF 4.0 Beta 1).

Enabling WCF 4.0 Service for WS-Discovery is very easy. we need to modify WCF service configuration settings .

1) First add one endpoint to the service

2) Add Service behavior with serviceDiscovery element. 

image

By doing the above changes into WCF service configuration , the WCF service will become discoverable over UDP on the local subnet. Clients can now takes an  advantage of WS-Discovery at runtime to “Discover” the actual address of the running service. WCF 4.0  in .NET 4 makes it easy for clients to accomplish this through a new DiscoveryClient class which lives in  System.ServiceModel.Discovery assembly.

Here is the client code and Configuration File

image

image

image

In this blog post i showed  that the client simply probed services for based on client contract type. Next post we will see how we can use Service Announcements

stay tuned….. 

Thanks(Nandri)

SreenivasaRagavan.

Thursday, August 13, 2009

Visualize Code Dependencies by Assembly, Class & Namespace in VS.NET 2010 Team suite Beta-1

In VS.NET 2010 Team Suite Beta-1 offers new feature called  visualize code dependencies by Assembly , Namespace and class. to generate Graphical view of code dependencies  click Analyze menu and click  Visualize code dependencies then select the options you want as shown below.

image

 

Here is the Visualize code dependencies by Assembly for my project MVCApplicaiton1  .

image

In the above Diagram i further Expended AccountController Class  just click the  image  arrow i could see all the methods and their dependencies.

For example if you look at the image method  do not have any dependencies so either no arrow going from nor coming in.image

using visualize code dependencies  we can even find out  Circular Reverences, Unused References, etc…( see the Legend)

image

I think this helps if new developer joins the Dev team he/she can easily understand components of each Modules and how it gets refinanced to others projecta or classes,and also this helps the new team member to understand the application very easily   and start working straightway  .

Thanks(Nandri)

SreenivasaRagavan.

BizTalk Server 2009 BAM Portal (Enabling 32-bit mode for IIS on 64-bit platform)

Today I installed BizTalk server 2009 on my Windows-7 64-bit OS, after installing i try configuring the BizTalk server  SSO, BizTalk Group, BTS Runtime etc.. all are  passed except BAM Portal. After looking at error message i figured out, for BAM portal the IIS must be in 32 bit mode.  because BAM portal requires IIS to run on 32 bit mode.

To enable IIS 32-bit mode  Here is the script we need to execute the following command

cscript.exe c:\Inetpub\AdminScripts\adsutil.vbs set W3SVC/AppPools/Enable32BitAppOnWin64 1 

please make sure that you run cmd as Administrator . other wise you get the following error on windows 7

image

Admin Mode:

image

I really Hope BizTalk Server team will fix this small issue in future. ( When i was @MS i was working for these to great people Puru Amradkar –PM , Michael Roze-SDE  they should look at it this issue :) )

Thanks(Nandri)

SreenivasaRagavan.

Tuesday, August 11, 2009

Model Bindings in ASP.NET MVC Application

In ASP.NET MVC Framework, Model is the part of the application . Using model we  build business objects which is used in application and typically build from  MS-SQL Server , ADO.NET Dataset or any other data source.

A model class in an ASP.NET MVC application does not directly handle input from the browser, nor does it generate HTML output to the browser instead its used for to retrieve and store data.

ASP.NET   M & C

Using model classes from a controller typically consists of instantiating the model classes in controller actions, calling methods of model objects, and extracting the appropriate data from these objects to display in views. This is the recommended approach for implementing actions. It also maintains separation between the logical elements of the application, which makes it easier to test the application logic without having to test it through the user interface.

Here is the simple Model class which represents a  Car

public class Car
   {
       public string TitleName { get; set; }
       public string Make { get; set; }
       public string Year { get; set; }
       public string LicPlate { get; set; }
       public string Color { get; set; }
  }

In ASP.NE MVC application the  Model Binders are simply maps the  HTTP-POST request form values to  .NET type.   here is the example of  ASP.NET MVC Model binding.

[HttpPost]
     public ActionResult Create( FormCollection values)
     {

           if (values["TitleName"].Length==0)
                ModelState.AddModelError("TitleName", "Title Required");

         if (!ModelState.IsValid)
         {
             return View();
         }

         string tn = values["TitleName"];
         cars.Add(new Car { TitleName =tn} );
             return RedirectToAction("Index",cars );
     }

With the FormCollection you don’t have to dig into the Request object.  other wise some people use Request object to get posted values as shown below.

[HttpPost]
       public ActionResult CreateCar()
       {
           Car car = new Car();

           string TitleName = Request.Form["TitleName"];
           string Year = Request.Form["Year"];
           // .........................
           //..........................
           return View();
       }

If your Data in Request.From then Model binding will do the above works for you automatically like Magic.

[HttpPost]
public ActionResult Bind( Car     car)
{

      if (string.IsNullOrEmpty(car.TitleName))
           ModelState.AddModelError("TitleName", "Title Required");

    if (!ModelState.IsValid)
    {
        return View();
    }

    cars.Add(car );
        return RedirectToAction("Index",car );
}

In the above controller  Action the Model binder will create  you Car object and populate it with data which is find in  HTTP-POST form Request. This is based on the  form data with matching up with  Car Property.

ASP.NET Model binder also can be extensible, so we can even create Custom Model Binder by implementing the Interface  IModelBinder

 Note: The Attribute [HttpPost] i used is this post is new in ASP.NET  MVC 2.0 which is equivalent  [AcceptVerbs(HttpVerbs.Post)]in MVC 1.0 

Thanks(Nandri)

SreenivasaRagavan.

Saturday, August 8, 2009

Extending ASP.NET MVC HtmlHelper class

There are two ways you can build Views content in ASP.NET MVC  one of the method  we use HtmlHelper class to build our views content. other method is to use Standard HTML Tags.  The difference i see between these two methods are  Html Helper class provides Readability of the View ,easy to use & reduce  script code

Here i am listing out some of the  Html Helper class methods The ASP.NET MVC framework includes.

  • Html.ActionLink() – Create HTML Link Tag

  • Html.BeginForm()  - Create <form> Tag.

  • Html.CheckBox()  

  • Html.DropDownList()

  • Html.EndForm()

  • Html.Hidden()

  • Html.ListBox()

  • Html.Password()

  • Html.RadioButton()

  • Html.TextArea()

  • Html.TextBox() –Create Html Text Box.

Here is  how we  use in  Views (.ASPX pages)  for example if you want to use HTML Textbox with txtName

<p> Enter the Name :
   <%=Html.TextBox("txtname") %>
</p>

The output of the above code is image

Suppose we wanted to render the  HTML Table output for the given Data source in this case  there is no Html Helper class method  available . So the solution to this problem is we can create custom Method which will render standard HTML Table output for the given Data or we can use C# new features called  Extension method to Extend Html Helper class. Extension method enables us to add new method in existing class

To create Extension Method  we need to follow the following Rules.

  1. Both class and Method should be static.
  2. The first parameter always the name of the class on which we are extending the method with [this ] keyword.

image

Now i am going to use my  HTML Table Helper Class in MVC  View (.aspx) Page.  first we need to Import the namespace where our  Html Helper class lives in my case

I am importing HtmlExtn.Util namespace.

image

 

image

Here is the output of the Index View.

 

image

You may be asking question yourself why can’t we use  ASP.NET server controls Instead  . Because ASP.NET MVC  do not have  ViewState and Postback features   which ASP.NET Server controls has this property.

Thanks(Nandri)

Sreenivasaragavan

ASP.NET MVC and LINQ to SQL Using Repository pattern

 The Repository Pattern

When building a Model for ASP.NET MVC applications always it is a good practice to use the Repository pattern so that the DAL layer is easy to change and test as per the need arises. When you use the Repository pattern, you create a separate repository class that contains all of your database access logic CURD with constraints.

When we create the repository class, we create an interface that represents all of the methods used by the repository class. Within the controllers, we write our code against the interface instead of the repository. That way, we can implement the repository using different data access technologies in the future.

In this post I am going to  build my Model using LINQ to SQL . let’s get started .  Now right click on Model Folder click new item and select the LINQ to SQL Classes template and add to the model as shown below

image

Now click Server Explorer link on LINQ to SQL Design Surface and  Add Data connection and choose the DB you wanted to work with.

image

Choose your DB server name and DB ( click Test Connection to validate the DB connection)

image

Now you added the Data source successfully.

image

Next step is to create a Repository pattern Interfaces .  Here  we are going to create a Repository  Interfaces for each Model Student, Course,Offering…

I am going to show you with Student model. so let us create IStudentRepository as shown below.

image

 

Next step is we need to  create StudentRepository class  that  implements (Inherits)   IStudentRepository .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCDataApp.Models
{
public class StudentRepository :IStudentRepository
{
// Create the Database context
private StudentDataContext studentdbconnection;

public StudentRepository()
{
studentdbconnection = new StudentDataContext();
}
public IQueryable<Student> GetAllStudents()
{

var query = from student in studentdbconnection.Students
select student;
return query.AsQueryable();
}
public void DeleteAStudent(string studentNo)
{
var q = from std in studentdbconnection.Students.Where(std => std.StdNo == studentNo) select std;

studentdbconnection.Students.DeleteOnSubmit(q.FirstOrDefault());
studentdbconnection.SubmitChanges();
}

public void AddStudent(Student std)
{
studentdbconnection.Students.InsertOnSubmit(std);
studentdbconnection.SubmitChanges();
}

public Student GetStudentById(string studentId)
{
Student stdRecord = null;

var std = from studentRecord in studentdbconnection.Students
where studentRecord.StdNo.Trim() == studentId.Trim()
select studentRecord;


if (std.Count () !=0)
{
foreach (var item in std)
{
stdRecord = new Student
{
StdNo = item.StdNo,
StdCity = item.StdCity,
StdLastName = item.StdLastName,
StdFirstName = item.StdFirstName,
StdClass = item.StdClass,
StdGPA = item.StdGPA,
StdMajor = item.StdMajor,
StdState = item.StdState,
StdZip = item.StdZip
};
}
}

return stdRecord;
}


}
}




 



We are almost done with Model.  Now  we have the ASP.NET MVC project  LINQ to SQL classes Model next we need to access the data and pass it the views. 



image



 



The above  HomeController class has two constructors methods. The first constructor (the parameterless one) is called when application is running. This constructor creates an instance of the StudentRepository class and passes it to the second constructor. The second constructor has a single parameter an IStudentRepository parameter. This constructor simply assigns the value of the parameter to a stdRepo instance variable. This is an implementation of a software design pattern called the Dependency Injection pattern. In particular, Constructor Dependency Injection.



Now we need add some code in Index View  to display the students records.



<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IQueryable<MVCDataApp.Models.Student>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>Index</h2>
<table border="5" bordercolor="red">
<thead>
<tr>
<th>Std No</th> <th>First Name</th> <th>Last Name</th>
</tr>
</thead>
<% foreach (var item in ViewData.Model)
{ %>


<tr>
<td>
<%=item.StdNo %>
</td>

<td>
<%=item.StdFirstName %>
</td>

<td>
<%=item.StdLastName %>
</td>
</tr>
<%} %>
</table>

</asp:Content>


Here is the view result 



image



 



Suppose If you want to change the data access technology using  EF ( Entity Framework) instead of  LINQ TO SQL  you simply implement the IStudentRepository interface with a class that uses the alternative database access technology. For example, you could create a class EF_StudentRepository  class. Because the controller class is programmed against the interface, you can pass a new implementation of IStudnetRepository to the controller class and the class would continue to work. this is the advantage we have when we use Repository Pattern.



when we use  Repository pattern we can able to change data access technology from one to another very easily. 



 



Thanks(Nandri)



SreenivasaRagavan

Thursday, August 6, 2009

Data Annotations Validation in ASP.NET MVC application.

ASP.NET MVC Framework 2.0 now supports Data Annotations validation supports. Originally this was shipped with .NET 3.5  Service pack 1 and this was used in Silver light application and ASP.NET Dynamic Data. Data Annotations features  gives  ASP.NET MVC application Model and View Model classes  to validate declaratively and have automatic binding and UI helper validation support within ASP.NET MVC.

To apply this new features let us create ViewModel class called Books with the following properties.

 public class Books
{
public string ISBN {get;set;}
public string Title {get;set;}
public string Publisher {get;set;}
public string AuthorName {get;set;}
public int NoPages {get;set;}
public DateTime PubDate{ get;set;}

}


Now let’s decorate right validation rules for each books class properties with right validation attributes. Data annotations attributes are lives in the following Namespace  System.ComponentModel.DataAnnotations.


image 


Let’s take the  Required attribute  the class RequiredAttribute is derived from ValidationAttribute as shown below.



image



So all Validations attributes are derived from  a base class ValidationAttribute this gives the message to us saying that  we can also create custom validation attributes .



We can now create two action methods  in HomeController.  The first action method  AddNewBook handles HTTP-GET Request and second action method AddNewBook will handle HTTP-POST method and it takes Books as parameter.



image



Now we are ready to add views . To add a view just right click either one of the action method  as shown below



image



In Add view Dialog check Create a strongly-typed view and in view content dropdown list select Create and click add .



image







after clicking the add button the following View template created based our Books Viewmodel object.



image




Now we are ready to test our application by requesting the  AddNewBook . now controller will route this request to 



public ActionResult AddNewBook()

       {


           Books bk = new Books();


           return View(bk);


       }

 


image



Now enter some invalid input and click create button this time controller will route the request to Second method with [HttpPost] decorated. since this is post request from the client. we know that there are errors in out input so now controller  redisplay the form this happens until all validation rules are satisfied .image



Now input the correct values and click the create button.



image image



 



Thanks(Nandri)



SreenivasaRagavan.

Wednesday, August 5, 2009

ASP.NET MVC Extensibility-Part 2

In this post I am show how to Extended ASP.NET MVC Framework  Pipeline with ActionAttribute ,IActionFilter, IResultFilter . First we are going to create new attribute which is derived from ActionAttribute class.

what is Attribute?

Using Attributes we can decorate C# code in declarative fashion.  attributes can be applied types, methods, properties, and so forth. Once associated with a program entity, the attribute can be queried at run time using a technique called Reflection.

Attributes exist in two forms: attributes that are defined in the Common Language Runtime's base class library. For example  when we are defining a WCF Service Operations we decorate  WCF service methods with [OperationContract] attribute. 

Second form of attributes are  custom attributes that we create, to add extra information to your code. This information can later be retrieved programmatically.So now we are going to create a custom attribute class which is derived from ActionAttribute with the Interfaces IActionFilter, IResultFilter  this way i can automatically get the methods which i need to implement.

Here i am going to create attribute called RouteUser and Implementing the OnActionExecuting method this will execute before the Controller Action code executes.

image 

Inside OnActionExecuting  method i am going to check if user is  Authenticated or not.  If user is not Authenticated then  i am going to throw an exception called access violation.  even you can log the details and Redirect the user to logon page. ok lets do that if user not authenticated we will redirect the user to Logon Page instead of throwing exception [i will put code for both] . 

image

Now we have finished creating the RouteUser attribute let’s use it in our  ASP.NET MVC controller action method and test it.

image

Now let us  invoke the Welcome action method  browsing the following url http://localhost:49584/Home/Welcome [please browse your local machine URL]  with out logging the result is the user Redirected to LogOn Page[http://localhost:49584/Account/LogOn] since the user did not Authenticated.

image

Note : we can use multiple action filters in the same action method  with order number specified  so that they execute in that order . 

image

Thanks(Nandri)

SreenivasaRagavan

ASP.NET MVC Extensibility -Part1

In this post i am going to show you how to extended MVC Framework ActionResult & ActerFilterAttribute 

ActionResult

In ASP.NET MVC  Framework user request are  routed to the Controller then controller will invoke right action and returns the ActionResult as view.  The view can be one of the following

  1. ContentResult – Simply writes the returned data to the response.
  2. EmptyResult – Returns an empty response.
  3. HttpUnauthorizedResult – Returns Http 401 code for non authorized access.
  4. JsonResult – Serializes the response to Json.
  5. RedirectResult – Redirects to another Url.
  6. RedirectToRouteResult – Redirects to another controller action.

Now we are going to extend the ActionResult to return the XML document .

Let we have Model  which describes Contacts Details with the following attribute  Name,Email, Phone, MSNMessengerID, WebPage etc.. now we wanted to return this Model as XML document as ActionResult.

My Model Class Definition:

image 


Next we need to create XML  ActionResult  class which is derived from ActionResult class.



Here is the ActionResult class.



using System;
namespace System.Web.Mvc {
// Summary:
// Encapsulates the result of an action method and is used to perform a framework-level
// operation on the action method's behalf.
public abstract class ActionResult {
protected ActionResult();

// Summary:
// Enables processing of the result of an action method by a custom type that
// inherits from System.Web.Mvc.ActionResult.
//
// Parameters:
// context:
// The context within which the result is executed.
public abstract void ExecuteResult(ControllerContext context);
}
}


XMLDocumentResult Derived from ActionResult


we need to override ExecuteResult method.  here  i am serializing the object as XML and retuning it.  


using System.Web;
using System.Web.Mvc;
using System.Xml.Serialization;
namespace MVCExten.code
{
public class XmlDocumentResult :ActionResult
{
private object xmlSerializeable;
public XmlDocumentResult() {
}
public XmlDocumentResult(object xmlSer)
{
this.xmlSerializeable = xmlSer;
}
public object XmlSer
{
get { return xmlSerializeable; }
}
public override void ExecuteResult(ControllerContext context)
{
if (xmlSerializeable !=null)
{
XmlSerializer xml = new XmlSerializer(xmlSerializeable.GetType());
// context.HttpContext.Response.ContentType ="text/xml";
xml.Serialize(context.HttpContext.Response.Output, xmlSerializeable);
}
}
}
}


Now let us create new action in home controller which returns the XmlDocumentResult



image



Here is the ActionResult render to the client



image



So  now we can able to create custom ActionResult for anything fox example  RSS feed document.



Next Post we will see about ActionFilterAttribute and how to use it.



Thanks(Nandri)



SreenivasaRagavan.