| I was waiting a long time to get a good topic to go for my first post. Now that I have it, let's begin. |
| This post contains sources for a console app. |
Pre-Requisites |
| First you need to setup a website on Microsoft Azure. You can publish any web application to azure for this. For help on publishing, you can find many good posts by using google. |
Second, you need to add a new app on azure in the following way :
1.) Go to the default directory on azure management portal
2.) Go to "Applications"
3.) Click "Add" at the bottom
4.) Click "Add an application my organisation is developing"
5.) Give a name to your application and select "Native client application"
6.) Give a URI to the application. For example, "http://localhost.com/"
7.) Now, your application is created and you need to give permissions to this app.
8.) At the very last of the page, you can click "Add Application" under "permissions to other applications".
9.) In the next window, note that you need to select "All Apps" in the drop down and click on the tick mark to show your website in the list.
10.) Now, you need to set the permission by selecting the drop-down with the text "Delegated Permissions : 0"
Third, you need some information about the application you created and the website you wish to modify. Here's how to get these :
1.) webSiteName
Its just the name of your website without the trailing ".azurewebsites.com". You can also view this on azure management portal by clicking "All items" image on the left. It shows names of all the items in the first column.
2.) webSpaceName
This is just the location name of your published item. In the same location as above, you can see the name of location in the last column. However, the correct location name will become "Default-Web-{your location}", without any spaces. For example, for south east asia, the location name will be "Default-Web-SoutheastAsia".
3.)tenantId
On azure management portal, click "All Items" and click on "default directory" or if you've made your own then click on that. Click "Applications". Now at the very bottom of the page, click "View Endpoints".
Here you can see the area I've marked. This is the tenantId.
4.) clientId
Close the "App Endpoints" window and click on the app you created in the second part of this post. Please note that you need to click it from the page of the directory show in the last step. Now click "configure".
Here you can see the client id.
5.) Redirect URI
Just below client ID, you can see your Redirect URI
6.) subscription Id
At the very last of the Menu on the left hand side, you can click on "Settings". Here you'll see sbuscription Id.
Code to create virtual directory
You'll need to add nuget package "Active Directory Authentication Library" for this code to workNow with all the values we need, its time for code. Below is the code for Console App :
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Threading;
namespace ConsoleApplication1
{
public class Azure
{
private string loginpath = "https://login.windows.net/{0}";
private string apiEndpoint = "https://management.azure.com/";
//Fill these up
private string webSiteName = "{your webSiteName}";
private string webSpaceName = "Default-Web-SoutheastAsia"; //Insert your webSpaceName here
private string tenantId = "{your tenantId}";
private string clientId = "{your client Id}";
private string subscriptionId = "{your subscription Id}";
//Not needed to set in console app because a function is called to get the token
//string token = "";
public void CreateVD(string name)
{
try
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(String.Format(@"https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Web/sites/{2}/config/web?api-version=2015-08-01",subscriptionId,webSpaceName,webSiteName));
request.Headers.Add("x-ms-version", "2013-03-01");
request.ContentType = "application/json";
var token = GetAuthorizationHeader();
request.Headers.Add("Authorization", "Bearer" + " " + token);
System.Net.WebResponse response = request.GetResponse();
string data = "";
using (System.IO.Stream stream = response.GetResponseStream())
{
System.IO.StreamReader sr = new System.IO.StreamReader(stream);
data = sr.ReadToEnd();
sr.Close();
stream.Close();
Console.WriteLine("data found");
}
if (data == "")
{
Console.WriteLine("Error in collecting data");
return;
}
string path = name, directory = name;
data = data.Replace("virtualApplications\":[", "virtualApplications\":[{\"virtualPath\":\"/" + path + "\",\"physicalPath\":\"site\\\\wwwroot\\\\" + directory + "\",\"preloadEnabled\":false,\"virtualDirectories\":null},");
request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(String.Format(@"https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Web/sites/{2}/config/web?api-version=2015-08-01",subscriptionId,webSpaceName,webSiteName));
request.Headers.Add("x-ms-version", "2013-03-01");
request.ContentType = "application/json";
request.AllowWriteStreamBuffering = false;
request.Accept = "Accept=application/json";
request.SendChunked = false;
request.Headers.Add("Authorization", "Bearer" + " " + token);
request.ContentLength = data.Length;
request.Method = "PUT";
System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
sw.Write(data);
sw.Close();
response = request.GetResponse();
using (System.IO.Stream stream = response.GetResponseStream())
{
data = (new System.IO.StreamReader(stream)).ReadToEnd();
Console.WriteLine("DONE");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
}
private string GetAuthorizationHeader()
{
AuthenticationResult result = null;
var context = new AuthenticationContext(string.Format(loginpath, tenantId));
var thread = new Thread(() =>
{
result = context.AcquireToken(apiEndpoint, clientId, new Uri(redirectUri));
});
thread.SetApartmentState(ApartmentState.STA);
thread.Name = "AquireTokenThread";
thread.Start();
thread.Join();
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
return token;
}
}
}
Now, you can call "CreateVD(string name)" method from "main" method to create a virtual directory on your website.
For Creating the Virtual Directory from website, I'll be updating this post / adding a new one with differences.
The only difference in both methods is the way of getting authorized.

