Home - About me - Browse by categories

Develop a blog using ASPNET vNext, Azure Website, DocumentDB and Search services - Part 1

Thanks to Adrien that reviews this blog post before I publish it !

Introduction

Few years ago I chose to develop my own blog instead of using a well-known blog engine like WordPress or DotNet Blog Engine, for example. Why? Because I use it as a sandbox project to test new Microsoft technologies. Today this blog is running in a Microsoft Azure Website, using SQL Database and Azure storage and is developed with ASP.NET MVC 5. I’m currently rewriting it with ASP.NET vNext (MVC 6), Azure DocumentDB and Azure Search. In this blog post series I will describe how I use these technologies to put the new version of my blog online Smile## Getting started with ASP.NET vNext

What is ASP.NET vNext ?

ASP.NET vNext (also known as Project K) will be a really big change for developers because it has been redesigned from the beginning. ASP.NET has always been an awesome and powerful technology to develop web applications but today, after a lot of evolutions, it is very monolithic and has a big memory footprint even to create a simple web application. One of the goal of the ASP.NET team was to reduce this footprint and make the framework more composable, instead of having a huge library that contains a lot of (needed) stuff: System.Web. ASP.NET vNext comes with ASP.NET MVC 6, a web application Framework that merges ASP.NET MVC, Web API and Web Pages. Applications will be host agnostic exactly as ASP.NET Web API is today: you can host it in IIS, or self-host it in a console application, for example. Because the Framework is totally composable, you will have to change some of your development habits. ASP.NET vNext projects use NuGet to resolve all dependencies, even .NET Framework dependencies. One of the coolest thing (IMO) that comes with this new version is the Cloud Optimized .NET Framework: an 11MB Framework divided into a set of NuGet packages that you can include (or not) in your project. That contributes to reduce the memory footprint of your applications but also allow to run applications that use different versions of the .NET Framework side-by-side. ASP.NET vNext uses the Roselyn compiler to build web applications dynamically so it comes with a better development experience. You can choose your editor and your favorite platform to develop your application. The ASP.NET team has worked with the Mono team to make ASP.NET vNext and the Roselyn compiler available on Mac and Linux: come as you are and develop web app with ASP.NET! Even if it looks like being a huge update of ASP.NET (and it is!), don’t be afraid: if you know ASP.NET MVC or Web API, you will develop with ASP.NET vNext finger in the nose J If you don’t know ASP.NET MVC, take the time to read some stuff about it before this article. ### Wow, that looks awesome, how do I start ?

Currently, one of the ways to develop ASP.NET vNext is to download the latest CTP of Visual Studio 14 from this page. You can also use one of the templates available in the this page. Once you have Visual Studio 14 CTP (or your favorite IDE, for those who are using a Mac, this article may be helpful: this page) you are ready to develop with ASP.NET vNext. ## Create the services on Azure portal

The blog uses different services on Microsoft Azure: - Website : the blog application host - Storage account : images displayed in the blog posts are stored in the Azure blob storage - DocumentDB : a NoSQL document database used to store the blog posts - Search : service that provides fast-search indexing and querying, used to search in blog’s posts

All these services are currently available on the preview of the new Azure Portal. You can access it at http://portal.azure.com. One of the coolest features that comes with this new portal is the possibility to group resources by business application into resource groups. So in the example of the blog it is possible to regroup each service instance in a single group and manage them together. Also, resource groups are very useful to get a pricing overview of your business app. After selecting your subscription, click on the + button at the bottom left of the portal and choose to create a new website. First, you have to name the website. Next you can choose a hosting plan that will determine the pricing rules that will apply for billing (I choose free plan in this case). Now you can create a new resource group: <ol> - Click Resource group - Click Create a new resource group - Give a name to the group and click OK </ol> image

Choose the subscription and the location where you want to create the website. I choose West Europe. Finish the website creation by clicking on Create. While the website is being created, click the + button again to add a new Storage account resource. Choose a name, the tiers you want and select the resource group that you have created with the website: image

Click Create to finish the Storage account creation. Add a new DocumentDB to the resource group. Click the + button, choose DocumentDB in the list. Give it a name, select the good resource group and the location where your want to create it: image

Finish the creation by clicking on Create. Notes: DocumentDB and Search services are currently in preview. If you don’t see them in the Azure Portal, you have to activate them on your subscription via the preview features portal.Create a new Search service in the resource group: click the + button, choose Search in the list. Give it a name, choose the tiers, the resource group and the location where you want to create it: the preview features portal

Conclusion

Your environment is now ready to develop with ASP.NET vNext, Azure Website, DocumentDB and Search services. In the next post, we will create the blog domain model and develop the data access services on Azure DocumentDB. Julien Winking smile

read more

Run background tasks in aspnet applications with dotnet Framework 4.5.2

Few days ago Microsoft has announced the availability of the .NET Framework 4.5.2. This new version brings some new features and improvements to ASP.NET. It is now very easy to run some background tasks from an ASP.NET Web app, using the new HostingEnvironment API. It allows to enqueue background tasks (as simple as working with the thread pool) and avoids IIS app pools shutdown until the tracked tasks are completed.

For a complete description of this new .NET Framework version, go to this page. You can find the runtime and developer pack installers this page.

Once you’ve installed .NET Framework 4.5.2 and the developer tools, open Visual Studio and create a new web application project that targets the .NET Framework 4.5.2 :

image

In this post, I have choose to use the HostingEnvironment api to queue thumbnail generation when the user uploads a picture (really simple scenario). The HostingEnvironment class defines a method QueueBackgroundWorkItem that takes an Action or a Func<CancellationToken,Task> as parameters.

To generate the thumbnail I have used the System.Drawing API and created the following simple helper :

public class ThumbnailHelper
{
public static Task CreateThumbnail(string filePath)
{
return Task.Factory.StartNew(() =>
{
Image originalImage = Bitmap.FromFile(filePath);

int thumbWidth, thumbHeight;

thumbWidth = 250;
thumbHeight = (originalImage.Height * 250) / originalImage.Width;

Image thumbnail = originalImage.GetThumbnailImage(thumbWidth, thumbHeight, null, IntPtr.Zero);

string thumbFileName = string.Format("{0}_thumb{1}", Path.GetFileNameWithoutExtension(filePath), Path.GetExtension(filePath));
string thumbFilePath = Path.Combine(Path.GetDirectoryName(filePath), thumbFileName);

thumbnail.Save(thumbFilePath);
});
}
}

The cshtml code :

@{
ViewBag.Title = "Upload a new picture";
}

## @ViewBag.Title

@using(Html.BeginForm("Upload", "Picture", FormMethod.Post, new{ enctype = "multipart/form-data"}))
{
@Html.AntiForgeryToken()
<div class="form-group">
<label for="file">Choose a picture</label>
<input type="file" name="file" id="file" />

<div class="form-group">
<input type="submit" value="Upload and create thumbnail" class="btn btn-primary"/>

}

and the controller code :

public class PictureController : Controller
{
public ActionResult Upload()
{
return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase file)
{
var appDataPath = Server.MapPath("~/App_Data");
string filePath = Path.Combine(appDataPath, file.FileName);
file.SaveAs(filePath);

HostingEnvironment.QueueBackgroundWorkItem(cancellationToken =>
{
return ThumbnailHelper.CreateThumbnail(filePath);
});

return RedirectToAction("Upload");
}
}

As you can see in the code above, just after that the picture is saved in the App_Data folder, a task is queued using the HostingEnvironment api. Now, you can be sure that the app pool of your application will not stop until all the thumbnails are generated.

Hope this helps Winking smile

Julien

read more

Developping web applications with WinJS

As you maybe heard this week at the day 1 keynote of the //Build 2014, Microsoft has announced that WinJS is now open source and available for web applications and not only Windows / Windows Phone apps ! It offers the possibility to develop WinJS apps for other devices than Windows devices. I think the opportunity is really cool Sourire

WinJS sources are available on github and you can use it in your web apps now. It consists in a set of controls like ListView, FlipView, DatePicker, Hub… and more that can be used in simple web applications.

You may find a lot of samples at http://try.buildwinjs.com/

If you want more information about the WinJS roadmap, you’ll may be interested in watching this webcast from //Build 2014 :

Enjoy Clignement d'œil!

Julien

read more

Renewed as Microsoft MVP ASPNET IIS for 2014

Yesterday I have been renewed as Microsoft MVP ASP.NET / IIS for one more year ! I am really happy to be an MVP for the 5th year Smile

image

A big thank you to Microsoft for my renewal.

Currently, I work mainly on Microsoft web technologies and Microsoft Azure. I will continue to blog about these topics whenever I think something I did might be interesting for others. If you read French, you may also be interested in following my french blog : http://blogs.infinitesquare.com/b/beedoo !

Stay tuned Winking smile

Julien

read more

Using OWIN to test your web api controllers

During the Microsoft Techdays in Paris, I spoke with Simon Ferquel about the newest features that came with ASP.NET MVC 5 and Web API 2. A big part of our session was about OWIN that is (IMO) one of the most exciting feature that has been released.

Introduction to OWIN middleware programming

###

In short, OWIN (Open Web Interface for .Net) is a set of specifications that define how a web application runs on a web server. You can find more about these specifications on this page.

OWIN is based on middlewares to add behaviors to an application. For example, you can use OWIN middlewares to do external authentication with providers like Facebook, Google, Microsoft or Windows Azure Active Directory. You can also use OWIN middlewares as simple technical components of your application (logs, for example). Each OWIN middleware is responsible for its business.

Working with OWIN is very easy : first you have to write your OWIN middleware (or not, if you’re using an existing one provided by Microsoft or another third party).

An OWIN middleware is represented by a class that inherits from OwinMiddleware, as it is done for the LogsMiddleware bellow :

public class LogMiddleware : OwinMiddleware
{
public LogMiddleware(OwinMiddleware next) : base(next)
{

}

public async override Task Invoke(IOwinContext context)
{
Debug.WriteLine("Request begins: {0} {1}", context.Request.Method, context.Request.Uri);
await Next.Invoke(context);
Debug.WriteLine("Request ends : {0} {1}", context.Request.Method, context.Request.Uri);
}
}

As you can see, an OWIN middleware takes the next middleware to invoke as constructor parameter. You should next override the Invoke method that will do the middleware stuff and invoke the next middleware.

The sample above is very simple : it logs the begin and the end of each request that is made to the server. Once the middleware is ready, you only have to register it in your application and it will be available for all technologies in your app (mvc, web forms, web api, signalR…) : you write one middleware to rule them all ! Winking smile

To register OWIN middlewares in your app, you have to create an OWIN Startup Class. You can use a Visual Studio template to create this class (or you can use the one that has been created at the project creation if it already exists) and all the structure of the class :

image

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(EbookManager.Web.Startup))]
namespace EbookManager.Web
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{

}
}
}

An OWIN startup class is very simple : it contains a method Configuration that returns void and takes an IAppBuilder instance as parameter. To make the class visible from OWIN, you should use the attribute OwinStartupAttribute at the assembly level and reference the type of the startup class. Now, you can register the log middleware and test your first OWIN middleware :

public void Configuration(IAppBuilder app)
{
app.Use(typeof(LogMiddleware));
}

And that’s all : your application will now use the log middleware via OWIN.

OWIN Self-Hosting

One of the other cool exciting feature of OWIN is the ability to self-host code like Web API or Signal-R :

image

Microsoft provides different hosts that can run OWIN applications. The first one that everybody knows is IIS server that runs ASP.NET for many years. But Microsoft provides two other hosts : the http listener that allows to self-host a web api or a signal-r hub in a .NET application (for example a windows service or a console application) and the unit test host that allows to unit tests web api controllers without server-deployment.

Using the unit test host

To work with the OWIN Unit Test host, you have to install the NuGet package Microsoft.Owin.Testing in your test project :

image

Once the package is installed, it is possible to create a test server that will host your web api without running IIS. To do that, you have to create an OWIN configuration class in the projet. This class is defined in the same way than an OWIN startup class except that you do not have to register it at the assembly level with the OwinStartupAttribute :

class OwinTestConf
{
public void Configuration(IAppBuilder app)
{
app.Use(typeof (LogMiddleware));
HttpConfiguration config = new HttpConfiguration();
config.Services.Replace(typeof(IAssembliesResolver), new TestWebApiResolver());
config.MapHttpAttributeRoutes();
app.UseWebApi(config);
}
}

Here, the configuration is done in the same way that you are use to configure an api written with Web API 2. The TestWebApiResolver is an assembly resolver that allows Web API to resolve controllers that are defined in another assembly than the one that defines unit tests.

Now, it is possible to create a test server based on the OWIN configuration in your unit test and use it like any Web API, for example with an HttpClient :

using (var server = TestServer.Create<OwinTestConf>())
{
using (var client = new HttpClient(server.Handler))
{
var response = await client.GetAsync("http://testserver/api/values");
var result = await response.Content.ReadAsAsync<List<string>>();
Assert.IsTrue(result.Any());
}
}

As you can see in the sample bellow, the HttpClient takes an custom handler that is provided by the OWIN test server. This is this step that allows us to bypass the use of the http protocol and that allows the tests to run without IIS.

Conclusion

I think that the ability to self-host a Web API in a test server to make unit test is a very cool feature because it really simplifies the process.

In my next post, I’ll discuss about testing a Web API that uses OAuth with OWIN.

If you’re interested in reading source code, you’ll find samples of OWIN usages in this project on github (this is the sample application we use at Microsoft Techdays).

Enjoy Winking smile

read more