Installing the Azure Management Certificates

This is the next post on Getting Started developing on Azure with Visual Studio 2010. Starting to develop on Azure with Visual Studio can be a lot to eat the first time. Getting Visual Studio ready, including installing the Management Certificates and so on is not a simple task (the first time anyway). So that is why I made this little walk-through series on starting to develop on Azure… In the first part you’ll build and run your first project on the Azure Compute Emulator, which is the local test version of the cloud. In this part you’ll get Visual Studio ready to directly publish your solution in the cloud by installing the management certificates and in part 3 you will create the Hosted Service and storage account to actually deploy from Visual Studio. 1.2 Deploying your solution to the cloud Now we’re ready to deploy to the actual cloud environment. Start by logging on to the Azure Management Portal, which is at . Open the Hosted Services tab, and select Management Certificates: If you just started with Azure development you will not have any certificate here. To make Visual Studio integrate better with the management portal (actually with the management API’s) we need to upload a certificate here so your Visual Studio can publish projects to the cloud. This is easily done with Visual Studio. 1.1.3 Installing the Management Certificate: Go back to Visual Studio with the cloud project open. Right-click the cloud project and select Publish… The Deploy Windows Azure project dialog should open: With this dialog you can publish your project. The first option will create the package, but then you have to deploy it using the Management Portal. The second option will do this for you. In the first drop-down you need to select a Management Certificate, or create a new one. Select Add… from the Credentials drop-down. The Windows Azure Project Management Authentication dialog opens: Select <Create…> from the first drop-down. Enter a friendly name for your certificate. I call mine AzureManagment. Now click the View button. This will allow use to export the certificate’s public key using the Details… tab: Click on the Copy to File button. This opens the Certificate Export wizard. Click next. Choose “Do not export the private key”: Click Next> twice, then choose a filename for the certificate. Hit Next> then Finish. Your certificate should be exported now. Go back to the management portal (, to the Management Certificates. Click on the Add Certificate button and select your previously exported file. Click Ok and wait for the import to complete. Your certificate should be added, and now you need to copy the subscription-id back to Visual Studio. It is right there in the properties window of the certificate: So copy it, go to Visual Studio to where the Windows Azure Project Management Authentication is waiting. Copy the subscription-id and name it: Click OK. In the next blog post we will add a hosted service and storage account and deploy the solution…

Getting started developing on Azure with Visual Studio 2010

Starting to develop on Azure with Visual Studio can be a lot to eat the first time. Getting Visual Studio ready, including installing the Management Certificates and so on is not a simple task (the first time anyway). So that is why I made this little walk-through series on starting to develop on Azure… In this part you’ll build and run your first project on the Azure Compute Emulator, which is the local test version of the cloud. In part 2 you’ll get Visual Studio ready to directly publish your solution in the cloud by installing the management certificates and in part 3 you will create the Hosted Service and storage account to actually deploy from Visual Studio. 1.1 Azure Lab – Getting started developing In this walk-through you will learn how to develop with Visual Studio 2010 on Azure. To be able to do this you need to have the latest Azure SDK with Visual Studio tools installed (SDK 1.4 at time of writing), and you should also have a valid Azure account. 1.1.1 Creating the Azure project Start Visual Studio 2010 and create a new cloud project, calling it MyFirstCloudProject: Click on Ok. The New Windows Azure Project dialog should open: Click on the ASP.NET Web Role and click the > button. Then rename the project by clicking on the rename button: Call it MyFirstWebRole: Click OK. Add a button to the web form: Implement its click event as follows: Code Snippet System.Diagnostics.Trace.WriteLine("Hello from Azure!"); To enable Tracing to the Windows Compute Emulator, add following configuration to your web.config (line 6 to 9 should be added): Code Snippet <listeners> <add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics"> <filter type="" /> </add> <add type="Microsoft.ServiceHosting.Tools.DevelopmentFabric.Runtime.DevelopmentFabricTraceListener, Microsoft.ServiceHosting.Tools.DevelopmentFabric.Runtime, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="DevFabricListener"> <filter type="" > </filter> </add> </listeners> Open the Solution Explorer and make sure that the Azure project is the start project. Run your solution by pressing F5. Note that Visual Studio will package your code and upload it to the Compute Emulator. If not already running, the compute emulator (the little Azure icon in the system tray) will also be started. Right-click the Azure icon in the system tray and choose “Show Compute Emulator UI”. After a while your browser will display the web site and the emulator will display loggings: This window shows you output as your web role gets started, etc… You can add some more by clicking the button. This should write something to the emulator: Try placing a breakpoint on the button’s event handler. Click the button. Visual Studio should stop on the breakpoint. If your code was a little more complicated this would allow you to debug it. In the next blog we will look at installing the management certificates to run this same code in the cloud, deploying it with Visual Studio 2010.

Creating and Using Custom Performance Counters in Windows Azure

Building software, especially software running on servers, requires some way to look “inside” the running application. Using the debugger is one way, but you cannot use a debugger on production applications. A better way is to use performance counters. These give you a way to see things, like how hard the CPU working, but also how many orders have been processed by your system. The first performance counter is provided by the system, the latter you can build yourself. Before Azure SDK 1.3 you couldn’t create your own performance counters because your code doesn’t get write access to the region of the registry where you register your custom performance counters. But with elevated startup tasks this is easy. In the blog post I will show you how you can create a startup task to create custom performance counters, and how to use them in your role. Commence by creating a new Visual Studio Cloud project. Add a single worker role. We’ll use this role to illustrate using a performance counter. Add another project, now a Console project (call it InstallPerfCounters). We’ll use this console application as the startup task. Implement the InstallPerfCounters console project as follows: Code Snippet class Program {   static void Main(string[] args)   {     const string categoryName = "U2U";     const string categoryHelp = "U2U demo counters";       if (!PerformanceCounterCategory.Exists(categoryName))     {       var counters = new System.Diagnostics.CounterCreationDataCollection();       counters.Add(new CounterCreationData       {         CounterName = "# secs/running",         CounterHelp = "How long has this been running",         CounterType = PerformanceCounterType.NumberOfItems32       });         var category = PerformanceCounterCategory.Create(categoryName,         categoryHelp, PerformanceCounterCategoryType.MultiInstance, counters);     }   } } This uses the same kind of code you would use anywhere else to create new performance counters. Now we need to install this as a startup task. Add a folder to the worker role project, calling it startup. We need to add two files here, one the console project we just made, and a command file. To copy the executable, let’s make first sure we’re using the release version at all time. Open the configuration manager: Select Release as the configuration: Build your project, ensuring everything compiles nicely. Now right-click the startup folder from the worker role project and select Add Existing Item… Browse to the release folder of the console project, select the executable and choose Add As Link from the drop-down: This should add the executable to the startup folder. Select it, and select Copy Always in the properties folder: Now we are ready to add the command file. Don’t use Visual Studio for this, because it will add the Byte Order Mark which is not supported by Azure. The easiest way to do this is by right-clicking the startup folder, and select “Open Folder in Windows Explorer”. Then right-click the folder’s contents, and add a new text document: Rename it to installcmd.cmd. Go back to Visual Studio. In Solution Explorer select “Show All Files”: The installcmd.cmd should appear, you can now right-click it and select “Include in project”. Edit it to the following contents: Code Snippet %~dp0InstallPerfCounters.exe /q /log %~dp0pc_install.htm exit /b 0   Now open the ServiceDefinition.csdef file from your cloud project and add a startup task: Code Snippet <Startup>   <Task commandLine="startup\installCmd.cmd" executionContext="elevated" taskType="simple" /> </Startup>   This should take care of installing the performance counter. Now let’s use it in our worker role. First we need to create the performance counter instance, and then update it. In this simple example we’ll make the counter increment once each second. So implement the worker role’s run as follows: Code Snippet public override void Run() {   // This is a sample worker implementation. Replace with your logic.   Trace.TraceInformation("UsingPerfCounters entry point called");     const string categoryName = "U2U";     PerformanceCounter secsRunning = new PerformanceCounter()   {     CategoryName = categoryName,     CounterName = "# secs/running",     MachineName = "." /* current machine */,     InstanceName = Environment.MachineName,     ReadOnly = false   };   var counterExists = PerformanceCounterCategory.Exists(categoryName);     while (true)   {     Thread.Sleep(TimeSpan.FromSeconds(1));     if (counterExists)     {       secsRunning.Increment();     }     Trace.WriteLine("Working", "Information");   } }   Publish this solution in Azure, not forgetting to turn on Remove desktop. Also note that I turn in IntelliTrace, whichh is great for debugging those nasty deployment problems… When you complete publishing you can now remote desktop to the instance and use PerfMon to look at your custom performance counter. Or you can use Azure Diagnostics….

Azure Inter-role communication using callback instead of queues

I’m currently playing with Azure and the Azure training kit, and I learned something cool today. When you work with Azure you can setup multiple worker roles for your Azure application. If you want to make these roles talk to one another you can use the queuing mechanism which is part of Azure. But you can also use WCF dual interface mechanism. Imagine you want to build a chat application using Azure and WCF. In this case you define a worker role that exposes a dual interface like this: Code Snippet [ServiceContract(     Namespace = "urn:WindowsAzurePlatformKit:Labs:AzureTalk:2009:10",     CallbackContract = typeof(IClientNotification),     SessionMode = SessionMode.Required)] public interface IChatService {   /// <summary>   /// Called by client to announce they are connected at this chat endpoint.   /// </summary>   /// <param name="userName">The user name of the client.</param>   /// <returns>The ClientInformation object for the new session.</returns>   [OperationContract(IsInitiating = true)]   ClientInformation Register(string userName);     /// <summary>   /// Sends a message to a user.   /// </summary>   /// <param name="message">The message to send.</param>   /// <param name="sessionId">The recipient's session ID.</param>   [OperationContract(IsInitiating = false)]   void SendMessage(string message, string sessionId);     /// <summary>   /// Returns a list of connected clients.   /// </summary>   /// <returns>The list of active sessions.</returns>   [OperationContract(IsInitiating = false)]   IEnumerable<ClientInformation> GetConnectedClients(); } The IClientNotification interface is the call-back interface which is implemented by the client of the service. The client calls the Register method on the server, which then can keep track of the client by using the callback interface: Code Snippet IClientNotification callback =   OperationContext.Current.GetCallbackChannel<IClientNotification>();   If you host the service as a single instance, all clients will register to the same service, so this service can easily track each client. But if you grow and start using multiple instances of your service in Azure, each client will register to a single instance, so each instance will know only about its own clients. If two clients, registered to different instances, want to communicate, the services will have to handle the communication for this. The solution is easy, make them also expose the IClientNotification callback service interface using internal endpoints, so they can communicate to each other: Code Snippet public class ChatService : IChatService, IClientNotification   Of course each service will have to be able to find the other service instances. This you can do with the RoleEnvironment class, which you can use in your worker role class: Code Snippet var current = RoleEnvironment.CurrentRoleInstance; var endPoints = current.Role.Instances                 .Where(instance => instance != current)                 .Select(instance => instance.InstanceEndpoints["NotificationService"]);   This does require the worker role to define an internal endpoint. You can do this in Visual Studio 2010. Select the worker role’s properties, go to the endpoint tab and enter an internal endpoint: The rest of the code is straightforward (of your comfortable with WCF that is) and can be found in the Azure Training Kit (look for the Worker Role Communication lab).

Looking at generated queries for LINQ 2 SQL and EF with Visual Studio 2010 Intelli-Trace

When you use LINQ to SQL or Entity Framework you might wonder from time to time what the actual SQL is that was generated by the runtime. Both frameworks have their specific way to allow you to look at this, but require some extra code. Of course you shouldn’t forget to remove this code. Visual Studio 2010 Ultimate gives you another way to look at the generated SQL, without having to change to code. When you turn on intelli-trace, the intelli-trace log will show you the SQL. For example running some LINQ to SQL code will show up as: The ADO.NET entries show the actual query being executed. Note that older queries will also show in here, so if you forgot to look at the query at time of execution, you can scroll back to it later!

Add Search support for Add Reference

Visual Studio 2010 now comes packed with too many assemblies. The list of assemblies to pick from in the Add Reference dialog is now a little too large for my taste. Today, while browsing around in the Visual Studio 2010 Extension Manager, I found the Search References extension: After installing it my Add Reference dialog now looks like this: And typing in the search box instantly filters the list of assemblies. Nice. Microsoft should have provided this out of the box! It is also a nice sample of how extensible Visual Studio is.

Keeping a file checked out after check-in with Team System

This week I got a question whether it is still possible to keep some file checked-out during a check-in. This is something you can do with Source Safe for example. To be honest I had no idea if this is possible, so I decided to have a look. So the answer is yes (although in general I think this is dangerous because this way people tend to check out files for long periods…). Simply go to options and check the fourth check-box from the top.

Pex and Code Contracts

I’m currently experimenting with Pex, Moles and Code Contracts, and I wondered what effect code contracts have on Pex tests. So I build this simple piece of code: 1: public class Demo 2: { 3: public int Foo(int a, int b) 4: { 5: if (a < 0) 6: return a; 7: else if (a > 0) 8: return b; 9: else 10: return a + b; 11: } 12: } Then I make Pex generate its Parameterized Unit Tests (PUTs). This generates the following test: 1: [PexClass(typeof(Demo))] 2: [PexAllowedExceptionFromTypeUnderTest(typeof(InvalidOperationException))] 3: [PexAllowedExceptionFromTypeUnderTest(typeof(ArgumentException), AcceptExceptionSubtypes = true)] 4: [TestClass] 5: public partial class DemoTests 6: { 7: /// <summary>Test stub for Foo(Int32, Int32)</summary> 8: [PexMethod] 9: public int Foo( 10: [PexAssumeUnderTest]Demo target, 11: int a, 12: int b 13: ) 14: { 15: int result = target.Foo(a, b); 16: return result; 17: // TODO: add assertions to method DemoTests.Foo(Demo, Int32, Int32) 18: } 19: } I just leave the code, right-click on The Foo method of the DemoTests class, choose “Run Pex explorations” and I get this: As you can see the exploration calls my code with negative, zero and positive values. What happens when I add a contract stating that a should be positive? 1: public class Demo 2: { 3: public int Foo(int a, int b) 4: { 5: Contract.Requires(a > 0); 6: if (a < 0) 7: return a; 8: else if (a > 0) 9: return b; 10: else 11: return a + b; 12: } 13: } Only line 5 was added, but if I run the pex explorations again I get:   The effect is that Pex now doesn’t explore negative numbers, because it can deduce from the contract not to even try. What if I use a contract to state that b should be negative? 1: Contract.Requires(b < 0); Again Pex sees this and explores my code with negative b: One more. When I change my code to do a little more with b, like this: 1: public int Foo(int a, int b) 2: { 3: Contract.Requires(a > 0); 4: Contract.Requires(b < 0 || b > 10); 5: if (a < 0) 6: return a; 7: else if (a > 0) 8: { 9: if (b > a) 10: return a; 11: else 12: return b; 13: } 14: else 15: return a + b; 16: } and when I run the explorations again: So, you can guide Pex by supplying contracts on the arguments of your methods.

Overloading & Co/Contra-variance could break your code!

Co and contra-variance were introduced to VB.NET and C# to make working with certain classes more natural (“because it should work”). But beware, I was experimenting a bit with this and found following possible breaking change. I started with these two classes: C# 1: public class Person 2: { 3: // ... 4: } 5:  6: public class Vip : Person 7: { 8: // ... 9: } VB.NET 1: Public Class Person 2: ' 3: End Class 4:  5: Public Class Vip 6: Inherits Person 7: ' 8: End Class Then I added a collection of people: C# 1: public class PersonList 2: { 3: public void Add(object obj) { 4: // ... 5: } 6:  7: public void Add(Person p) 8: { 9: // ... 10: } 11:  12: public void Add(IEnumerable<Person> people) 13: { 14: foreach (Person p in people) 15: { 16: // ... 17: } 18: } 19: } VB.NET 1: Public Class PersonList 2: Public Sub Add(ByVal obj As Object) 3: ' 4: End Sub 5:  6: Public Sub Add(ByVal person As Person) 7: ' 8: End Sub 9:  10: Public Sub Add(ByVal list As IEnumerable(Of Person)) 11: ' 12: End Sub 13: End Class Next I create a PersonList collection and then add a list of Vip’s: C# 1: class Program 2: { 3: static void Main(string[] args) 4: { 5: PersonList people = new PersonList(); 6:  7: List<Vip> others = new List<Vip> { 8: new Vip(), new Vip() 9: }; 10:  11: people.Add(others); 12: } 13: } VB.NET 1: Sub Main() 2: Dim people As New PersonList 3: Dim others As New List(Of Vip)(New Vip() {New Vip(), New Vip()}) 4: people.Add(others) 5: End Sub When I compile this in Visual Studio 2008 the first Add method, taking the object argument, gets called. But with Visual Studio 2010 (using the .NET 4 target) the third Add method gets called. This is because now IEnumerable<T> is co-variant and will now convert the List<Vip> to an IEnumerable<Person>. Ok, granted. This is NOT something you will see every day, but if you ever encounter it, this might be very confusing. This kind of problem can also occur with extension methods and user-defined conversions…