Microsoft Virtual Academy – A Lap Around Azure Websites - All the Questions and Links From the Talk

On January 14th, 2015 Jon Galloway and Cory Fowler presented a live “Lap Around Azure Websites” on Microsoft Virtual Academy. I was the online “Community Expert” for the live event and fielded questions in the chat.

Some questions were more easily answered just by sharing a link! Here are the links that I mentioned in the chat or that were cited by Jon and Cory:

As well, here are some other really great MVA sessions you should take advantage of:

  • Building Apps with Node.js Jump Start (Course)
  • Introduction to Creating Websites Using Python and Flask (Course)
  • What’s New in Visual Studio 2013 Jump Start (Course)
  • Microsoft Azure Fundamentals (Course)

And, if you’re into the whole reading thing, I published a book on Azure Websites that is still really relevant, in spite of all the new features and changes the portal’s seen.

The Common and Predominant Questions

I grabbed the questions that stood out the most from the chat and am posting them below, along with my answers.

Can Javascript run on .NET platform also?
No, JavaScript doesn’t run natively on .NET. But Azure != .NET, and Azure Web Sites has many options for web stacks, including Node.js. Remember that JS has traditionally been a client-side language, so it of course can be used in any web application created with .NET

Do we need SDK’s and command line tools with Visual Studio 2015 Preview.
No, you don’t need it. But the SDK adds some extra (really useful) tooling, and the command line tools gives you options from a console or PowerShell script.

What are your thoughts on using WebMatrix? How does it compare to VS in terms of workflows you are going to talk about?
WebMatrix is a great tool for working with non-.Net stacks and has language support beyond what you’ll find in VS. However, if you’re working with .NET langauges (as well as many other non-.NET languages), VS gives you probably the IDE experience, hands-down.

When signing up for the free trial on Azure Websites it still asks me for entering my credit card details on the trial registration page. Is it going to charge me?
Even if they do collect the CC info, there will no charges. By default there is a spending limit of $0 on your account. Unless you remove that, there will not be any charges incurred. You can sign up with confidence!

How can you deploy to two Azure websites? One for Staging and another one for Production.
The easiest way is to use two different branches in source control, then you can automate everything about deployment to two entirely different websites. You can use slots and swapping to help with this.

My trial period has expired and I have converted my subscription to Pay-As-You-Go subscription. When will I have to pay something?
You’ll have to pay if you want to start adding “real-world” value to your project. Things like scaling, dedicated domain names, load balancing and the like.

Are MySQL databases hosted on Azure the same as SQL server? What’s the deal with these 3rd party partners? How is it different?
The third-party DB providers are from partners that may or may not use Azure resources. They provide an integration mechanism with Azure, but don’t necessarily spin up Azure resources. With MySQL, you just need a connection string to get at the data. It is not hosted on the same server as Azure SQL. And in the case of ClearDB, they are actually hosted on an Azure cluster.

_Should a team have their GIT repository in VS online or Azure for an Azure site?
_
There is no preference. In fact, I have on-prem git repos, VS Online hosted and even repos (the majority) hosted on GitHub. You are free to choose what works with your team.

Should I add my packages to .gitignore when working with GitHub and Azure Websites? Does Kudu install the packages for me? If so, wouldn’t it be faster to deploy by NOT adding the packages to .gitignore?
It’s possible that you might save time, but deploying to different regions may mean greater latency as you deploy. Local cached packages can be quickly retrieved by Kudu, which could result in time saving for you.

_Can I use the Kudu webhooks with a local githook from my Git repo? 
_
The webhook endpoint is exposed in the API, you can read more about it here.

How do deployment slots work? Can I use separate databases for different slots?
Slots can have their own configuration, so if you need different connection strings for the alternate slots, you can do that. This is also true of app settings and the like.

_What does Kudu do? _
Kudu is the deployment engine that powers Azure Websites. It’s grown into a great set of services that allow you to manage and customize your deployment process. There is a public API you can use in your own projects, integrate with other web hooks and more.

_How does the Kudu Console work in the Browser?
_
The cool bits to me (as a developer) is the continuous connection to the browser from the server. That’s all powered by SignalR, which is another open source project started by some MS folks. You can find the SignalR GitHub repo here.

What are the costs related to turning on tracing?
There is a very small percentage of a performance hit, but nothing really in terms of monetary costs, it’s included in the platform. The one potential thing to watch for is that there is a cap on website space and the logfiles will count towards that.

How do I analyze the data from my error logs on my site?
You can use the built-in support site from the scm sub-domain on your site. Just navigate to <yoursite>.scm.azurewebsites.net/support and select your hostname. From there, you can drill in and see error and troubleshooting information.

Can I use .NET 3.5 on Azure Websites?
Yes, this is an option from the configuration menu. The only trouble I’ve had in moving to AW is when you have legacy third-party components that need access to unsafe memory or the registry (not supported on websites).

Day 1 – The Basics of the Basics with Azure Table Storage

In this series we are looking at the basic mechanics of interacting with cloud-based Table Storage from an MVC 5 Application, using the Visual Studio 2013 IDE and Microsoft Azure infrastructure.

Before We Get Going…

Let’s not mince words here, the best way to develop in the cloud is with the best and most up-to-date toolset that we have available. You’re going to want to grab these prerequisites as a minimum foundation for following along in this series:

The Straight-Up Attack: Accessing Table Storage from Your Controller

Follow these quick steps to get started:

  • Create a new solution in Visual Studio using the ASP.NET Web Application project template

  • Right-click on your project in Solution Explorer, then Manage NuGet Packages and add “WindowsAzure.Storage” to your dependencies.
  • Alternatively, you can install the package from the Package Manager Console with the following command:
    Install-Package WindowsAzure.Storage

    The project is now prepped, so now we can add the needed code bits to start building our app. Let’s start by adding the following class to our project in the Models folder:

    public class KittehEntity : TableEntity
    {
    public KittehEntity(string kittehType, string kittehName)
    {

    <span class="kwrd">this</span>.PartitionKey = kittehType;
    <span class="kwrd">this</span>.RowKey = kittehName;
    

    }

    public KittehEntity() {}

    public string ImageUrl { get; set; }
    }

Next, replace the code in the HomeController with the code below. Note that you’ll need to add the namespace for the models to the usings at the top.

public ActionResult Index()
{
    var storageAccount = CloudStorageAccount.Parse(
        CloudConfigurationManager.GetSetting("StorageConnectionString"));

    var client = storageAccount.CreateCloudTableClient();

    var kittehTable = client.GetTableReference("PicturesOfKittehs");
    if (!kittehTable.Exists())
    {
        kittehTable.Create();

        var thrillerKitteh = new KittehEntity("FunnyKittehs", "ThrillerKitteh");
        thrillerKitteh.ImageUrl = "http://cdn.buzznet.com/assets/users16/crizz/default/funny-pictures-thriller-kitten-impresses--large-msg-121404159787.jpg";

        var pumpkinKitteh = new KittehEntity("FunnyKittehs", "PumpkinKitteh");
        pumpkinKitteh.ImageUrl = "http://rubmint.com/wp-content/plugins/wp-o-matic/cache/6cb1b_funny-pictures-colur-blind-kitteh-finded-yew-a-pumikin.jpg";

        var batchOperation = new TableBatchOperation();

        batchOperation.Insert(thrillerKitteh);
        batchOperation.Insert(pumpkinKitteh);
        kittehTable.ExecuteBatch(batchOperation);

    }

    var kittehQuery = new TableQuery<KittehEntity>()
        .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "FunnyKittehs"));

    var kittehs = kittehTable.ExecuteQuery(kittehQuery).ToList();

    return View(kittehs);
}
Admittedly, this is a bit of a naive approach because we’re mixing concerns here and putting storage access and table seeding in a single controller method, but I want to highlight the premise here without adding too much cruft. Through the rest of the series we’ll extract a service to do the heavy lifting and move back towards best practices.

What we’re doing above is the following: * Reading the connection string from our web.config

  • Configuring the client
  • Getting a reference to a table
  • If the table doesn’t exist (it won’t, first time), we build a batch operation and seed it with some data
  • We fetch all records with a “FunnyKittehs” partition key
  • We pass the data to the view

    Now, replace the code in the Views\Home\Index.cshtml with the following:

    @model IEnumerable<YourNamespace.Models.KittehEntity>
    @{
        ViewBag.Title = "Home Page";
    }
    
    @foreach (var kitteh in Model)
    {
        <div class="jumbotron">
            <h4>@kitteh.RowKey</h4>
            <img src="@kitteh.ImageUrl" />
        </div>
    }
    Note that you’ll need to update the namespace to match your project’s.

    Finally, add a connection string to the AppSettings section of your web.config. This will tell our app to use the local storage emulator provided by the SDK.

    <appSettings>
      <!-- other settings... -->
      <add key="StorageConnectionString" value="UseDevelopmentStorage=true;" />
    </appSettings>

    Finally, run the app! You should see a couple of adorable kittehs in your browser, rendered in a razor view, with data populated by the MVC controller with entities loaded from Azure Storage Tables.

    Next Steps

    In this post we injected a few entities into our table using a seed method, but what about adding new entities from the UI? In the next article, we’ll beef up the views and controller to allow users to add new documents to our storage account.

    _(Psst! If you’re just getting started with MVC and want to get your hands real dirty, check out my book on _Bootstrap and the MVC Framework_)._

  • Day 0: 8 Days of Working With Azure Table Storage from ASP.NET MVC 5

    Here’s a short and simple way to get started using Azure Table Storage from ASP.NET MVC 5. Following these brief, task-oriented articles will help you learn the mechanics of working with table storage and give you some pointers on how you might want to approach it in your app.

    We’re going to start with the basics, a simple MVC app with a controller that builds the table, inserts a couple of rows and then displays them.

    If you want to follow along, please pop into Azure and make sure you’ve got an account ready to go. The trial is free, so get at it!

    But then we’re going to expand on that, adding other operations to manipulate the data as well as the tables themselves, and then we’ll take it to the next level where we start to apply some better strategies around how we actually access the data.  After all, MVC is all about separation of concerns!

    Most of these principles will apply if you need to access a storage table from other areas of .NET as well…you could just as easily apply these to Web API, a console application or your next WinForms project. By the end, we’ll have extracted the important parts out into a reusable block of code that runs equally as well with the Azure Storage Emulator in your development environment as it does in production in the cloud.

    Working With Azure Table Storage – Our Agenda

    Check back for more on the series in the days ahead, all the links will be posted here.

    And hey, if you’d like to ramp up in your MVC skills, please check out my recent book:

    banner5

    There is Something you Want to Know. So Learn it.

    Students, especially, take note of this because you can get all the tools for free, so this is a great way to kick-start your career. This kind of learning was not available, much less for free when I was a kid.

    image

    That’s it. An email address. That’s all you need to get started.

    Of course, this isn’t an offering limited to students, so for you seasoned vets, give up on that treadmill and commit to four weeks of levelling up.

    Okay peeps, go rock some awesome!

    Shameless plug: if you’re wanting to ramp up your web-dev skills and get in on a 30 day challenge, be sure to check out my book on Bootstrap and the MVC Framework with tons of tips on CSS, JS, jQuery, and ASP.NET’s MVC 5. Each chapter is in digestible snippets that you can rock out in usually 15 minutes or less.

    A Lap Around Azure Websites

    If you haven’t yet started your free trial of Azure Websites – or even if it’s been a while since you have – you might be surprised to find out just how rich the offering has become. Rather than trying to catch up on your own, invest one day of time into yourself on January 14th!

    Register For The Free, Live Event Here!

    image

    I am thrilled to be joining the two excellent presenters – Jon Galloway and Cory Fowler – on Microsoft Virtual Academy as a Community Expert to help answer questions through the day. You’ll find me in the chat room, directing you to resources, answering questions and, heck, I might even craft up a sample or two along the way. :)

    UPDATE: I have posted all the links and questions/answers that came up through the session, be sure to check out the full list here.

    Some Background and Some Present Day

    It wasn’t too long ago that Azure Websites was an obscure beast in the cloud mix, with awkward deployment requirements, limited language and platform options and plenty of alternatives that required far less effort with better scaling options.

    Today’s Azure Websites’ in equally suitable for greenfield development start-ups, enterprise migrations and hobby sites. A myriad of languages, web stacks, versatility in DB connections, a great deployment story and full integration with the world’s best IDE makes Websites a legitimate consideration for your next – or first – project.

    Catch you online!

    Using Editor Templates Multiple Times on the Same Page in MVC

    banner5

    In the last post we created a star rating control that can be easily used in model binding and in displaying a record on our page. The rating control used FontAwesome and some CSS hacks to change radio buttons (which are usable from screen readers) into stars. This gave us a reusable rating control in MVC that is accessible and looks pretty darn okay, and meets our needs for model binding.

    image_thumb6

    But what if you wanted to build out a list of elements that you wanted to rate? Rather than just one movie, you wanted users to be able to rate your whole collection?  Understanding the mechanics of the binding engine are important if you want to POST a list of entities back to an MVC controller.

    Getting the Basics

    One of the earliest things that attracted me to the MVC Framework was model binding, and the freedom to stop fishing the in the Form object for parameters that may or may not exist. Over time, many of us built libraries of code that we’d suck in to each project so that we could do things like wrap the extraction of a list of checkbox or radio values up into some kind of abstraction. We don’t need to do that in MVC.

    You’ll recall that a list of checkboxes in HTML is quite straightforward. The simplest approach might be something like this:

    <form method="POST" action="Index3">
    
        <input type="checkbox" name="movies" title="The Last Starfighter" value="The Last Starfighter" id="movie1" />
        <label for="movie1">The Last Starfighter</label><br />
    
        <!-- ... -->
    
        <input type="checkbox" name="movies" title="Amelie" value="Amelie" id="movie2" />
        <label for="movie2">Amelie</label><br />
    
        <button type="submit">Save</button>
    </form>
    And to “catch” that data, we need an action (the target of the form above) with the same name that accepts a List<string> with the name of the checkbox. The value attribute of the checkbox will be added to the list parameter in your action. Your action will look something like the following:
    [HttpPost]
    public ActionResult Index3(List<string> movies)
    {
        return View();
    }
    The model binder allows any of the selected checkboxes to have a landing spot in your list. You don’t have to check for nulls, or iterate through the form collection to discover all that might have been submitted. It’s worth noting here, as well, that if your value attribute were all integers in your form, you could just as easily have the framework bind to a List<int> in your action signature. So, that’s great for simple values, but… ## …What About Binding Complex Objects? I’m so glad you asked. ![Smile](https://jcblogimages.blob.core.windows.net/img/2014/09/wlEmoticon-smile.png) [![image](https://jcblogimages.blob.core.windows.net/img/2014/09/image_thumb1.png "image")](https://jcblogimages.blob.core.windows.net/img/2014/09/image2.png)If we now look back at our rating control, the control itself is actually ready to go as-is, but we’d need to get a bit more code into our view page (not the partial, but more like, the list of the movies) to get it to tick correctly.  Here’s what we’ll do: * Change our index action to return a list * Iterate over the list in our view * Pass in some secret magic sauce to the HtmlHelper that renders our stars control We’ll load up some fake data to push to the view. You would typically want to get this data from a database or an API call of some kind. For now, we’ll go with this:
    public ActionResult Index()
    {
        var movies = new List<Movie>
        {
            new Movie{Title = "The Last Starfighter", Rating = 4},
            new Movie{Title = "Flight of the Navigator", Rating = 3},
            new Movie{Title = "Raiders of the Lost Ark",  Rating = 4},
            new Movie{Title = "Amelie",  Rating = 5}
        };
    
        return View(movies);
    }
    Great, now we just need to update our view. Basically, you can take everything out of the form and just replace it with the following, a foreach over the collection we’re passing in:
        @foreach (var movie in Model)
        {
            <div class="row">
                <div>
                    <p>@movie.Title</p>
                    <input type="hidden" value="@movie.MovieId" name="@string.Format("movies[{0}].MovieId", i)" />
                    <input type="hidden" value="@movie.Title" name="@string.Format("movies[{0}].Title", i)" />
                    <p>@Html.EditorFor(p => movie.Rating, "StarRating", string.Format("movies[{0}].Rating", i++))</p>
                </div>
            </div>
        }
    Also, don’t forget to change the @model on your page to the collection of Movie as so:
    @model List<YourApplication.Models.Movie>
    Finally, update the code block at the top of the page to declare a variable that we will use as a counter over our collection:
    @{
        ViewBag.Title = "My Awesome List of Awesome Movies";
        var i = 0; // movie control index
    }
    We’re moving along now! There’s two crucial parts in how all this will work when it gets rendered on the client and eventually hits the model binder on the way back in when the form is submitted. The first is the way I’ve constructed the name attribute on our controls. For instance:
    name="@string.Format("movies[{0}].MovieId", i)"
    In the above code, on the first iteration, the name would be rendered as “movies[0].MovieId”. The prefix “movies” is what our parameter needs to be called on our action (for the POST). The index notation [0] tells MVC which element this object is in our list, and finally, the “MovieId” is simply the property we want to pass in.  _**Note**: While I’m passing in the ID and the Title as hidden params, I’m only doing so to show the model binder in action. You should always test/cleanse these values in your controller to prevent over-posting of data, where a malicious user could modify the object without your consent._ The second noteworthy point is the overload that I’m calling on the EditorFor method:
    @Html.EditorFor(p => movie.Rating, "StarRating", string.Format("movies[{0}].Rating", i++))
    That’s important because I’m passing the similarly generated name (as above) as the name of the HTML field name. Remember that [in the last post](http://jameschambers.com/2014/09/using-font-awesome-in-an-accessible-bindable-star-rating-control/) the EditorTemplate contained references to the ViewData.TemplateInfo.HtmlFieldPrefix? That is normally provided for you by default, but in the case of a list of objects, you need to provide it on your own. That code, in the Shared\EditorTemplates folder, was referenced like this:
    var htmlField = ViewData.TemplateInfo.HtmlFieldPrefix;
    …and it was sprinkled throughout the control template. Finally, we’re going to need to get that POST action in line.  Update your controller method to look like this:
    [HttpPost]
    public ActionResult Index(List<Movie> movies)
    {
        return View(movies);
    }

    Now, when the form is submitted each set of indexed form fields will be used to new up an instance of our Movie class and placed in the collection. I’ve set a breakpoint so that you can see it in action:

    image

    You’d obviously want to do more than just cycle the movies through the controller, so rather than just returning the list you could do your validation, update your database, or aggregate stats from this response to a running average. So much fun to be had.

    Summary & Next Steps

    I always like to encourage folks to try things out and see if they can get it working on your own. It all starts with File –> New Project. Be sure to check out my Bootstrap series or purchase a copy of my book for more examples like this, and happy coding!