Archive | ASP NET MVC RSS for this section

How To: Convert ASP.NET Web API to Azure API app

In my last post, I introduced and discussed about the new azure API apps.  It’s really nothing more than your asp.net web API with a new way and form to expose the metadata so to speak.  Its actually a web app with other additional features for hosting. Azure API  is hosted within a web app.

In the pipeline to Azure API app, there a gateway which performs other stuff before reaching the Azure API app. The gateway is just another web app able to perform extra functionality like authetication with providers.

Every resource group with that contains an API app also includes a gateway. The azure API app expose there metadate via a new representation swagger. Its a new powerful representation of RESTful API.

In this post we are looking at how to convert an already existing ASP.NET web api to azure api app. I will be using visual studio 2013.

Open visual studio 2013, and create a new ASP.NET Web api.

aspnetwebapi

To keep things simple, I am not using any authentication in this post. We will make a few changes to ValuesController, make sure it look like show below


public class StudentController : ApiController
{
public IHttpActionResult Get()
{
var students = Students();

return Ok(students);
}

private List<Student> Students()
{
var students = new List<Student>();
IGenerationSessionFactory factory = AutoPocoContainer.Configure(
x =>
{
x.Conventions(c => { c.UseDefaultConventions();});
x.AddFromAssemblyContainingType<Student>();
});

//Create a session
IGenerationSession session = factory.CreateSession();
students = session.List<Student>(50)
.First(25)
.Impose(x => x.FirstName, "Bob")
.Next(25)
.Impose(x => x.FirstName, "Alice")
.All()
.Impose(x => x.LastName, "Pius")
.Random(10).Impose(x => x.LastName, "Peter")
.                                                  All().Get().ToList();

return students;
}
}

In our code we are using “autopoco” package to generate object to test with. So far this is just the normal ASP.NET web api. You can run the application and hit “http://localhost:26467/api/Student&#8221; and you will see the response of 50 students.

So how do we convert it to azure API app? Good question, and the essence of this post. To do that you simply add a new package called “swashbuckle” as shown below. Go package manager and search for “swashbuckle”

swashbuckle

When this is installed a new file should be added in your App_Start, “SwaggerConfig.cs”. Ensure your solution looks like below

Swaggerfileconfig

That’s the file that makes your expectations come true. Nothing much, nothing less. So run you application and hit the following url, “http://localhost:26467/swagger&#8221; which takes to a screen like below:

Swagger_documentation

If your screen looks like above then everything so far looks good. So this generates a documentation of all the api operations in the project, you need to know it uses the same pipeline as how ASP.NET WEB api generate help pages.  Click “Try it out!” and you will see a json response from the “GET” operation.

But where is the metadata? Navigate to “http://localhost:26467/swagger/docs/v1&#8221;, and this will generate a metadata file which is json in nature. We will talk on how to use this metadata file to generate a client sdk and other uses.

metadata

So from the image above.

1. Paths holds a collection of the API controllers in the projects

2. Indicate a API controller in our project “/api/Student”

3. Within every API controller, all available operations tagged with the http verb are listed.

4. The responses the operation supports.

That’s it!! 🙂 We have managed to convert/enable an ASP.NET Web api to a azure api app.

Source code can be on github

Advertisements

When to use Response.Redirect and Server.Transfer?

Recently I had to respond to an issue which was a result of using wrongly of the aforementioned in web forms. Each of them are used with a specific purpose and not as an alternative to another. And so let see when to use either of them and in what situations.

They do have distinct notable differences. One of them being with Response.Redirect the browser url changes to the targeted page while in Server.Transfer the url remains the same.

With Response.Redirect a HTTP 302 message is usually sent do the browser  while in Server.Transfer all happens without the browser knowing anything, and it ends up recieving a different content from the requested.

Another difference is that the Server.Transfer consumes more server power in comparison to Response.Redirect.

Server.Transfer cant send a user to an external site while Response.Redirect can.

When to use Response.Redirect:

  • we want to redirect the request to some plain HTML pages on our server or to some other web server
  • we don’t care about causing additional roundtrips to the server on each request
  • we do not need to preserve Query String and Form Variables from the original request
  • we want our users to be able to see the new redirected URL where he is redirected in his browser (and be able to bookmark it if its necessary)

When to use Server.Transfer:

  • we want to transfer current page request to another .aspx page on the same server
  • we want to preserve server resources and avoid the unnecessary roundtrips to the server
  • we want to preserve Query String and Form Variables (optionally)
  • we don’t need to show the real URL where we redirected the request in the users Web Browser

I do hope this will help someone out there who needs to find which to use and when. This might not be exhaustive but it’s worthy you consideration

Happy coding!

What really is Katana and owin?

What really is really Katana? How about Owin? After playing around with Katana, I really found it worthywhile to post about what I have found regarding them. OWIN ( initials for Open Web Interface for .NET )is a set of specifications that defines a stardand interface between which .NET web servers and web applications communicates. Katana on the hand is an implementation of the OWIN.

A little history of ASP NET is that it was released in early 2002 or sometime around then, with .NET framework 1.0 and it was meant to bring a web experience for customers who included classic asp  and desktop line of business application developers like VB 6.

There were alot of stuff and concerns brought forward by these two customers, which meant that the framework was to be monolithic leading to inclusion of all concerns in one single package, System.Web.  The package included just to mention a few features, Modules, handlers, sesssion, cache, web forms and controls. And all this was meant to run on IIS.

With time the System.Web package became complex because with every new requirement it was added to the package. By default most of the features were turned on by default to seamless intengration .

By then, IIS was the only hosting for ASP NET and most of the features for ASP NET runtime map one to one with those found on the IIS. This was a problem and in around 2008 ASP NET MVC was released which atleast enabled rapid developement and was distributed via nuget. Come 2012 ASP NET WEB APi was released , and unlike ASP NET MVC, WEB API does not rely on System.Web in anyway. Initially WEB API was started by the WCF team, which later was sent to ASP NET  team who added capabilities like self hosting.

Thats a little background and history of a few players which brought the idea behind katana. In a modern web application, you  can expect to have at least some static files, web api, rendering engine perhaps MVC razor, and perhaps SignalR for some real time communication. And the question is perhaps, couldn’t it be awesome to be able to compose all these or other multiple frameworks together to create a single server?

And there comes Katana which is a set of components for building and running web applications on a common abstraction which is, OWIN…

The primary interface in OWIN is a application delegate or simply AppFunc, which is a delegate that takes IDictionary<string,object> and returns a Task, and the signature is like Func<IDictionary<string,object>,Task>

Katana is meant to offer the following

Portability by reducing to the least primitives as possible

Composability ->Its really easy to compose modules together that will participate in all aspect of the incoming requests.

Performance and scalability -> Uses Async throughout and there is total decoupling of web application and host.

A typical Owin enabled application should have the following layers.

1. Application ->This is your application which could be like ASP NET MVC

2. Application framework -> These could be regular OWIN component implementation giving simple to use API to developers to easily plug-in to the pipeline. For example, we have signalR and Web API, though currently SignalR uses OwinHost.

3.Server –> This is responsible to binding to a port and channels request to the pipeline for processing. e.g SystemWeb, HttpListener o or the new Weblistener

4.Host –> This is a process managers that spans new process call to your code and provides and puts the pipeline in place eg this could be IIS if you will be hosting on IIS, could be OwinHost.exe which is the katana implementation or even you custom process.

Currently, katana embraces conventions over configuration. So when you install owin, when you code runs it goes through you code via reflection looking for a class with name of Startup and a method named “Configuration” taking IAppBuilder interface as the only parameter. IAppBuilder is an interface used to compose modules together. There are alot of extension methods built on top of IAppBuilder which we will explore at a later post.

To recap, let write a simple application and host on a console application. I am using visual studio 2013. Open VS 13, File -> New Project ->Console Application, give a nice name and click Ok. This is  a simple console application with nothing to do with Owin. So open Package Manager Console and install the following nuget packages

Install-Package Microsoft.Owin.

install-package microsoft.Owin.Host.HttpListener.

install-package microsoft.owin.hosting

And at least it should be close to

Package-isntallation

With in we will now add the basic code to host our application. And just as we said we will need to add a class with a name “Startup” and a method “Configuration”. Quickly let to that. After we finish setting up the nuget packages then copy and paste following code to your program.cs file as is

using System;
using Microsoft.Owin.Hosting;
using Owin;

namespace KatanaTest
{
 class Program
 {
 static void Main(string[] args)
 {
 //Create a url
 string uri = "http://localhost:8080";

using (WebApp.Start(uri))
 {
 Console.WriteLine("Server is starting");
 Console.ReadKey();
 Console.WriteLine("Stopping the server");
 }
 }
 }

///
/// Note the name "Startup"
 ///
 public class Startup
 {
 ///
/// Note the name and parameter
 ///
 ///
 public void Configuration(IAppBuilder app)
 {
 //Simple write to the response stream here
 app.Run(x =>
 x.Response.WriteAsync("We are just testing this application"));
 }
 }
}

Run the code and open you favourite browser and paste http://localhost:8080/. The result which would be “We are just testing this application” printed on the browser. This means that you have successfully written you first owin application hosted on a console application.
Katana is utilized in the ASP NET MVC 5 project template for authetication. In our case we have utilized the simplest method ever to write something on the response stream. But there is alot of extensibility and capabilities with katana where you can plug your own middleware or component in the pipeline, which is how the authetication is plugged in the ASP NET MVC 5. Another post regarding this soon.

But just to point out is that all you really need to write a katana module, is to write a class which has a constructor takes one arguement of type  Func<IDictionary<string,object>,Task>, and this represent the next module in the pipeline which you manually call from your component.

Just to demonstrate lets a middleware component that prints some message to the response

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Owin.Hosting;
using Owin;

namespace KatanaTest
{
 class Program
 {
 static void Main(string[] args)
 {
 //Create a url
 string uri = "http://localhost:8080";

using (WebApp.Start(uri))
 {
 Console.WriteLine("Server is starting");
 Console.ReadKey();
 Console.WriteLine("Stopping the server");
 }
 }
 }

///
/// Note the name "Startup"
 ///
 public class Startup
 {
 ///
/// Note the name and parameter
 ///
 ///
 public void Configuration(IAppBuilder app)
 {
 app.Use();
 //Simple write to the response stream here
 app.Run(x =>
 x.Response.WriteAsync("We are just testing this application"));

//Plug our component here

 }
 }

public class HelloWorld
 {
 private Func<IDictionary<string, object>, Task> _next;
 public HelloWorld( Func<IDictionary<string,object>,Task> next)
 {
 _next = next;
 }

public Task Invoke(IDictionary<string, object> environment)
 {
 var response = environment["owin.ResponseBody"] as Stream;

using (var writer = new StreamWriter(response))
 {
 return writer.WriteAsync("Hello!!");
 }
 }
 }
}

Its as easy as that, and now when you run the application you see “Hello!” on the browser. Something worthy noting here is “owin.ResponseBody”, which’s one of the key in the Environment dictionary. For now take that dictionary as the HttpContext which contains all the information about a request. There are more Owin specific keys in the dictionary which we will explore in a later post.

That’s it for now, there is more to come on this same topic especially on how to write to write and hook up your own modules in the pipeline. You may also be interested in Checking-out-the-Helios-IIS-Owin-Web-Server-Host which I may recommend to get some information on the topic.

Happy coding and kindly get involved via comments, questions or suggestions. Thanks for reading 🙂

Abstract classes or interfaces?

Many of the times, I have seen the question of what factors should one consider either to implement a functionality in terms of abstraction, and this narrows down to if one should employ abstract class or interfaces.  A few days ago I was surprised when reviewing some code and just to brainstorm the developer,  I asked him a simple question, why did you choose to use abstract class rather than an interface?  Guess the response.. I just thought its good to use abstract class rather than interfaces. I didn’t have any other question for him but found it useful to demisfy this here for him, and others who would have the same kind of response to such a question.

I do agree that the choice of using any of them can be a daunting task.I will try to summarize what I have and wha I have found useful on the internet on this post. But  lets start at looking at the definitions of each:

An abstract class is a class that cannot be instantiated but must be inherited. The class can contain some default implementation for the child classes to use, and this methods should be non abstract methods. If an abstract method need exist, then it should be modified with abstract keyword and does not contain a body.

An interface on the hand is a type definition similar to class except that it purely represent a contract between an object and its user. And so its just a collection of members definitions e.g method, properties, events etc without any implementation.

So this brings to the question of who support or does what? Here are do’s and don’ts for each of them.

  1. Instantiation: Abstract classes cannot be instantiated away from their derived classes, meaning that there constructor are called only by their derived classes. Interfaces on the hand cannot be instantiated.
  2. Abstract classes can provide abstract members which base class MUST implement while all interfaces members MUST be implemented in the base class. So you can not implement partial interface, if you don’t need an implementation or you will not use some interface members you may need to leave stubs. e.g ConvertBack method for IValueConverter is usually not implemented but most implementation of the interface leave a stub, and this bring to the Interface Segragation Principle
  3. Extensibility: Abstract classes are more extensible than interface. You can alter an abstract classes without breaking any version compatibility. And note this extensibility is for non-abstract members. Interfaces on the other hand, if you have to extend you will have to create a new interface, otherwise you break the existing clients. Consider a situation where you are employed and after sometime you get a pay rise, you actually and should sign a new contract which looks the same as the previous with with the new  salary figures appear.
  4. Virtual members: Abstract classes allows for virtual members with default implementation for the deriving classes while for interfaces all members are automatically virtual and cannot contain any implementation.
  5. Accessibility modifiers: You can control accessibility of some members in abstract classes while all members of an interface are public by default.
  6. Inheritance: Being a rule in C# specification multiple class inheritance is not supported meaning that a class cannot inherit from more than one classes. On the contrary multiple inheritance is supported with interfaces

With that in place there are some guideline you should follow when deciding which one to use and when to use it.

  1. If you anticipate to create multiple versions of a component you may use abstract classes reason being it’s easy to create and version your components. For example by changing or updating the base class all inheriting classes are automatically updated whilst in interfaces they do not support versioning. Once an interface is created it cannot be changed you will have to create a new one. The analogy being once you sign a contract with your employer, and happens you get a pay rise you sign a new contract, you don’t manipulate the previous.
  1. If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
  2. If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
  3. If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.

So too much of theory lets dive and see how we can establish some, if not all of the aforementioned points. So we are going to use an aspect of polygons. Basically we have a number of polygons which have different ways of calculating their areas. So we will employ both, interface and abstract class concepts.

 public interface IRegularPolygon
 {
 int NumberOfSides { get; set; }
 int SideLength { get; set; }

double GetArea();
 }
 public class Octagon : IRegularPolygon
 {
 public int NumberOfSides { get; set; }
 public int SideLength { get; set; }

public Octagon(int length)
 {
 NumberOfSides = 8;
 SideLength = length;
 }

public double GetArea()
 {
 return SideLength * SideLength * (2 + 2 * Math.Sqrt(2));
 }
 }

We also have an abstract class approach of the same.

 public abstract class AbstractRegularPolygon
 {
 public int NumberOfSides { get; set; }
 public int SideLength { get; set; }

public AbstractRegularPolygon(int sides, int length)
 {
 NumberOfSides = sides;
 SideLength = length;
 }

public abstract double GetArea();
 }
 public class Triangle : AbstractRegularPolygon
 {
 public Triangle(int length) :
 base(3, length) { }

public override double GetArea()
 {
 return SideLength * SideLength * Math.Sqrt(3) / 4;
 }
 }

Assuming that  you have implemented you get a requirement that you need to add a way to calculate the perimeter of the polygons. And knowing that, to calculate the perimeter of a polygon is just multiplying the number of sides with the length of one side.  With the abstract class implementation it really straight forward all you need to do is as below:

 public double GetPerimeter()
 {
 return NumberOfSides * SideLength;
 }

With the interface implementation you cannot just add the function declaration since this will break the existing clients. An easier way is to have a new interface with all the previous declaration or rather employ interface inheritance where you create a new interface with the new perimeter function inheriting from the IRegularPolygon. I would go with the latter.

Just to keep the post short, we end by looking what is in the framework which employs abstract classes and intefaces. In the BCL we have System.IO.Stream class, which is an abstract class. It contains some implementation of various methods as well as abstract and virtual methods which deriving classes implements. Some of the deriving classes include:

  • MemoryStream
  • FileStream
  • BufferedStream

With the interface, we have List<T> class which implements a list of interfaces which also show interface inheritance and best application of Interface Segregation Principle. Some of the interface it implements are

IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable

So we end the post to make sure its not too long,  having demonstrated a couple of points I leave it to you to try the rest and poke me if any issue arises or if you need some clarity or some of technical engagement.

Its my hope you will consider the above mentioned points next time you find yourself in a dillema of which one to use, abstract or interfaces.

Again happy coding  and bye for now 🙂

Returning javascript from ASP NET MVC

I have seen developers wonder how to return javascript from the server and have executed on client in an ASP NET MVC application. Fortunately, we have JavascriptResult in the ASP NET MVC stack which is responsible for doing exactly this.  It will make your life easier, but I am not advocate for  this as there are better ways doing this using Javascript on the client.

Anyway, here is how you can go about this in a few short lines of code

View:

@Ajax.ActionLink("display", "Display", new AjaxOptions())

@Html.TextBox("name","Pius")

@Ajax.ActionLink("checks", "Sample", new AjaxOptions())

Controller:


public JavaScriptResult Display()

{

const string script = "$('#message').append('Display');";

return JavaScript(script);

}

public JavaScriptResult Sample()

{

string script = "var textboxvalue=$('#name').val();";

script += "$('#message').append(textboxvalue);";

return JavaScript(script);

}

Output:

1) Clicking on the first link will display Display in the message div.

2) Clicking on the second link will display mazhar in the message div.

Happy coding and see you here again 🙂

Upgrading ASP NET MVC 3 to ASP MVC 4

Recently, asp net mvc 4 has been released, and it happened that i wanted to convert my mvc 3 application to mvc 4.  The steps are really easy since all you need is to change the configuration files of the application

  1. To manually upgrade an existing ASP.NET MVC 3 application to version 4, do the following:
    1. In all Web.config files in the project (there is one in the root of the project, one in the Views folder, and one in the Views folder for each area in your project), replace every instance of the following text (note: System.Web.WebPages, Version=1.0.0.0 is not found in projects created with Visual Studio 2012):System.Web.Mvc, Version=3.0.0.0
      System.Web.WebPages, Version=1.0.0.0
      System.Web.Helpers, Version=1.0.0.0
      System.Web.WebPages.Razor, Version=1.0.0.0

      with the following corresponding text:

      System.Web.Mvc, Version=4.0.0.0
      System.Web.WebPages, Version=2.0.0.0
      System.Web.Helpers, Version=2.0.0.0,
      System.Web.WebPages.Razor, Version=2.0.0.0,

    2. In the root Web.config file, update the webPages:Version element to “2.0.0.0” and add a newPreserveLoginUrl key that has the value “true”:<appSettings>
        <add key=”webpages:Version” value=”2.0.0.0″ />
        <add key=”PreserveLoginUrl” value=”true” />
      </appSettings>
    3. In Solution Explorer, right-click on the References and select Manage NuGet Packages. Search for Microsoft.AspNet.Mvc and install the Microsoft ASP.NET MVC 4 package. Click OK.
    4. In Solution Explorer, right-click the project name and then select Unload Project. Then right-click the name again and select Edit ProjectName.csproj.
    5. Locate the ProjectTypeGuids element and replace {E53F8FEA-EAE0-44A6-8774-FFD645390401} with {E3E379DF-F4C6-4180-9B81-6769533ABE47}.
    6. Save the changes, close the project (.csproj) file you were editing, right-click the project, and then select Reload Project.
    7. If the project references any third-party libraries that are compiled using previous versions of ASP.NET MVC, open the root Web.config file and add the following three bindingRedirect elements under the configuration section:

      <configuration>
        <!–… elements deleted for clarity …–>
         <runtime>
          <assemblyBinding xmlns=”urn:schemas-microsoft-com:asm.v1″>
            <dependentAssembly>
              <assemblyIdentity name=”System.Web.Helpers” 
                   publicKeyToken=”31bf3856ad364e35″ />
              <bindingRedirect oldVersion=”1.0.0.0″ newVersion=”2.0.0.0″/>
            </dependentAssembly>
            <dependentAssembly>
              <assemblyIdentity name=”System.Web.Mvc” 
                   publicKeyToken=”31bf3856ad364e35″ />
              <bindingRedirect oldVersion=”1.0.0.0-3.0.0.0″ newVersion=”4.0.0.0″/>
            </dependentAssembly>
            <dependentAssembly>
              <assemblyIdentity name=”System.Web.WebPages” 
                   publicKeyToken=”31bf3856ad364e35″ />
              <bindingRedirect oldVersion=”1.0.0.0″ newVersion=”2.0.0.0″/>
            </dependentAssembly>
          </assemblyBinding>
        </runtime>
      </configuration>

Easy 🙂 You have you application on asp net mvc 4. Hope you enjoy!!

Using Json.NET to implement your own json serializer (ASP NET MVC)

When working with even the latest version of ASP NET MVC 4, there are times when you will need to return Json from you controllers.  In this case the framework utilizes the JavascriptSerializer. This is the default for ASP NET MVC unlike the ASP NET WEB API which uses Json.Net

Also worthy noting is that JsonValueProviderFactory uses the JavascriptSerializer to deserialize request body to action parameters.  My problems with JavascriptSerializer on ASP NET MVC  as follows:

1.  The date format that is returned: Most of the times I have come across this date format ( Date(1365850930898)).

2. Circular reference which is a common issue when working with Entity framework. Though there are work around for this like disable lazy loading, its not an ideal solution as lazy loading is one for main reason for the ORM like EF.

To solve all these related issue, JSON.NET comes into play as it has solution to these issues. Actually JSON.NET is the default json serializer for ASP NET WEB API.

Without further ado, I will go straight to explain how to go about these issues:

The first step is to implement our own custom json serializer which extends the JsonResult class

public class CustomJsonResult : JsonResult
{
public CustomJsonResult()
{
Settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Error
};
}

public JsonSerializerSettings Settings { get; set; }

public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");

if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("Json get is not supported");

var response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType;

if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;

if (Data == null)
return;

var scriptSerializer = Newtonsoft.Json.JsonSerializer.Create(Settings);

using (var sw = new StringWriter())
{
scriptSerializer.Serialize(sw, Data);
response.Write(sw.ToString());
}

}
}

And since i write working with base controller where I can share all common functionality I have implemented a base controller as follows

<pre>public class BaseController : Controller
{
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding)
{
//Lets return our new custom result
return new CustomJsonResult
{
Data = data,
ContentEncoding = contentEncoding,
ContentType = contentType,
};
}
}</pre>

Here is my home controller which first first uses the JsonResult

<pre>public JsonResult Products()
{
return new JsonResult
{
Data = DummyOrders(),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}</pre>

jsonresult

So to test my custom serializer I charged the action as follows

<pre>        //Action to test our new custom result
public CustomJsonResult Products()
{
return new CustomJsonResult
{
Data = DummyOrders(),
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Settings =
{
ReferenceLoopHandling = ReferenceLoopHandling.Error
}
};
}</pre>

And here is the result

customjsonresult

 

 

 

 

 

So comparing the two result you can actually look at the date returned.

Kind reading and let me know you thougts

 

Download code from  here

%d bloggers like this: