Thursday 5 July 2018

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:
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:
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:
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.
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:
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.

 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:
Since we have provided vital information such as username and password to connect to Azure database server, the Entity DataModel Wiazrd asks us whether we want to include sensitive data in the connection string or not. Here we’ll select the Yes radio button and click on Next. Also, if you desire you may want to change the connectionstring name, but in this example I am leaving it as the default.
Now we need to select the entities to work with. To keep it simple, I am selecting the simplest table in the School database (and by “simple”, I mean the table with no relationship to any other tables). So I am going to select Department table to proceed in this example. As shown in the image below, to select the Department table, check the checkbox of Department and leave the other fields as default.
Next, to create the datamodel, click on Finish and we’ve added the model. Using this model, we will create the Azure API. You can verify the created SchoolModel in the Solution Explorer as shown in the image below:
As of now we have added the model. Make sure you have sucessfuly built the project at this stage, and then let’s create a controller. Right click on the Controllers folder and from contextmeny, select Add->Controller.  In the scaffolding option, select Web API 2 Controller with actions, using Entity Framework as shown in the image below:
To add the controller using the scaffolding, you need to select the following options:
  1. Model class: Choose Department from the dropdown
  2. Data context class: Choose SchoolEntities from the dropdown
  3. Either give your desired controller name or leave the suggested name which is based on the model class.
On clicking Add, the DepartmentsController would be added to the project. Essentially, we have created web API to perform CRUD operations on the Department table. In the next step, we have to enable the Swagger Metadata and UI.
Enabling Swagger Metadata and UI
Azure App Service supports Swagger 2.0 metadata. Using this each API can define an EndPoint URL that returns metadata for the API in Swagger JSON format. The metadata returned can be used to generate client code.
You can navigate metadata for the created API by appending  apiUrl/swagger/docs/v1. So let us go ahead and run the project, and you should get a “forbidden” message as shown in the image below:

To navigate to the metadata of the API, append /swagger/docs/v1 to the baseurl as shown here
Here you see Azure API metadata in JSON format. This is Swagger 2.0 JSON metadata for the API. This can be used to create the client code.
To enable the Swagger UI, go back to the project, and from the App_Start folder open SwaggerConfig.cs file.  In the file, locate the following lines of code and uncomment them:
Once again, go ahead and run the Azure API App by pressing F5. Append the URL with /swagger and you will find Swagger UI has been enabled on the API.
Using the Swagger UI, we can test the API created. For example, let us go ahead and try to create a new Department. Click on the POST option, create the department data to be inserted in JSON fromat, and click on Try it out.
You will see Response Body and Response Code returned from the API. On sucessful creation of the resource, it should return the status code 201.
You might have noticed as of now that it is vey simple to create Azure API Apps, enable the Swagger metadadata and UI and test them locally. Now let’s go ahead and publish them in the Azure.
 Deploy API  to Azure
So far eveything we have done is local. Now we want to move our local Azure API app to Azure using Azure tools intgrated with Visual Studio 2015. To start, right click on the project and select Publish.
In the Publish Web dialog box, select Microsoft Azure App Service and click Next.
On the next widow, select subscription and click on New.
In the “Create App Service” window, first change the type to the API App as shown in image below:
Next give the following information:
  1. Unique API name
  2. Choose the subscription
  3. If you have already created the App Service Plan, you can choose that. To create a new one click on New.
In this example I am creating a new App Service plan as shown in the image below. We will use this newly created plan to publish the application.
After providing all the information, your hosting options should look like below:
As of now, we have provided all information required to publish the application. Click on Create to proceed further in the deployment. On the next screen, confirm all the details and click on Next to proceed further.
On this screen, you can verify the connection strings and update the database. To keep the things simple, leave all settings to default and click on Next.
On this screen, preview the deployments and click on publish to deploy the Azure API App to the Azure Service.
You can see the publish status in the ouput window of Visual Studio. On a sucessful pubish, you will be navigated to the Azure API App hosted in Azure Service. You should get Azure API app running in Azure service as shown in the image below.
You have sucessfuly deployed Azure API App to Azure Service!
 Configuring metadata URL in portal 
To configiure the metadata URL, login to the portal and in the App Services section you will find your newly created API App.
 Click on the API App and select API defintion.
In the API defintion, you can change the metadata URL. As discussed above, by default the metadata URL is set to  ../swagger/docs/v1.
We can change the metadata URL to something else as shown in the image below. After changing the URL, don’t forget to save the new URL by clicking on the save button in the top. To keep it simple, I have left the metadata URL as the defualt here. So when you navigate to ../swagger/docs/v1, you will get the swagger metadata which is required to create client side code. The metadata can be seen in the browser as shown in the image below:
You can perform a GET operation and view all the departments in the browser by navigating to the URL ../api/departments. Departments will be returned as JSON in the browser as shown in the image below:
You can also test the other operations using the swagger UI as we discussed in the previous section of this article.
Great, so far we have created Azure API which is working with the SQL database in Azure. We have also sucessfuly deployed that to the Azure App Service.
Creating MVC Client
In this section of the article, we will create a .NET client. Let us go ahead and create an ASP.NET MVC project.
In the template, select MVC and choose No Authentication from the Change Authentication option.
After successful creation of the project, right click on the project and from the context menu select Add->REST API Client.
On selecting the REST API Client option, you will get options to either Download API from Microsoft Azure or select to existing Swagger metadata file. Optionally you can change the client namespace name here as well.
Let us select option to Download from Microsoft Azure API App and click on the Browse button.  To select the App Service, choose subscription and select Azure API App as shown in the image below and click on the ok button.
After further clicking on the Ok button, the metadata will be downloaded to the client app. On successful download of the metadata, you will find client side code has been generated. You can see them in solution explorer as shown in the image below:
Now we have created the client side code from the Azure API App. Let’s go ahead and add a contoller: right click on the Controllers folder, and from context menu select Add->Controller.  From the template, choose MVC 5 Controller with read/write actions.
Using the genearted code, it is very easy to perform operation on Azure API.  In the Index action of the generated controller, you can fetch all the departments by using instance of SchoolApiApp. To fetch all the departments, refer the listing below:
 private SchoolApiApp app = new SchoolApiApp();
        public ActionResult Index()
        {
            return View(app.Departments.GetDepartments());
        }
As you might have inferred from the code listed above, it takes just a few lines of code to work with the REST API. Keep in mind that .NET client side code has been generated using the Swagger metadata of Azure API app.
To add View, right click on the Index action and select add view. In the Add View template, select List and choose Department as model class.
Creating a record is also very simple. To do so, all you need to do is to call a Post method by passing the enity object as shown in the listing below.
public ActionResult Create([Bind(Include = "Administrator,Budget,Name,StartDate")] Department department)
        {
            try
            {
                // TODO: Add insert logic here
                if(ModelState.IsValid)
                {
                    department.DepartmentID = 4569;                
                    app.Departments.PostDepartmentByDepartment(department);
                }

                return RedirectToAction("Index");
            }
            catch(Exception ex)
            {
                return View();
            }
        }
The generated code will have all the operations like List, Post, Put, and Delete. You can use them as easily as we just used List and Post operations in above examples.
In the last step let us go ahead and publish MVC client to Azure Web App. Publishing would be same as we published the API App. For brevity, I am avoiding the screenshots and only mentioning the steps.
Publish MVC client to Azure Web App
  1. Right click on the project and click on publish
  2. Select Publish target as Microsoft Azure App Service
  3. Choose subscription and click on New
  4. Give the web app a name, select region, and click on Create
  5. In the last step, click on Publish
 On a successful publish, you will get a “publish succeeded” message along with the URL in Visual Studio output window.

Great! We’ve just published an ASP.NET MVC Application to Azure Web App, which is consuming an Azure API App. 
 Conclusion
In this article, we learned how to perform the following tasks:
  • Make a SQL Connection to in SQL database in Azure
  • Use Entity Framework database first approach to scaffold CRUD operation
  • Expose the operations in Azure API App
  • Configure the swagger API and UI for metadata and API testing
  • Publish 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 table in SQL database in Azure
  • Publish ASP.NET MVC application in Azure Web App

No comments:

Post a Comment