Showing posts with label Cloud Computing. Show all posts
Showing posts with label Cloud Computing. Show all posts

Monday, June 23, 2025

Export Azure Resources to Excel or CSV in Seconds | Azure Portal (No Code)

 In this vide we will talk about below features – 

  1. Export to CSV azure resources
  2. Customize default Virtual Machines view and then export to CSV
  3. Customize default IP address, NSF, UDR view and then export to CSV
  4. Create your own view with app services and export to CSV






Thursday, April 27, 2017

Send email from Azure SendGrid using PowerShell

Abstract

Sendgrid is popular. No doubt about it! Especially for Dev and Test scenarios where you get 25000 free emails a month. This post describes how can you use Sendgrid to send email using PowerShell.

Don’t expect me to write blog post on C# code for sending email using Sendgrid. Because, Sendgrid will keep updating their API (like V2, V3 and so on); ultimately C# code will also change. So you can refer C# or other languages code sample from SendGrid documentation itself.

Provision SendGrid account on Microsoft Azure

Let’s create a SendGrid account quickly on Azure. Login to Azure portal on the link – http://portal.azure.com . Sendgrid today available only in selected region. Example, not available in India region. I am based out of India so nearest data center for me is SouthEast Asia referred as SEA in the blog). I will select the SEA datacenter for the creation of SendGrid account on Azure. Therefore first let’s add Resource group in SEA region and then create SendGrid in the same Resource group.

Select “Resource Groups” in left had pane. It lists all resource groups present in your subscription. Click on “Add” button present at the top. Provide the resource group name as SendEmailRG, subscription of your choice and location as SEA as shown below. Click on Create to finish the resource group creation process.



Click on New. You will see a search box at the top. Type Sendgrid on the search box; intelligence will automatically display “Sendgrid Email Deliverys”. Select the same and press enter. Another horizontal blade will open. Select the Sendgrid Email Delivery option and click on Create.

Provide the name of account as “EmailSample”. Provide the password of your choice and remember it. We will need it later. Select the Azure subscription and select existing option for resource group. Select SendEmailRG resource group. This step will ensure that SendGrid account in created in SEA region.

On pricing tier; select the option as Free as shown below –



If you have money feel free to select the other paid pricing tiers.

Provide the contact information. I have provided below. Remember you will receive confirmation email from SendGrid. So don’t put values like below; rather give genuine values.



Select “I give…” checkmark for legal terms and click on Purchase. Then proceed ahead and finish the SendGrid account creation process.

Retrieve essential detail from SendGrid account

To send email we need username, password and SMTP server name. This information is available on Azure portal under your sendgrid account. So go to the SendGrid account we created in above step from Azure portal. Click on Configurations and you will see the required information listed as shown below –


PowerShell to Send Email

Let’s first define the essential parameters based on the information we captured from configurations tab of sendgrid tab –

$Username ="YourUserNameFromPortal"

$Password = ConvertTo-SecureString "YourPassowrdWhichYouHadEnteredDuringSendGridCreation" -AsPlainText -Force

$credential = New-Object System.Management.Automation.PSCredential $Username, $Password

$SMTPServer = "smtp.sendgrid.net"

Any email object requires necessary information like email from, email to, subject line. Let’s add this information as parameters –

$EmailFrom = "No-reply@azureadmin.com"

[string[]]$EmailTo = "YourEmail@gmail.com"
$Subject = "Sending sample email using SendGrid Azure and PowerShell"

$Body = "This is sample email sent using Sendgrid account create on Microsoft Azure. The script written is easy to use."

If you observe, I am using array for $Emailto variable. This is because if I want to add multiple email address into “To” list, I should be able to do it using array. So I want to send email to multiple addresses I will add them as below –

[string[]]$EmailTo = "YourEmail1@gmail.com", “YourEmail2@yahoo.com”

Then use below command to send the email –

Send-MailMessage -smtpServer $SMTPServer -Credential $credential -Usessl -Port 587 -from $EmailFrom -to $EmailTo -subject $Subject -Body $Body -BodyAsHtml

Manage option on SendGrid account

Look at the below screenshot for highlighted option.



This option will help you in generating api key, monitoring of your sendgrid account, failed emails , reports and so on. No this is not another blog post on another day because Sendgrid documentation is detailed to explain all the options. Why you want me to write blog post on the information which is already explained so well?

Note -

Sendgrid provides API Keys which can be used for providing limited access. The above PowerShell code do not use API Key for sending emails. In case you want to use SendGRid API Keys based access control and then send the email using PowerShell; I will suggest to write c# code exe with required parameters and then invoke it using Powershell.  😊


Happy Emailing!!

Saturday, October 18, 2014

Multiple web applications in single cloud service web role with multiple SSL certificates and custom domains over https using Server Name Indication


I know the title of this post is quite big and hard to understand in first go. But I wanted to highlight the important aspect I am going to touch in the article and hence such a long name.
Ok, so here in this post I am going to demo how you can host multiple web applications in single cloud service. I know you may say that there are numerous posts on the same topic what is different in here? Yes the difference is there. You may find that most of the posts talks about hosting multiple web sites in single cloud service web role but they do not focus on running them on HTTPS and with custom domain name. Exactly this is what I am explaining in this post.
So in essence, we will see that, how can we host multiple web applications in single cloud service web role. Then we will see how the same applications can be hosted on HTTPS using SSL certificates in single cloud service web role. After that we will extend the talk to hosting same apps with custom domains using new feature of IIS 8.0 called as Server Name Indication (SNI).
Applicable software stack – VS 2013 and above, Azure SDK 2.3 and above, IIS 8.0 and above. [IIS 7 not supported].
Create required project in Visual Studio
This part is pretty straightforward implementation. To start with I created a simple cloud service project in VS2013 and added one web role in it. I renamed the web role to ManegementAppWebRole as shown below –

I changed the default.aspx UI text to just make it identify as Management App. Now I added another ASP.NET web project in the same solution. This will be my survey app. In this also I changed the default.aspx text to just make it identify as Survey app. So in all my projects structure is as follows –

Hosting multiple web applications in the same cloud service web role
Okay, so here I am representing a way by which you can have two web sites hosted in the same cloud service web role. In my case one of the applications is Management app web role itself and another is Survey web application which is not the part of cloud service. So I will run the survey app as part of Management app web role. To configure this full IIS capability can be leveraged. We have a special file in cloud service project know ServiceDefinition.csdef file. My current structure of .csdef file is as shown below –


The <Sites> tag is the key to make this possible. So I just added another site in .csdef file and provided the path of Survey web application. And provided the actual physical path of my survey app. Most importantly if you observe I have provided the host header for my survey app as “surveyapp.kunal.com”. This is the main differentiator of the survey app running in the Management app web role. IIS do not allow to have more than one site listening on the same port without adding host header. We need to provide host header because both of our applications will be running on the same Endpoint port which is 80. Therefore there has to be some way by which IIS can understand the request of user need to be served by which application. Therefore we need host header. The complete structure of my .csdef file is as shown below –

Now in reality my host header site “surveyapp.kunal.com” do not exists. Therefore to make survey app resolve to this URL I need to update “hosts” file of my machine. Hosts file is located at C:\Windows\System32\drivers\etc\hosts. I copied the file to desktop and opened in notepad and added an entry as highlighted below –
Then from desktop I replaced / copy-pasted the hosts file back to its location.
Now let’s run the project in debug mode by pressing F5 and it open the browser with management app with url similar to below – http://127.0.0.1:60123/ Here 60123 is port opened by my emulator, this will different in your case. Open another browser and cope the same url of management app and just replace 127.0.0.1 by our host header name i.e. surveyapp.kunal.com. So final url in new browser window will be - http://surveyapp.kunal.com:60123/and bingo!! I see my management app and survey app running on the same port as shown below –

Let’s run the same implementation in Full IIS and Full emulator mode. This can be configured from the cloud service project properties. To open the properties of cloud service project, right click on Cloud service project and select Properties.
Note – With Azure SDK 2.4 FULL Emulator has been deprecated; however I guess you should be able to run the Full IIS with Emulator Express. This is what I think!!
Ok, now let’s run the project by pressing Ctrl+F5 [DO NOT RUN in DEBUG MOE!!] and here is what I see in browser and IIS –

As you can see, host header has been applied for my Survey Application. This is how we can run multiple web application in single cloud service web role.
Advantage – You are running the tow different web apps in the same IIS. In other words you are running two different web applications in same instance of Azure role and hence you save money. In case of 2 different roles for 2 different web app, you will be charged for role VM instances of 2 applications. In this case you are charged for only one role VM instances.
Now in next part we will see how we can run these web applications over HTTPS and custom domain. This means, I have custom domain mapped for survey as “surveyapp.kunal.com” and now we will have custom domain name updated in hosts file for Management app as “managementapp.kunal.com” plus to run them on https and certificates.

Monday, June 16, 2014

Understanding Azure Traffic Manager for network traffic management


Before understanding Azure Traffic Manager let’s first understand terminologies that are used in Traffic Manager.
What is Domain Name System - DNS –?
Every web site hosted on server has a unique IP. It is very hard to remember the IP therefore user friendly name introduced. These are nothing but the Domain names. So DNs server internally converts user friendly names into IP address of a web site.
Hence Domain name is simply a unique name for your application by which it is known in the internet world. For example, Google.com is DNS name. In other words, we can call it as a unique name that is assigned to your web application.
What is Local DNS?
Local DNS server is nothing but the server of your Internet Service Provider by which you get internet access for your machine. If you are part of any organization and accessing the internet from organization network then your corporate network DNS will be your local DNS.
What is CNAME?
CNAME stands for Canonical Name. The dictionary meaning of Canonical is Authorized or Recognized.
CNAME is a type of record in the DNS used to specify that, domain name uses the IP address of another domain. For example, on Azure I created a cloud service and its DNS name will be http://kunalcloudservice.cloudapp.net

Let’s say I wish to change it to http://kunal.com so that I don’t want my customers to see cloudpp.net thing. Then I will configure CNAME or custom name for my cloud service DNS. So http://kunal.com will be my CNAME for cloud service DNS.
What is DNS Cache?
A DNS cache contains records that transform domain names to IP address. The internet domain name system involves caching on internet DNS server and on client machine which connects to DNS servers.
Why to use Azure Traffic Manager?



Thursday, June 12, 2014

Scalability – Scale up and scale out


The scalability meaning in dictionary states that, ability of system to expand to cope with increased use.
Scalability Definition -
In computer terminology it is referred as, the ability of a system to handle growing amount of work without degrading its performance.
Description –
Scalability of a system or application always depends on Hardware and software component that forms a complete system or application. For an application to be scalable first it should support distributed architecture.
The distributed application means complete application spans across multiple computers in a network and they work in conjunction by passing messages to each other. You application is based on distributable architecture means complete application can be deployed on many servers or computers and still it works well without any failure and malfunction. If your application is distributable then it can be scalable as well.
For achieving scalability Hardware Virtualization is always preferred. To understand hardware virtualization process in terms of cloud computing click on following link -
http://sanganakauthority.blogspot.com/2011/10/understanding-microsoft-datacenters-and.html


Type of Scalability –


Saturday, June 7, 2014

Create Azure Managed Cache Service in Microsoft Windows Azure


Currently Azure Managed creation is not supported from Azure management portal. You need Azure Powershell command to get started with Azure Managed Cache Service.
Open Powershell for azure.


Type following command to login to subscription

Add-AzureAccount

You will be prompted to login. Enter the credentials and proceed.

Then you need to select the azure subscription of your choice. Type following command to select the desired subscription.

Select-AzureSubscription

You will be prompted to enter the subscription name. Please enter your subscription name. This can be found on portal – settings menu option on left hand pane as shown below -

Wednesday, May 7, 2014

Assign user to single database in Azure SQL Database


Security is vast topic in case of SQL Azure. In this post I will explain simple steps required to create user, assign db owner role to that user specific to single Azure SQL DB.

The advantage is, you don’t have to use admin credentials of Azure SQL DB server. Also the new use will not have any access to master database and hence accidental changes to other database are avoided.  

First login to Azure SQL management portal. Login to SQL Azure management portal using credentials of user which has access to master database. Such user can be server administrator for Azure SQL.

Then create a sample database. I will name it as “MyDB”. Now I need to create a user in such a way that it will have permission to perform any operation on MyDB only. So same user credentials can be used in applications connecting to SQL Azure.

Steps are as follows –


Create Login in master database query window.
Create Login kunal WITH PASSWORD = ‘yourPassword’ 

Create user in query window of MyDB database from above created login.
Create User kunalasuser FROM LOGIN kunal 

Saturday, April 26, 2014

Stop copy of Azure Virtual Machine from one subscription to another subscription using Azure Powershell

Technologies - Azure Blob sorage and Poweshell sdk 2.3 and above...

If you wish to take back up of azure virtual machine, the best way is to use Windows Azure Powershell cmdlets. Also there is an excellent post written about copying the azure virtual machine across subscriptions here - http://blogs.msdn.com/b/microsoft_press/archive/2014/01/29/from-the-mvps-copying-a-virtual-machine-from-one-windows-azure-subscription-to-another-with-powershell.aspx?Redirected=true

 
However sometimes it may happen that you start copying of Azure Virtual machine to a storage account and finds that the selected storage account is not the intended one. Then you might want to stop the copy operation of azure virtual machine immediately. In such case following guide will help you to stop the copy operation of virtual machines.
The copy operation can be started with powershell command Start-CopyAzureStorageBlob.
Similarly to stop Azure blob copy operation we have Stop-AzureStorageBlobCopy command.

Let’s walkthrough the each step required to stop the blob copy operation in case of Azure virtual machine or in case of any blob copy operation. The same steps can be used for soppting all types of blob copy operation and it is not specific for stopping azure virtual machine vhd copy.

Can not find your azure storage credentials – Windows Azure Storage


I was performing an operation in powershell to copy blob from one storage account to another storage account. But before that I was trying to get the blobs present in container by using powershell command –
Get-AzureStorageBlob -Container vhds
When you fire this command you will receive error stated as below –
“Can not find your azure storage credentials.”
The reason is you have not set the context for current storage operation. The total scripts should be as follows –

Thursday, April 17, 2014

How to create Azure virtual machine using Visual Studio and Azure SDK 2.3


In build 2014 Day 2 keynote, the new capability of visual studio was demonstrated about creating Azure Virtual Machine without login to the Azure management portal. With the release of Azure SDK 2.3, now you can create an Azure Virtual Machine from visual studio itself. Following steps walks you through the same –
Open Server Explorer in visual studio 2012 and right click Virtual Machines option. Then select “Creation Virtual Machine” option as shown below –


A dialog box appears. Sign in to your account and select subscription in which you wish to create Azure Virtual Machine.


Then you can select the image from which you wish to create the virtual image. Either you can use standard image from option Platform Images, or you can choose MSDN images. If you already have images captured from other virtual machines then you can create virtual machine from these captured images as well.

However you cannot create Azure Virtual Machine from “My Disks” option which is available on Azure Management Portal.


Select the image of your choice and click Next. I have chose Windows Server 2008 R2 SP1 for this demo. Enter basic details for selected VM image.


Then select existing cloud service or create new. Based on virtual network configuration for selected cloud service data in Subnet and Virtual network dropdown will populate. If cloud service does not belong to virtual network then these dropdowns will be disabled.


You can modify the existing, add new or delete existing endpoints as shown below –



Click on Create to start creating azure virtual machine. The progress can be viewed from Azure Activity Log in visual studio. However the way we can cancel the ongoing deployment in case of Cloud Service Deployment, Azure VM Cancellation is not supported. Refer below screenshot –


Hope this helps.

Cheers…
Happy Provisioning!!!

Monday, March 31, 2014

Content Type application/soap+xml; charset=utf-8 was not supported by service. The client and service bindings may be mismatched


This is the error I had encountered when I was configuring wshttpbinding with Azure WCF  Web role as per the steps I mentioned here - http://sanganakauthority.blogspot.in/2014/03/azure-wcf-web-role-with-wshttpbinding.html 

This problem is encountered when metadata endpoint is not configured on WCF web config file. So you need to configure mex endpoint and mark httpGetEnabled as true. 

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> 

And in service behaviour mark httpGetenabled=true. This should solve the problem. 

Hope this helps.

Cheers…
Happy Configuring!!!

Tuesday, March 11, 2014

Azure Virtual Machine Provisioning Timed Out problem and solutions


To capture the image of Azure Virtual Machine, you should follow the steps mentioned at the link –

 

This link states to select “Quit” option while performing sysprep so that while provisioning VM based on captured image, it won’t run into timed out error. This is perfectly fine. However what if even after selecting Quit during sysprep you run into Provisioning timed out error while creating VM based on captured image? 

I recently ran into such issue. I had selected Quit option during sysprep, and then I captured the VM image and when I provisioned VM based on this captured image, I got error as “Provisioning Timed Out”.

However interesting fact was that, I was able to make RDP to the machine and all installed application was working fine on it. Now if I restart this captured image based Azure VM from Management Portal, VM got into Running status on portal. This was one of the workaround however not a permanent solution. 

Then I raised a support ticket with Microsoft and findings were awesome.

Recently in Feb 2014, Azure Team technical blog posted that, VM agent is now by default installed on Azure virtual Machines. And guess what, VM agent was the problem behind Provisioning timed out error for Azure VM.

This new VM agent was installed on Azure VM that I was using to capture the image. Then when I created a new virtual machine based on captured image by default VM agent tries to get installed again, but as it is already installed may be monitoring servers will never receive the status as “installation complete” which they are waiting for  and hence after certain time interval status of VM becomes Provisioning Timed Out.

To fix this problem of Provisioning Timed Out, while creating VM’s remember to uncheck the option “Install the VM agent”.

That’s it you are done and problem of Provisioning timed out error resolved.
 
MSDN link here -

Hope this helps.

Cheers…

Happy Provisioning!!!

 

Saturday, March 8, 2014

Azure WCF Web role over http with wshttpbinding and custom UserNamePasswordValidator – step by step guide


Today I tried to host WCF service using Azure web role with wshttpbinding and custom username and password validator and access it over http.
Wshttpbinding is based on ws- security and it is good option to provide authentication mechanism to WCF service hosted on Azure. Let’s start it right away.

Add Custom username and password validator -
First of all create an Azure cloud service project with one web role and WCF web role. Then add reference to System.IdentityModel to WCF project so that we can use our own custom username and password validator based on UserNamePasswordValidator class. Create a class as shown below in WCF web role project –
/// <summary>
/// Validator class to be used for WCF authentication in case of wsHttpbinding only
/// </summary>
    public class Service1UserNameValidator : UserNamePasswordValidator
    {

        public override void Validate(string userName, string password)
        {
            if (null == userName || null == password)
            {
                throw new ArgumentNullException();
            }

            if (!(userName == "MyUser" && password == "My#Password"))
            {
                // This throws an informative fault to the client.
                throw new FaultException("Unknown Username or Incorrect Password. Unauthorized access to the web service.");
                // When you do not want to throw an infomative fault to the client,
                // throw the following exception.
                // throw new SecurityTokenException("Unknown Username or Incorrect Password");
            }

        }
    }


Configuration to be added in web.config of WCF project –

Now we will configure wshttpbinding for the service based on security mode as Message and clientCredentialType as UserName. Please add below configuration tag in WCF web role
web.config file under System.ServiceModel bindings tag –
<bindings>
      <wsHttpBinding>
        <binding name="wsHttpBinding_IService1">
          <security mode="Message">
            <message clientCredentialType="UserName"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings> 



Now we need to configure the Service Behaviour for WCF Web role.
Under <behaviours> tag add following –
<serviceBehaviors>
        <behavior name="CustomValidator">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceCredentials>
            <serviceCertificate findValue="localhost" storeLocation="LocalMachine"
              storeName="My" x509FindType="FindBySubjectName" />
            <userNameAuthentication userNamePasswordValidationMode="Custom"
              customUserNamePasswordValidatorType="WCFService.Service1UserNameValidator, WCFService" />
          </serviceCredentials>
        </behavior>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
Under Services tag add following –
<services>
      <service behaviorConfiguration="CustomValidator" name="WCFService.Service1">
        <endpoint address="" binding="wsHttpBinding"
          bindingConfiguration="wsHttpBinding_IService1"
          name="wsHttpEndpoint" contract="WCFService.IService1">
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
You will see that, we have named the behaviour as CustomValidator. Metadata retrieval is allowed over HTTP only and not for https. Then most important part is           <serviceCredentials> tag. This is where we specify the certificate to be used and custom username and password validator.
serviceCertificate tag specifies the certificate to be used. Usually we specify certificates which are issued by certificate authority. As part of this tutorial I am using self signed certificate which gets generated in IIS 7 itself during IIS 7 installation. However please be aware that, this certificate should not be used in production environment.

Open run window and type “inetmgr” without quotes. This will open IIS. Select the computer name in left pane and double click Server Certificates in middle pane to open the feature. You will find that, a certificate named as “IIS Express Development Certificate” is already present. I will use same certificate for this tutorial.




Export/ Import certificate -
During development, this certificate should be present in Trusted People Store of current user and Personal store of Local Machine. During production on cloud service hosting, we need to put the same certificate to some more places which I will talk later.
For now, to add export certificate and import in Trusted People store refer to following link –
The link talks about importing and exporting certificate in Local Machine. Same can be used to import or export certificate in Local user store which can be opened from run window and typing “Certmgr.msc” command.
Add Certificates to Roles -
Next we need to make sure that; self signed certificate is added for WCF web Role and WebRole1 project. Right click WCF role in cloud service project and select Properties. Then click on Certificates option present on left hand side pane. Click on “Add Certificate”; this will add a row. Provide name as localhost, store location as localmachine, store name as my. Now open the certificate from personal store of current user and copy the thumbprint. Add it to the thumbprint section of certificate added in properties of WCF Web Role. Follow the same steps to add localhost certificate for Web Role project.

Next tag is userNameAuthentication. This is where I am specifying my custom class to be used for username and password validation. In this tag WCFService is the name of namespace in which my Service1UsernameValidator class exists.

Adding WCF Web role Service Reference locally in Web Role -
Now we need to start WCF service web role so that service reference can be added in WebRole1 project. Right click WCF Service and debug to start new instance as shown below –



This will start WCF service on some localhost url as shown below - http://localhost:someportnumber/Service1.svc
No we need to add service reference to Web role 1. Righ click WebRole1 project -> click Add service Reference. A window will appear. Click on Discover button. WCF Service Service1 started above will get listed. Keep the reference name as ServiceReference1 only and Click OK to add reference. Open web.config for Webrole1 project. This web.config we will modify to have wshpbinding. You will observe that, in <system.serviceModel>tag basichttpbinding is added.


Copy paste following segment in ServiceModel tag of web.config in WebRole1 project.

<bindings>     
      <wsHttpBinding>
        <binding name="wsHttpBinding_IService1" transactionFlow="false">
          <security mode="Message">
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <behaviors>
      <endpointBehaviors>
        <behavior name="ClientCertificateBehavior">
          <clientCredentials>
            <serviceCertificate>
              <!--Setting the certificateValidationMode to PeerOrChainTrust means that if the certificate
              is in the user's Trusted People store, then it will be trusted without performing a
              validation of the certificate's issuer chain. This setting is used here for convenience so that the
              sample can be run without having to have certificates issued by a certificate authority (CA).
              This setting is less secure than the default, ChainTrust. The security implications of this
              setting should be carefully considered before using PeerOrChainTrust in production code.-->
              <authentication certificateValidationMode="PeerOrChainTrust" />
            </serviceCertificate>
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>

    <client>
      <endpoint address="http://localhost:7493/Service1.svc"
        binding="wsHttpBinding" bindingConfiguration="wsHttpBinding_IService1"
        contract="ServiceReference1.IService1"
        behaviorConfiguration="ClientCertificateBehavior"
        name="wsHttpBinding_IService1" />   
    </client>   
We have specified binding element as wshttpbinding which is similar to that of WCF Service. Next we have specified the endpoint behaviour with certificate validation mode as PeerOrChaintrust. Please refer to the comment mentioned above the tag certificateValidationMode. Hence while moving the deployment to production make sure that you have valid certificate issued by CA. In endpoint just replace the 7493 by your respective port number.
Add sample web form to consume WCF Web role locally -
Now add a web form in the WebRole1 project named as SamplePage.aspx and in page_load event add following code –
namespace WebRole1
{
    public partial class SamplePage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            WebRole1.ServiceReference1.Service1Client service1 = new ServiceReference1.Service1Client();
            service1.ClientCredentials.UserName.UserName = "MyUser";
            service1.ClientCredentials.UserName.Password = "My#Password";
            string result =  service1.GetData(5);
            Response.Write(result);


        }
    }
}
The username and password specified above are same as the one specified in custom validator in WCF Service web role. Now right click WebRole1 project and select Debug->start new instance. First the custom username validator’s validate method is called making sure that authentication of WCF web role is working fine.
The output should show message as “You Entered: 5.”
This completes the configuration of Azure WCF Web Role using wshttpbinding over http in development environment.
Right now I have hardcoded the username and password in custom validator class. In real scenario, it may be read from database.

Configure port and endpoint for Roles in cloud service -
Now next step is to configure WCF Web role in Azure cloud service using wshttpbinding.
Open ServiceDefinition.csdef file and make sure that the WCF Web role endpoint is configured for http and port 8080 where as Webrole1 is configured for http port 80.
Add certificate to cloud service on Azure Management Portal -
Now I here assume that, you already have a cloud service, storage account created in Azure subscription. Open the cloud service from Azure Management portal and upload certificate localhost.pfx file used in this project. I hope you already have exported the certificate by following the steps mentioned in blog link given above.



I am using localhost certificate here however in real world, using self signed certificate for production deployment is a measure threat. This is only for demo purpose. For production deployment consider a certificate issued by Trusted Authority.

Change WCF End point of WebRole to cloud Service URL -
Now we need to change the endpoint address in WebRole1 project as now it should refer to azure cloud service hosted WCF web role URL. As described above we have marked port 8080 for Azure WCF Web role and my cloud service URL let’s say – kunalwcfdemo.cloudapp.net then my WCF web role URL will be – http://kunalwcfdemo.cloudapp.net:8080/Service1.svc
This is the URL of my endpoint and it should be added in web.config file of WebRole1 project ad comment the localhost URL. So modify the client tag of web.config of Webrole1 project as follows –
<client>
      <!--<endpoint address="http://localhost:7493/Service1.svc"
        binding="wsHttpBinding" bindingConfiguration="wsHttpBinding_IService1"
        contract="ServiceReference1.IService1"
        behaviorConfiguration="ClientCertificateBehavior"
        name="wsHttpBinding_IService1" />-->
      <endpoint address="http://kunalwcfdemo.cloudapp.net:8080/Service1.svc"
        binding="wsHttpBinding" bindingConfiguration="wsHttpBinding_IService1"
        contract="ServiceReference1.IService1"
        behaviorConfiguration="ClientCertificateBehavior"
        name="wsHttpBinding_IService1" >
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>
    </client>
Also it might be possible that, the ServiceReference1 might be still pointing to localhost url of WCF web role. Therefore right click

Important:- Adding localhost certificate to Trusted Store of Web Role Instance VM -
Publish the cloud service project. Make sure that you enable remote desktop for the both roles while publish. We will need to make RDP to Web Role machine NOT WCF Role machine and we will need to add localhost certificate in Trusted People store of current user, local machine on Web Role instance virtual machine. So copy localhost.pfx to the desktop of web role instance.
It should be already present in Personal Store of Local Machine. Add it to Trusted People of Local Machine and trusted People of Current User.
Please note that we are not making any change in WCF Web role VM.

Change in Web role VM is required because we are using PeerOrchainTrust and certificate is self signed. If we are using certificate issued by trusted authority and certificate validation mode ChainTrust then this step may not be required. As this tutorial is for demo purpose and we are using self signed certificate we have to add certificate manually by making RDP to web role instance.

Set the SamplePage.aspx as start page for Webrole1 –
If you wish to set any .aspx page as start page of your web role project then please follow the instruction given at this link –

Hushhhhhhhhhhhh….Long process but we are done here…
You should be able to access the WCF web role URL as – 



Note - If the 8080 port in blocked in your organizations network you won’t be able to access it. J
Then you should be able to access Web role URL –



Well just replace the name kunalwcfdemo with your cloud service…I have removed this service from azure subscription to save on cost.
If you need source code of this project, comment your email and I will share it with you.

Hope this whole tutorial helped you. Suggestions are welcome…

Thanks for reading..
Cheers…
Happy WCF…Azuring!!!...