Getting started with Azure API Apps and Azure MVC web App in Azure App Service

In this article, you will learn how to create Azure API Apps and an MVC client deployed in Azure We App. This is going to be a very simple application connecting various components of Azure App services, and to build it we’re going to use Azure API App, Azure Web App, and SQL Server in Azure. A high level architecture of the application can be drawn as shown in the image below:

image

Essentially, in this post we will learn to perform the following tasks:

  • Make a SQL Connection in SQL database in Azure
  • Use the Entity Framework database-first approach to scaffold a CRUD operation
  • Expose the operations in an Azure API App
  • Configure the swagger API and UI for metadata and API testing
  • Publish the Azure API App in Azure App Service
  • Create client side code using swagger metadata API in an ASP.NET MVC Application
  • Use generated client code in MVC application to perform CRUD operations on a table in a SQL database in Azure
  • Publish the ASP.NET MVC application in Azure Web App

On completion of this post, you should have an Azure API App and an MVC-based Azure Web App running live in the Azure Service. As the output of the article, we have Azure API App running at http://schoolapiapp.azurewebsites.net/swagger/ui/index. We’ve also got an MVC-based Azure Web App running on this URL: http://mvcclientazureapiapp.azurewebsites.net/

In this example I am using Visual Studio 2015, however you can use Visual Studio 2013 too. You’ll also need a subscription to Azure, but you can get a free trial. Let’s get started!

Azure API App

Let us start with creating an Azure API App. To set up the development environment, install Azure SDK. You can download Azure SDK for Visual Studio 2015 from here and Azure SDK for Visual Studio 2013 from here. After successful installation you should get the successfully installed dialog box as shown in the image below:

image

Now your development environment is all set to create your first Azure API Apps. Let’s go ahead and create a new project, by selecting New->Project->ASP.NET Web Application. Give a suitable name to your ASP.NET Web Application, and from the template dialog box choose Azure API App as shown in the image below:

image

After successfully creating the project, do the following:

  1. Delete ValuesController from the Controller folder. We don’t need this controller.
  2. Right click on the Models folder and add a new Item.

To add a new item, select ADO.NET Entity Model from the Data tab and give a name to the model. Here, I am leaving it as SchoolModel.

image

In this step, in the Entity Data Model Wizard, select EF Designer from the database option and click on Next as shown in the image below:

image

Let us take a moment here and understand what are we going to do in next step. Here we will be connecting to a School database which is inside the SQL databases in Azure.

image

To connect to a SQL database in Azure, you need to perfom following tasks:

  • Add a client IP to the database server Firewall rule in the Azure portal
  • Provide a database server name in Azure
  • Provide a username and password using SQL Server authentication
  • Select the required database and click on OK

You may want to refer to the images below to provide information to connect to a database in Azure:

Read full article on in Infragistics Blog

How to Create a YouTube AngularJS Directive

I have often seen, developers come across requirement to embed a YouTube video in an AngularJS application. In this post, we will learn to create a simple YouTube AngularJS directive and also to use some of the popular directive from the GitHub.
We will follow step by step approach to create the YouTube custom directive. So let us start with create module and the controller.

var myApp = angular.module('myApp', []);
myApp.controller('VideoController', function ($scope) {
    $scope.video = 'zRtPUIumXcY';
});

Next we will create a custom directive with the isolated scope. Let us go ahead and create YouTube directive with following characteristics

  • Directive will be used as an Element
  • Directive will work in the isolated scope
  • Directive replace property is set to true, such that user will not able to view the directive information in the browser
  • In the template, iframe is used to play the YouTube video.
  • In the link function, we are watching the object passed to directive. Whenever value of object changed, directive will play the different video from the YouTube.

By putting all above together, directive is created as shown in the listing below:


myApp.directive('angularYoutube', function ($sce) {
    return {
        restrict: 'E',
        scope: { video: '=' },
        replace: true,
        template: '<div style="height:300px;"><iframe style="overflow:hidden;height:100%;width:100%" width="100%" height="100%" src="{{url}}" frameborder="1" allowfullscreen></iframe></div>',
        link: function (scope) {
            scope.$watch('video', function (newVal) {
                if (newVal) {
                    scope.url = $sce.trustAsResourceUrl("http://www.youtube.com/embed/" + newVal);
                }
            });
        }
    }
})

As you might notice in above listing that in the template, we are using the iframe to play the YouTube video. Also we are watching the value passed to the directive and constructing the URL using the $sce service of AngularJS.
On the view, angularYoutube directive can be used as shown in the listing below:

<div ng-controller="VideoController">
        <angular-youtube video="video"></angular-youtube>
    </div>

As of now, we should able to play a video in AngularJS application. Right now we are passing hard coded video code from the controller. We can allow user to pass the video code, just by using an input textbox as shown in the listing below:


<div ng-controller="VideoController">
        <input type="text" ng-model="video" placeholder="enter video code here to play"/>
        <hr/>
        <angular-youtube video="video"></angular-youtube>
    </div>


Here we have created a very simple custom AngularJS directive to embed the YouTube video in the AngularJS application.
For advanced scenarios, you may want to use Angular YouTube Embed . I find it very useful for advanced scenarios. I hope you find this post useful. Thanks for reading.

How to work with Enums in ASP.NET MVC

Recently I got a question from one of the readers that how to work with Enums in ASP.NET MVC? Before we move ahead in this post, let me tell you that it is very simple to work with Enums in ASP.NET MVC 5.1 and later. In MVC 5.1, HTML helper class EnumDropDownListFor has been introduced which is used to display the Enum in a dropdown as shown in the image below:

image

To start with let us consider that we have created an Enum TypeOfStudent as shown in the listing below. This Enum holds information about the type of a particular student.


public enum TypeOfStudent
    {
        [Display(Name = "Science Student.")]
        SS,
        [Display(Name = "Arts Student.")]
        AS,
        [Display(Name = "Economics Student.")]
        ES,

    }

We are going to use TypeOfStudent enum in the Student class which is created as shown in the listing below:


  public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

        public TypeOfStudent StudentType { get; set;}
    }

Right click on the Controller folder and create a controller using the scaffolding. We need to select MVC 5 controller using the Entity Framework as shown in the image below:

image

In the Model class select Student and create a Data context class (perhaps select an existing one) to add a controller.

image

We just added a controller which is using Student class as model and the Student class has Enum TypeOfStudent as a property. Let us go ahead and run the application, we will find Enum property is rendered in the dropdown as shown in the image below:

image

As we see that Enum values has been populated in the StudentType dropdown. In the Create and Edit views of the controller, a control EnumDropDownListFor has been added as shown in the listing below:


  <div class="form-group">;
            @Html.LabelFor(model =&gt; model.StudentType, htmlAttributes: new { @class = "control-label col-md-2" })
            &lt;div class="col-md-10"&gt;
                @Html.EnumDropDownListFor(model =&gt; model.StudentType, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model =&gt; model.StudentType, "", new { @class = "text-danger" })
            </div>;
        </div>;

When we create View using the scaffolding, MVC 5.1 and later use HTML Helper class EnumDropDownListFor to create dropdown from the Enum.

Using RadiButtons for the Enum

In MVC 5.1 onwards we do have support of EnumDropDownListFor which renders Enum values to a drop down. We may have a requirement to render the Enum values to RadioButton. There is no simple way to do it. For this we have to create HTML Helper class. Let us go ahead and create a HTML helper class. To create HTML Helper class

  1. Add a static class to the project
  2. Add HTML Helper method as static method to the class

I have created a folder named Helper and inside that created a class EnumRadioButtonHelper. Inside the static class, we have created static method EnumRadioButton to render Enums in the RadioButtons.


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MVCEnum.Helper
{
   public static class EnumRadioButtonHelper
    {
        public static MvcHtmlString EnumRadioButton<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        {
            var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            var listOfValues = Enum.GetNames(metaData.ModelType);

            var sb = new StringBuilder();

            if (listOfValues != null)
            {
                sb = sb.AppendFormat("<ul>");

                
                foreach (var name in listOfValues)
                {
                    var label = name;

                    var memInfo = metaData.ModelType.GetMember(name);

                    if (memInfo != null)
                    {
                        var attributes = memInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);

                        if (attributes != null && attributes.Length > 0)
                            label = ((DisplayAttribute)attributes[0]).Name;
                    }

                    var id = string.Format(
                        "{0}_{1}_{2}",
                        htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
                        metaData.PropertyName,
                        name
                    );

                    var radio = htmlHelper.RadioButtonFor(expression, name, new { id = id }).ToHtmlString();

                    sb.AppendFormat("<li>{0}{1}</li>", radio, HttpUtility.HtmlEncode(label));
                }

                sb = sb.AppendFormat("</ul>");
            }

            return MvcHtmlString.Create(sb.ToString());
        }
    }
}

We can use the EnumRadioButton helper method on the view directly. We also need to make sure that, we have added the namespace of the helper class on the view. I have added the namespace as shown in the listing below:

@using MVCEnum.Helper
@model MVCEnum.Models.Student

Once namespace is added, EnumRadioButton can be used to render Enum in RadioButton as shown in the listing below:

  <div class="form-group">
            @Html.LabelFor(model => model.StudentType, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">            
                @Html.EnumRadioButton(m => m.StudentType)
            </div>
        </div>

On running the application, we will find StuentType is rendered in RadioButton also as shown in the image below:

image

We learnt how to work with Enums in MVC 5.1 and later. In MVC 5.1 EnumDropDownListFor has been introduced to render Enums in DropDown. We can also create HTML helper class to render Enums in RadioButtons. I hope you find this post useful. Thanks for reading.

Areas in ASP.NET MVC

Areas are some of the most important components of ASP.NET MVC projects. The main use of Areas are to physically partition web project in separate units.  If you look into an ASP.NET MVC project, logical components like Model, Controller, and the View are kept physically in different folders, and ASP.NET MVC uses naming conventions to create the relationship between these components. Problems start when you have a relatively big application to implement. For instance, if you are implementing an E-Commerce application with multiple business units, such as Checkout, Billing, and Search etc. Each of these units have their own logical components views, controllers, and models. In this scenario, you can use ASP.NET MVC Areas to physically partition the business components in the same project.

In short, an area can be defined as: Smaller functional units in an ASP.NET MVC project with its own set of controllers, views, and models.

image

Read full article on the Infragistics blog