Tag: ASP.Net

Continuous Integration/Deployment Using GitHub, AppVeyor & Microsoft Azure Websites

There are plenty of tools available these days that a developer or development team can use to set up continuous integration/deployment.  AppVeyor is one such tool that I first heard about last spring (May 2014) when reading a post by Scott Hanselman entitled “AppVeyor – A good continuous integration system is a joy to behold“.   I thought it sounded pretty interesting and so I gave it a try.  It was so easy and simple to set up that I had builds up and running in 15 minutes and I had it deploying to my Azure Websites account in under 30 minutes!

Getting up and running is straight forward assuming you already have GitHub and Azure accounts. These aren’t hard to set up either, but for the purpose of this demo I’ll be assuming you already have one of each.  (Everyone does right?)  To demonstrate how to get things set up I have created a little demo site and checked it into GitHub.  It’s a very simple project which is basically the default ASP.NET MVC template.  I’ve stripped out a few of the endpoints, changed the text on the one remaining page and added in some unit tests that can be run as part of our build.  I’ll probably add onto this site later for other demos or just for fun, but for now this will be adequate for us to take a look at the build and deployment process using GitHub, AppVeyor and Microsoft Azure Websites.

Getting Set Up On AppVeyor

Now that we have an ASP.NET project on GitHub we can get started setting up AppVeyor to build our project.  The first step is to set up our account.  At the time of this writing there is a big green button labeled “SIGN UP FOR FREE” right on the home page.  Click that button, select a plan (I’m choosing the “Free – for open-source projects” option), and choose log in with GitHub.  You can also select BitBucket or Visual Studio Online if you would like to use one of those services instead.  I have not tried them, but I would assume they work exactly the same.

AppVeyor Sign Up Screen

Once you log into GitHub you will be presented with an authorization screen from GitHub.com asking you to confirm that you would like to authorize AppVeyor to access your account.  Click “Authorize application” to authorize AppVeyor and continue with set up.

GitHub Authorization ScreenNext you’ll see the project screen which will be empty at this time except for large item that says “+ NEW PROJECT”.  Click this link to add a new project to your account.   This will take you to a page to select the source control repository you would like to pull from.  The page will default to GitHub and after a few seconds your GitHub Repositories will appear.  If you now hover over the repository you would like to add a button will appear to the right so that you can add the repository.  Click the add button.

Select Repository GitHub - Add

Your First Build

At this point you should have things configured enough to build your repository.  Simply click the “New Build” button on the right to start a build!

Build QueuedNotice that the build is now queued up, the site has pulled in the commit message, time and author and it has automatically incremented our version number to version 1.0.1.  We can manipulate these version numbers in the settings if we wish as well allowing us to make it version 2.0, 2.1, etc.  The server will simply keep incrementing the build number.

Once the build actually begins we will be able to view the console output.

Build Console Output

And once it completes we will get a success or failure message.

Build Success

Notice the green “Build Success” message.  We now have everything configured and any time we commit on the master branch a build will be triggered.  We can customize the branches that build etc. in the settings which I will dig into in a later post.

Also note here that the server has automatically detected and run our unit tests!  Had any of our tests failed the server would have failed the build as well.

Setting Up Azure Websites

The first thing we will need to do in order to deploy our site to Azure is create the site in Azure.  If you already have done this or your site is already live on Azure go ahead and skip ahead to the next step – Configuring Deployment.

Start off by going to the Microsoft Azure Portal (https://manage.windowsazure.com/) and once you are logged in click the “WEBSITES” link on the left side bar and then click the New button in the lower left corner.

Portal Websites

A panel will appear at the bottom of the screen.  Select “COMPUTE”, “WEBSITE” & “CUSTOM CREATE”.

New Compute Website Custom Create

Enter a URL for your website and click the check mark button.

Custom Create Dialog

After a little churning your site will be created.  While we are here there is a little piece of information we will need later, so let’s get that now.  Click on your new site in the websites list to view the details.

Website details

Now click the “Download the publish profile” link on the right side of the page and save it off to your local disc for later use.

Configuring Deployment

To configure your deployment go back to AppVeyor, select your project, click settings and then when the settings page loads go to the build section (third item down the left side).  You’ll need to be sure the option “Package Web Application for Web Deploy” is checked and then save your changes.

Build Settings - Package for MS Deploy

Next go down to the Deployment section (three more items down).  First click “Add Deployment” to add your first deployment and get started configuring it.  You’ll need to select the “Web Deploy” deployment provider.  This is where we need the info in the publish settings file we saved earlier.  Specifically we need the settings publishUrl,  msdeploysite, username, and userPWD.  These values go into the fields in the deployment section as follows:

Server = https: //[publishUrl]/msdeploy.axd?site=[msdeploySite]
Website Name = [msdeploySite]
Username = [username]
Password = [userPWD]

You will also want to turn off NTLM.

Deployment Settings

Click the “Save” button and we should be ready to give it a try.  To start a new build click “LATEST BUILD” and then “NEW BUILD”.  Assuming we’ve done everything correctly a build of your project will queue up and if it is successful it should deploy to you site on Microsoft Azure.

The site is at: http://dependencyinjector.azurewebsites.net/
The GitHub Repository is at: https://github.com/dependencyinjector/dependencyinjector
The AppVeyor Build Information is at: https://ci.appveyor.com/project/lahouse/dependencyinjector

Resources

Documentation:
http://www.appveyor.com/docs/deployment/web-deploy#provider-settings

Scott Hanselman’s Blog Post: http://www.hanselman.com/blog/AppVeyorAGoodContinuousIntegrationSystemIsAJoyToBehold.aspx

ASP.NET 5 / ASP.NET vNext – Resources

ASP.NET 5 is a major rethinking of .NET on the server.  It’s cross platform (it can be run on Linux or Mac as well as Windows), cloud ready, modular,  has a unified MVC / Web API / Web Pages programming model, allows you to self host your application or to host in IIS in the traditional manner, and of course it’s open source (Apache 2.0) on GitHub.  It’s a lean, mean modern web development stack that will run anywhere.

Getting Started

The best way to get started is to head over to www.asp.net/vnext and start digging in.  There’s tons of content to help wrap your head around the new world and to get you going in the right direction, and while you’re there you download the CTP of Visual Studio 2015 as well or you can grab it off of Visual Studio.com.

The Weekly Community Stand Up

The team is hosting a weekly community standup where they discuss what is new and where they are headed.  Each stand up is about 20 to 30 minutes long and packed with loads of information about what is coming and what the thought process is behind the decisions the team is making.

Channel 9 Videos

Channel 9 has a nice little series of videos on ASP.NET 5 that are hosted by Scott Hanselman  and various team members including Rowan Miller from the Entity Framework team.  (Check out Scott’s Blog too.  He has a posted a few articles on ASP.NET 5 / vNext)

What’s New with ASP.NET 5: (01) ASP.NET 5 What and Why

What’s New with ASP.NET 5: (02) ASP.NET MVC + Web API Part 1

What’s New with ASP.NET 5: (03) ASP.NET MVC + Web API Part 2

What’s New with ASP.NET 5: (04) Visual Studio Tooling for ASP.NET 5

What’s New with ASP.NET 5: (05) ASP.NET 5 Internals Deep Dive

What’s New with ASP.NET 5: (06) Entity Framework 7

And this video on the Open Sourcing of the .NET Framework.

Immo Landwerth and David Kean – Open sourcing the .NET Framework

.NET Blog

You might also want to keep an eye on the .NET Framework Blog for all the latest news.

Setting Up Dependency Injection in ASP.NET MVC with AutoFac

There are lots of IOC (Inversion of Control) containers out there that you can use to do dependency injection in your ASP.NET MVC project.  Honestly, most of them are pretty good, and having chosen to use one is really far more important than which one in most cases.  Having said that, there can be some significant differences in performance and features.  I typically use Autofac because it is one of the fastest and it can reliably and automatically call Dispose() on the IDisposables that it creates in a per http request scope.

Adding Autofac To Your Project

Thanks to the magic of NuGet, you can quickly and painlessly add Autofac to your solution and get started.  In my example here I’ll be adding Autofac support to an ASP.NET MVC 5.2 web application with Web API 2.2.  To do that I’ll need to add 2 packages to my project, Autofac ASP.NET MVC 5 Integration (Id: Autofac.Mvc5 / Version: 3.3.3) and Autofac ASP.NET Web API 2.2 Integration (Id: Autofac.WebApi2 / Version: 3.4.0) .  Adding those packages will add the dependent package Autofac (Id: Autofac / Version 3.5.0), which is the actual core Autofac assembly.  Once completed I have the following packages installed:

ASP.NET MVC AutoFac NuGet Packages

Configuring The Container

Now that we have the packages installed we will need to configure our IOC container and register it with the system.  In keeping with the pattern already in place for handling start up application configuration in ASP.NET MVC, I add a DependencyConfig class to the App_Start folder of my MVC project.  This is a static class that has only a single public method named RegisterDependencyResolvers() and two private methods.

public static IContainer RegisterDependencyResolvers()
{
    ContainerBuilder builder = new ContainerBuilder();
    RegisterDependencyMappingDefaults(builder);
    RegisterDependencyMappingOverrides(builder);
    IContainer container = builder.Build();
    // Set Up MVC Dependency Resolver
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    // Set Up WebAPI Resolver
    GlobalConfiguration.Configuration.DependencyResolver= new AutofacWebApiDependencyResolver(container);
    return container;
}

In the above code snippet line 3 creates a container builder that we will use to configure and create our IOC container.  Lines 4 and 5 call our private methods to configure the type mappings our container will use, we’ll circle back to that in just a minute here.  Line 6 actually creates our Autofac container and line 8 registers a new AutofacDependencyResolver (using our container) as the dependency resolver for ASP.NET MVC.  That means that not only have we set up a dependency resolver for services that we need in our code, but also for the services that ASP.NET MVC will need as well.  For example when ASP.NET needs to create an instance of a controller to handle requests to our site, it will use the container we just created to create an instance of that controller (and all of it’s dependencies).  Line 10 does the same thing as line 8, but this time it is registering a dependency resolver with the WebAPI engine.  Finally line 11 returns an instance of the container we created.  I sometimes use this for unit testing that the dependency mappings have been set up correctly.

Registering Types With The Container

In order for the Autofac container to resolve the dependencies we need we’ll need to tell it what to use for the implementation of the service interfaces our items require.  This is not the only way to do this, but it is the way I prefer and it seems to work out pretty well.  In the first method below we are going to create some global registrations to put in place some general rules so we don’t have to explicitly specify the type for every single thing we need.

private static void RegisterDependencyMappingDefaults(ContainerBuilder builder)
{
    Assembly coreAssembly = Assembly.GetAssembly(typeof (IStateManager));
    Assembly webAssembly = Assembly.GetAssembly(typeof (MvcApplication));
    builder.RegisterAssemblyTypes(coreAssembly).AsImplementedInterfaces().InstancePerRequest();
    builder.RegisterAssemblyTypes(webAssembly).AsImplementedInterfaces().InstancePerRequest();

    builder.RegisterControllers(webAssembly);
    builder.RegisterModule(new AutofacWebTypesModule());
}

On lines 3 & 4 I am getting a reference to the assemblies that contain types I want to register in my solution.  In this case I have a core assembly that contains my models and logic and a web assembly which contains my web UI (Controllers, Views, etc…).  Lines 5 & 6 register every type in the assembly as the implementation for any interface they implement.  Let’s assume that I have a class Foo that implements the IBar interface in one of these assemblies.  With this registration I have registered Foo as the implementation of IBar and if I ask the container to resolve an IBar it will give me an instance of Foo.  It also means that if I ask the container to resolve an item that requires an IBar as a constructor parameter that it will create a Foo and pass it into the constructor of the type I am asking for.   The last part of these two lines defines the lifetime or scope of the objects created.  In this case we are specifying InstancePerRequest.  That means that the container will create one instance of any given type per http request and use it to fulfill any requests for that type.  At the end of the request any objects created will be destroyed.  There are a number of scopes you can choose.  InstancePerRequest and SingleInstance are the two I use the most.  See the docs for more details.

Line 8 registers the MVC Controllers in the web assembly so that ASP.NET can use our resolver to resolve them.  Line 9 then registers an Autofac Module with the container that allows the container to resolve certain web types (like HttpContextBase) so that they can be injected into our classes. (This makes it much simpler to mock & unit test our classes that depend on these web types!)

Now that we have our global registration in place we will probably want to be specific in a few cases.  For example, if you have more than one implementation of a given interface you may want to be specific about which one to use (FYI: last one registered wins…), or you may want certain objects to be create in a different scope as I have done below.

private static void RegisterDependencyMappingOverrides(ContainerBuilder builder)
{
    builder.RegisterType<WebSettingManager>().AsImplementedInterfaces().SingleInstance();
}

In this case I have registered the WebSettingManager class as the implementation of it’s interface(s) and set it to use a SingleInstance scope effectively making it a singleton that lives across http requests.

Final Set Up – The Global.Asax

The last thing you will need to do is actually invoke the RegisterDependencyResolvers method during application start up so that everything gets hooked up properly.

In your global.asax file in Application_Start you will need to add one line of code.

DependencyConfig.RegisterDependencyResolvers()

Here is the entire DependencyConfig.cs

public static class DependencyConfig
{
    public static IContainer RegisterDependencyResolvers()
    {
        ContainerBuilder builder = new ContainerBuilder();
        RegisterDependencyMappingDefaults(builder);
        RegisterDependencyMappingOverrides(builder);
        IContainer container = builder.Build();
        // Set Up MVC Dependency Resolver
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        // Set Up WebAPI Resolver
        GlobalConfiguration.Configuration.DependencyResolver=new AutofacWebApiDependencyResolver(container);
        return container;
    }

    private static void RegisterDependencyMappingDefaults(ContainerBuilder builder)
    {
        Assembly coreAssembly = Assembly.GetAssembly(typeof (IStateManager));
        Assembly webAssembly = Assembly.GetAssembly(typeof (MvcApplication));

        builder.RegisterAssemblyTypes(coreAssembly).AsImplementedInterfaces().InstancePerRequest();
        builder.RegisterAssemblyTypes(webAssembly).AsImplementedInterfaces().InstancePerRequest();

        builder.RegisterControllers(webAssembly);
        builder.RegisterModule(new AutofacWebTypesModule());
    }

    private static void RegisterDependencyMappingOverrides(ContainerBuilder builder)
    {        
        builder.RegisterType<WebSettingManager>AutofacDependencyResolver()
                  .AsImplementedInterfaces().SingleInstance();
    }
}

Resources

Project Home Page: http://autofac.org/

Project Documentation: http://autofac.readthedocs.org/en/latest/#

Project Source Code: https://github.com/autofac/Autofac

NuGet Packages: http://www.nuget.org/packages?q=autofac

The Build Wrap Up

Unfortunately, as is often the case at a large developer conference, the Internet connection gave out on Friday morning and I was unable to make my post for Thursday’s sessions.  I attended a couple of more sessions Friday and left directly from the conference for the airport and didn’t arrive home until after 2am Saturday.  Now that I am back home and settled in, Let’s just do a wrap up of the conference.

On Thursday & Friday I attended a few really good sessions, specifically “Future Directions for C# and Visual Basic” presented by Anders Hejlsberg, “Creating immersive data experiences with Entity Framework” presented by David Annsley-DeWinter & Jeff Derstadt, and “Building real-time web apps with HTML5 WebSockets” presented by Ravi Rao.

Of the Sessions I attended I would recommend watching the following if you missed them:

One of the sessions I was looking forward to on Thursday was cancelled (Building IIS and ASP.NET apps with the power of async – Damian Edwards and Phil Haack).  I believe they are planning on recording the session once back in Redmond, so I’ll post a link when I see the video.

Windows 8 Developer Preview

If you were not lucky enough to attend Build and receive a Window 8 Developer Preview PC you can download the Windows 8 Developer Preview from http://msdn.microsoft.com/en-us/windows/apps/br229516.  Scott Hanselman has a good article on how to set up a Windows 7 PC to boot from Virtual Disk.  I have followed this guide and installed The preview on the PDC09 Laptop. It seems to work well so far.

Beta & technical preview downloads – Announced this week

Executive Conference Summary – Key Take Aways

The conference really revolved around the Release of Windows 8 Developer Preview and Building Apps for the new Metro Interface.

Microsoft has put significant effort into improving performance of the operating system for Windows 8.  Boot times seem to be much quicker, the UI seems very responsive and the memory footprint for the O/S has been cut nearly in half.

Windows 8 will ship with a new Windows App Store for Metro Apps.

The new Metro Interface looks a lot like the Windows Phone 7 Metro Interface.  When writing an application for Windows going forward you will have the choice of building a traditional Win32 (or .Net WinForms/WPF) app running on the desktop or a new Metro Style app running on the new WinRT (Windows Run Time).  The two environments cannot be mixed, the new Metro Style apps are sandboxed.  Also note that you cannot use GDI in Metro Style Apps, only Direct X.

As a web developer I spent most of my time attending the ASP.Net and Visual Studio 11 sessions, but there were a lot of great sessions on a whole range of topics around developing for Windows 8.  I would recommend checking out Channel9 on MSDN to learn more and watch the sessions.

In ASP.Net 4.5 Web Forms gets support for Model Binding,  Strongly Typed Data Controls, Support for Data Annotations.  All ASP.Net applications get better support for HTML 5 and CSS3, CSS Folding, auto tag matching, new improved design view support (borrowed from Expression Blend as I recall) along with a newly designed style in all the project templates. 

ASP.Net 4.5 also includes the ASP.NET Optimization – Bundling package which combines and minifies the CSS and JavaScript files in your Web Application.  This package is available as a Nuget Package for ASP.Net 4.0, so we can start using it today.