Vadim's Weblog

Never stop learning.

Archive for the ‘.Net’ Category

Capitalize only first character. (C#)

Posted by Vadim on October 9, 2013

Once in a while, you may need need to capitalize only the first character of a word. Like everything else in programming, there’s more than one way to solve this problem. In this post, I’m going to explore three different ways to capitalize the first letter of a word, and then let you know which one I prefer.

1. String manipulation solution.
private string UpperFirst(string text)
{
return char.ToUpper(text[0]) +
((text.Length > 1) ? text.Substring(1).ToLower() : string.Empty);
}

 

This solution is straightforward. First, capitalize the initial character of the text, and then append the rest. Next, we test if our text has more than 1 character. If this is text with multiple characters, we convert the rest of the text to lowercase, in case there are any uppercase letters.

2. LINQ solution.
private string UpperFirst(string format)
{
return format.First().ToString().ToUpper() +
String.Join("", format.Skip(1)).ToLower();
}

 

LINQ solution is also easy to follow and understand. We get the first character, and then we convert it to String (because the char type doesn’t have instance implementation of ToUpper()). Then, like in the previous solution, we append the rest of text.

3. TextInfo.ToTitleCase solution.
private string UpperFirst(string text)
{
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text.ToLower());
}

 

This solution is taking advantage of the ToTitleCase method. It looks simple, but it’s not exactly like our two previous solutions. The problem with this solution is that it’s going to capitalize every word in the text.  For example: if your text has the value “hello world”, the result of this solution will be “Hello World” and not “Hello world” as in the two earlier examples. If you need to capitalize every word in your text, use this solution. Otherwise, use one of the earlier solutions.

The best solution for me.

Personally, the 1st solution looks the best. There are two reasons why I think solution #1 is the best:

  1. I believe it’s easier to read, but readability is very subjective.
  2. It performs better. I iterated each solution 1,000,000 times, and the first solution performed the fastest.

Below is the table of my performance test, in case you’re interested. It shows the time in milliseconds for 1,000,000 iterations.

Solution Time
String manipulation

201

LINQ

511

TextInfo.ToTitleCase

361

 

Please let me know if you can think up other implementations for capitalizing letters.

Technorati Tags: ,,,

Posted in C# | Tagged: , , , | 2 Comments »

Detect when another site is unavailable. (404 detection)

Posted by Vadim on December 25, 2010

A long time ago we used to store our code on punched cards.  Since that time, our development tools improved a lot.  Thanks to more powerful languages and tools, it became easier for us to write code, and as a result, our applications became more and more complex.  In 1986 Fred Brooks predicted exactly that in his article “No Silver Bullet”.  Today, any modern application uses third party libraries or components.  Our web apps need to integrate with other sites to use their services. But what do you do if the third party site is down?

At first, the problem doesn’t seem that difficult, but then I realized that it’s impossible to detect with JavaScript when another site is unavailable. (Please let me know if I’m wrong.)  If it would be possible to do this with client scripting, it would be huge security hole.  Since the release of Netscape Navigator 2.0 in 1996, browsers prevent access to most methods and properties across pages on different sites.  Today, this policy is known as Same Origin Policy.

The solution I came up with is to ping the third party host on the server side before JavaScript is loaded.  If I get a good response, then I proceed with my JavaScript; otherwise, it’s redirected to my error page.

Here’s a sample how you can check if the host available with ASP.NET:

protected void Page_Load(object sender, EventArgs e)
{
    HttpWebResponse response;
    try
    {
        var request = 
            (HttpWebRequest)WebRequest.Create("http://www.someSite.com/camdsa");
        response = request.GetResponse() as HttpWebResponse;
    }
    catch (WebException webException)
    {
        Response.Redirect("ErrorPage.aspx?status=" + webException.Status);
        return;
    }
}

If GetResponse() throws a WebException, it means that something went wrong with our request.  We can figure out what’s wrong by analyzing the WebException Status and Response properties.

kick it on DotNetKicks.com

Posted in .Net, ASP.NET, C# | Tagged: | 1 Comment »

NuGet Upgrade on 12/10/10

Posted by Vadim on December 10, 2010

There’s a new upgrade for NuGet.  To update it just go to Tools –> Extension Manager in Visual Studio to lunch Extension Manager dialog. In Updates you’ll see an update for NuGet Package Manager.  It will ask you to restart your VS.

Posted in NuGet | Tagged: | 1 Comment »

Baby steps to create a NuGet Package.

Posted by Vadim on December 8, 2010

You probably heard about NuGet (formally known as NuPack), an open source package management system for the .NET from Microsoft.  Jeff Kwak, who works with me at Ultimate Software, recently wrote a nice post about how to create a NuGet Pakage.  Jeff’s article inspired me to create a package for my own open source project, SystemWrapper.   In this post I want to describe step by step how I did it.

Step 1: Create a NuSpec file.

NuSpec file is an xml file that contains the metadata for a package.  I’ll try to describe every field of NuSpec format with an example.

In this first step we’ll going to use the minimum set of fields.

Element
Description
id The identifier for the package.  It used as a partial name of the package.
version The package version.  Also used as a partial name of the package.
authors Author name.  Use a comma to separate multiple authors.
description You know what it is.
<package>
  <metadata>
    <id>SystemWrapper</id>
    <version>0.3.5.0</version>
    <authors>Vadim Kreynin</authors>
    <description>
      SystemWrapper is a library that wraps .NET classes for system resources like System.IO.FileInfo, System.Reflection.Assembly, and many other classes so you can easily mock them.
    </description>
  </metadata>
</package>

I named the xml SystemWrapper.nuspec.  I believe that it is a good logical name for NuSpec file.

One of the way to add a package is to use Add Library Package Reference dialog.  I’ll talk more about adding a package and Add Library Package Reference dialog later in this article but for now I want to show where NuSpec fields a re used.  Bellow is the image that describes where above NuSpec metadata elements used in the dialog.

musthaveNuGetFields

Step 2: Build the package.

First you need to download NuGet.exe command line tool.

Now when we have NuGet.exe, we are ready to create our SystemWrapper NuGet package.  Fire up your Command Console and type the following line.
NuGet.exe pack SystemWrapper.nuspec

If everything runs at it supposed to, you should see systemwrapper.0.3.5.0.nupkg file in your Windows Explorer.

As you can see the name of the file is [id].[version].nupkg.  id and version from our NuSpec file.

Step 3: Publish the package.

To release System Wrapper to the world we need to contribute to NuGet packages on CodePlex.  In this example I’m going to show how to host System Wrapper NuGet package locally.  You can follow this technic to host packages for your company.  I learned how to host NuGet packages locally from a great Phil Haack’s post.

First, I create a directory for my packages.  It has an original name ‘packages’.

packagesdir

Next, we need to add another package source.  Out of the box you should have only one package source which named ‘NuGet official package source’.  We are going to create another package source and I’m going to call mine ‘Vadim’s package source’.  I think that this is going to cement my legacy.

In order to add a package source in Visual Studio we need to go to Tools –> Options.  Inside the option dialog box select Package Manager and enter values for Name and Source and press Add button and then OK to close the Options dialog.

AddPackage

You also can get to this dialog by pressing Settings button in Add Library Package Reference dialog, which is the first image of this post.  The button located in the lower left corner of the dialog.

Step 4: Find the package in Visual Studio.

There are two ways we can browse for our package.  One way is using Package Manager Console which is Powershell based. Another one is Add Library Package Reference dialog that I mentioned earlier.

First let me describe how we can browse using Package Manager Console.  We can lunch the console by selecting View –> Other Windows –> Console from the menu or simply press Ctrl+W, Ctrl+Z.Navigation2PackageManagerConsole

SelectPackageSourceFromPMCAfter console is loaded, we need to select our package source.  Just pick it from the Package source drop down box.  In my case it’s “Vadim’s package source”.  Next, type List-Package at PM> prompt.  See the result bellow.

PMCOutput

I don’t know why I cannot see my description in Package Manager Console.  It shows fine in Add Library Package Reference dialog.  Let me know if you have an answer for me.

AddRefOptionsNow let me show how you can browse for the package using Add Library Package Reference dialog.  The way I do it is just right click on References in the project to see my  add options.  Select “Add Library Package Reference…” to display the dialog.  The dialog has three panels.  The first panel has three sections: Installed packages, Online, and Updates.   “Installed packages” shows the package that installed for specific project.  The second one “Online” shows packages that are available.  We want to chose this option.  Select your package source.  The third option is updates.

The second panel shows the list of packages.  The third panel shows details of the selected package.

musthaveNuGetFields

It doesn’t make scenes for us to install the package at the moment because we only describe the package but doesn’t add any libraries to the project.

Step 5: Add SystemWrapper.dll to the package.

Our goal is to add SystemWrapper to the project.  It means that we need to add assembly reference to SystemWrapper.dll. It’s very easy to do, we just need to add files element to our NuSpec file. files element must be on the same level as metadata element.

Here’s a fragment that we add to NuSpec metadata:

<files>
   <file src="SystemWrapper\bin\Release\*.dll" target="lib" />
</files>

file element has two attributes src and target.  I just want to let you know that src is a path that relative to the nuspec file.  Our target attribute has a value ‘lib’, it means that dlls under SystemWrapper\bin\Release will become assembly references on install.  In our case it’s going to be only one dll.  You can get more details on your own by reading the NuSpec File Element Specification.

Here’s the complete NuSpec file:

 

<package>
  <metadata>
    <id>SystemWrapper</id>
    <version>0.3.5.0</version>
    <authors>Vadim Kreynin</authors>
    <description>
      SystemWrapper is a library that wraps .NET classes for system resources like System.IO.FileInfo, System.Reflection.Assembly, and many other classes so you can easily mock them.
    </description>
  </metadata>
  <files>
    <file src="SystemWrapper\bin\Release\*.dll" target="lib" />
  </files>
</package>

After we updated NuSpec file, we need to repeat step 2 (Build the package).

Step 6: Install the package.

Once again you can install either from Package Manager Console or from Add Library Package Reference dialog.  It’s strait forward to install it from Add Library Package Reference dialog, you just press the Install button.  After the installation, I have SystemWrapper in my Installed packages.  I can easily uninstall it by pressing the Uninstall button.  How easy is that?  Also if I look in Online section, I can see that instead of an Install button there’s a green check mark for my package.

In Package Manager Console I just type Install-Package SystemWrapper at PM> prompt.

PM> Install-Package SystemWrapper
Successfully installed 'SystemWrapper 0.3.5.0'
Successfully added 'SystemWrapper 0.3.5.0' to PackageObjectLibrary
You can uninstall the package by typing Uninstall-Package SystemWrapper.
For more details check out Package Manager Console Commands.

Step 7: Display more information about the package.

When developers browse for packages, they probably would like to more information about a package than just a description.  Adding projectUrl element to NuSpec file will point users to the resource with more details.
Here’s an example for System Wrapper:
<projectUrl>http://systemwrapper.codeplex.com/</projectUrl>

You might also want to add a link to your license terms.  Once again you need to add another field to the NuSpec file.  This time we need to add licenseUrl.  If you don’t want a developer to install your package unless she accepts the license terms, than you need to add requireLicenseAcceptance element. The xml might looks like this:

<licenseUrl>http://systemwrapper.codeplex.com/license</licenseUrl>
<requireLicenseAcceptance>true</requireLicenseAcceptance>

When a user tries to install the package, she will see a dialog similar to the one bellow:

licenseAcceptance

You also can specify your own icon instead of default blue NuGet icon that appears in Add Package Reference dialog .  The element for an icon is iconUrl.  The icon should be a 32×32 pixel PNG file with a transparent background.

<iconUrl>http://mysite.com/32_button_green.png</iconUrl>

The complete NuSpec file might look something like that:

<package>
  <metadata>
    <id>SystemWrapper</id>
    <version>0.3.5.0</version>
    <title>System Wrapper</title>
    <authors>Vadim Kreynin</authors>
    <description>
      SystemWrapper is a library that wraps .NET classes for system resources like System.IO.FileInfo, System.Reflection.Assembly, and many other classes so you can easily mock them.
    </description>
    <projectUrl>http://systemwrapper.codeplex.com/</projectUrl>
    <iconUrl>http://systemwrapper.codeplex.com/32_button_green.png</iconUrl>
    <licenseUrl>http://systemwrapper.codeplex.com/license</licenseUrl>
  </metadata>
  <files>
    <file src="SystemWrapper\bin\Release\*.dll" target="lib" />
  </files>
</package>

extraNuGetFields

 

Summary

I know that I didn’t talk about dependencies or modifying config files at all.  I just try to give a simple example to follow.  I hope that it can help you to get started with NuGet.  Here’s some references I would recommend for you to read:

Posted in NuGet | Tagged: | 6 Comments »

MbUnit 3.2 makes it easier to work with Xml

Posted by Vadim on July 18, 2010

In my previous article I mentioned about upcoming new release of Gallio /  MbUnit.  Feel free to download the Release Candidate and try it for yourself.  In this post I’ll talk about another new feature.

Not everybody like XML but everyone had to work with it. It’s used for many different purposes. Most people use it for configuration like web.config or .csproj / .vbproj. Some people use this format for data, others for communication. I believe that it’s going to be very hard to find a .NET developer that didn’t work with XML. If you do work with XML and you like to unit test your code, than I have good news for you. With new upcoming version 3.2 of MbUnit you are going to get better support to unit test your XML code. The Gallio team gives us three new Assert methods to test XML:

  • Assert.Xml.AreEqual
  • Assert.Xml.Exists
  • Assert.Xml.IsUnique

Assert.Xml.AreEqual

Let start by showing a simple and probably very obvious example:

        [Test]
        public void TestXmlAreEqualWithString()
        {
            const string xmlString =
                "<Books>" +
                "  <Book title='C# in Depth' />" +
                "  <Book title='Learing C#' />" +
                "</Books>";

            Assert.Xml.AreEqual(xmlString, XElement.Load(new StringReader(xmlString)).ToString());
        }

In the example above we’re comparing XML strings.  There’s another overload that instead of strings takes TextReader objects.

        [Test]
        public void TestXmlAreEqualWithTextReader()
        {
            const string xmlString =
                "<Books>" +
                "  <Book title='C# in Depth' />" +
                "  <Book title='Learing C#' />" +
                "</Books>";

            TextReader textReaderXml = new StringReader(xmlString);
            Assert.Xml.AreEqual(
                new StringReader("<Books><Book title='C# in Depth'/><Book title='Learing C#'/></Books>"),
                textReaderXml);
        }

As you can see, the formatting of XML is different, but our test still succeeds since it represents the same XML.

Let’s now make a small test.  We know that XML is case-sensitive  language.  What is going to happen if you we mismatch case?  Let’s make expected value for one of the book title ‘Learning c#’ instead of ‘Learning C#’.

        [Test]
        public void TestXmlAreEqualWithString()
        {
            const string xmlString =
                "<Books>" +
                "  <Book title='C# in Depth' />" +
                "  <Book title='Learing C#' />" +
                "</Books>";

            Assert.Xml.AreEqual(
                "<Books><Book title='C# in Depth'/><Book title='Learing c#'/></Books>",
                XElement.Load(new StringReader(xmlString)).ToString());
        }

After executing this test, we will see the following error that conveniently highlights the problem area:

AreEqual_error

Wait a second.  But what if in my application I don’t care about case-sensitivity for my data?  Well, in this case guys from the Gallio team provided us with an optional parameter of type XmlOptions.  Therefore, if we add XmlOptions.Loose parameter to our Assert.AreEqual, our test is going to pass.

            Assert.Xml.AreEqual(
                "<Books><Book title='C# in Depth'/><Book title='Learing c#'/></Books>",
                XElement.Load(new StringReader(xmlString)).ToString(), 
                XmlOptions.Loose);

You can find more information on XmlOptions in the Gallio Wiki site.

 

Assert.Xml.Exists

This assertion method checks if an element or an attribute can be found in a specific XML document.

  • The first parameter of Assert.Xml.Exists method is an Xml document.   Like in Assert.Xml.AreEqual method you can represent Xml document as a string or a TextReader object. 
  • The second parameter is an Xml Path that can be either a string in format “/element[/element]:attribute” or an object that implements IXmlPathLoose interface.
  • The third parameter is already familiar to us XmlOptions object.

Let’s look at a specific example where will check if Book element exists. 

        [Test]
        public void TestXmlExistsForElement()
        {
            const string xmlString =
                "<Books>" +
                "  <Book title='C# in Depth' />" +
                "  <Book title='Learing C#' />" +
                "</Books>";

            // Xml Path as a string
            Assert.Xml.Exists(xmlString, "/Books/Book", XmlOptions.Default);
            // Xml Path as a IXmlPathLoose
            Assert.Xml.Exists(xmlString, XmlPath.Element("Books").Element("Book"), XmlOptions.Default);
        }

For completeness let’s show a separate example where we will be looking for title attribute.

        [Test]
        public void TestXmlExistsForElement()
        {
            const string xmlString =
                "<Books>" +
                "  <Book title='C# in Depth' />" +
                "  <Book title='Learing C#' />" +
                "</Books>";

            // Xml Path as a string
            Assert.Xml.Exists(xmlString, "/Books/Book:title", XmlOptions.Default);
            // Xml Path as a IXmlPathLoose
            Assert.Xml.Exists(xmlString, XmlPath.Element("Books").Element("Book").Attribute("title"), XmlOptions.Default);
        }

In case an element or an attribute not found, Gallio will produce an error message similar to the one below:

Exists_error

Assert.Xml.IsUnique

This method takes the same parameters as Assert.Xml.ExistsAssert.Xml.IsUnique fails if an element is encountered more than once in Xml document.  I expect that you will not utilize this method as much as other two methods.

The following code is going to fail because we have two Book elements in out Xml.

        [Test]
        public void TestXmlIsUnique()
        {
            const string xmlString =
                "<Books>" +
                "  <Book title='C# in Depth' />" +
                "  <Book title='Learing C#' />" +
                "</Books>";

            // Xml Path as a string
            Assert.Xml.IsUnique(xmlString, "/Books/Book", XmlOptions.Default);
            // Xml Path as a IXmlPathLoose
            Assert.Xml.IsUnique(xmlString, XmlPath.Element("Books").Element("Book"), XmlOptions.Default);
        }

Here’s our error message:

IsUniqe_error

Last words.

I hope you find it useful and I didn’t waste mine and your time because my wife and kids never going get this hour back.

 Gallio wiki site is a great place to learn more about XML AssertionsGallio / MbUnit is an open source project and they always looking for new contributors.  If you consider joining the project, click here to learn how.

kick it on DotNetKicks.com

Posted in .Net, MbUnit | Tagged: , , | 3 Comments »

Assert.Count in MbUnit version 3.2

Posted by Vadim on July 18, 2010

The Gallio team is about to release version 3.2 of Gallio and MbUnit.  If you’re impatient and like to eat your cake hot before it cools down, then download the Release Candidate.  The new version has many new great features.  Click here to see the list of enhancements and here for the bug fixes.

One of the new features is Assert.Count.  It’s impossible to count how many times I wrote code that verifies number of items in the specified collection:

        [Test]
        public void Test()
        {
            var list = new List<int> {2, 3, 5};
            Assert.AreEqual(3, list.Count);
        }

Now with new 3.2 version I can write my code like this:

        [Test]
        public void TestCount()
        {
            var list = new List<int> { 2, 3, 5 };
            Assert.Count(3, list);
        }

I assume that for most people it doesn’t look like a huge improvement and it’s probably not, but it definitely makes code more readable and defines clear the intentions of the specific assertion.

I don’t expect to surprise anybody by telling you that it also works with arrays.

        [Test]
        public void TestArray()
        {
            Assert.Count(3, new[] { 1, 2, 3 });
        }

Actually it works with any object that implements IEnumerable interface even if doesn’t have Count or Length property like CredentialCache class.

        [Test]
        public void TestEnumerable()
        {
            var myCache = new CredentialCache
                         {
                             {
                                 new Uri("http://www.contoso.com/"),
                                 "Basic",
                                 new NetworkCredential("userName", "password")
                             },
                             {
                                 new Uri("http://www.contoso.com/"),
                                 "Digest",
                                 new NetworkCredential("userName", "password", "domain")
                             }
                         };
            Assert.Count(2, myCache);
        }

It even works with string types (of course it does, string also implements IEnumerable).

        [Test]
        public void TestString()
        {
            Assert.Count(5, "Vadim");
        }

kick it on DotNetKicks.com

Posted in .Net, MbUnit | Tagged: | 1 Comment »

How to display your assembly “Add References” dialog.

Posted by Vadim on July 11, 2010

In Ultimate Software (the company that I work for) we build all the assemblies in the same directory.  Let say it’s C:\Common.  When we need to reference an assembly, we browse to C:\Common directory and select a desired assembly.

I decided to look what we need to do to add our assemblies into .NET tab of “Add Reference” dialog box.  It’s quite simple actually.  All we need to do is to create a registry entry.

First lets assume that we want to reference AssemblyReference.dll that located in C:\Common directory.  It’s probably not going to surprise anybody if I tell you that you’ll not find it in “.NET” tab of Add Reference dialog.

.NetReference

As you can see it’s not there at the moment.  However, if we chose a “Browse” tab and navigate to C:\Common directory will be able to find it.

BrowseReference

I just want to point out that adding an assembly to GAC will not add that assembly to the .NET tab’s list.   It’s also not a good practice to install an assembly to the Global Assembly Cache, unless you want to share that assembly with other applications running on that computer. 

Therefore only thing we need to do add our assembly to .NET tab’s list is to create a unique sub-key under

HKLM\SOFTWARE\Microsoft\.NETFramework\.NETMinimumVersion\AssemblyFoldersEx\

If you’re running a 64-bit OS you will need to create it under:

HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\.NETMinimumVersion\AssemblyFoldersEx\

.NETMinimumVersion is the lowest .NET Framework version from which the assembly can be referenced.  In our example I chose version 2.0.50727 as you can see below.

After creating a new sub-key, we’ll change its default string value to the “C:\Common\” directory path.

RegistryReference

After restarting Visual Studio 2010, we can find our AssemblyReference assembly in .NET tab’s list of Add Reference dialog.

.NetAssemblyRef

In our example we added the sub-key under HKEY_LOCAL_MACHINE node that allows all the users on this system to see AssemblyReference.dll.  If we wanted only the current user to see this assembly, we would create our sub-key under HKEY_CURRENT_USER instead.

Note for VS 2008 and earlier:

For Visual Studio 2008 and earlier you need to add your sub-key under

HKLM\SOFTWARE\Microsoft\.NETFramework\AssemblyFolders\

kick it on DotNetKicks.com

Posted in .Net | 2 Comments »

AssemblyHelpers now works .NET 4 assemblies.

Posted by Vadim on May 9, 2010

assemblyhelper-thumb[1] More than two weeks ago I received an email from someone that AssemblyHelper tool doesn’t work with .NET 4 assemblies.

I first mentioned about the tool in Testing internals members with InternalsVisibleTo attribute article.

Here I just want to tell the tool is updated an you can use it against .NET 4 assemblies.  Of course, it still works with assemblies prior version 4.

Feel free to download the updated version.

kick it on DotNetKicks.com

Posted in .Net, TDD | Tagged: | 1 Comment »

Part 2: Configuration – Learning Azure with me.

Posted by Vadim on January 31, 2010

In Part 1 “Hello Azure” we briefly talked about the Service Configuration file (ServiceConfiguration.cscfg).  In that article we didn’t modify this file, we just accepted all the values provided by Cloud Service Visual Studio template.

Let look at this file and take it apart.

<?xml version="1.0"?>
<ServiceConfiguration serviceName="LearnAzure" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration">
  <Role name="LearnAzureWeb">
    <Instances count="1" />
    <ConfigurationSettings>
      <Setting name="DiagnosticsConnectionString" value="UseDevelopmentStorage=true" />
    </ConfigurationSettings>
  </Role>
</ServiceConfiguration>

image The root element ServiceConfiguration has only one attribute which is serviceName.  The serviceName attribute is required. If you omit this attribute, Visual Studio is going to complain about your XML during compilation.  You can see that this attribute has the same value as our Cloud Project which is LearnAzure.  The name of the service must match the name of the service in the service definition.  If you look inside ServicDefinition.csdef file, you’ll see that value for the name attribute in ServiceDefinition element is also LeanAzure.

ServiceConfiguration element can have only Role elements as children.  Because the only role we have is ASP.NET Web role, LearnAzureWeb, we can see only one Role element.  In case our project contained another role the Service Configuration file would reflect this fact.

Role element also has a single name attribute which is required.  The name attribute represents the name of the service and must match the name of the service in the service definition defined in the WebRole element.  The Role element can have following children elements:

  • Instances
  • ConfigurationSettings
  • Certificates

Looking at our ServiceConfiguration.cscfg file we can see that it contains ConfigurationSettings and Instances elements.

Instances Element

Before we start discussing the Instances element, let me tell you what I know about Microsoft datacenters that host Windows Azure applications.  Microsoft has many strategically placed datacenters that have no physical roof.  Inside each datacenter a lot of sealed shipping containers.  Each containers has inside anywhere from 1,800 to 2,500 servers.  One of these datacenters is located in Chicago.

Now back to our Instances element that has a required count attribute that represents number of instances of your application.  In case our Learn Azure application becomes a hit, we will need more computing power to run it.  We’ll request more power by increasing count value in the Instance element.  Each instance will be run on different server and probably in different container.  And I’m going to guess that it has  a very good chance that each instance will be executed in different datacenter.

<Instances count="5" />

Instances element is required and you can have only one element in each Role.

If you are not friendly with XML, you can modify Instance count using GUI in Visual Studio.  In your Cloud Project right click on the Role and select Properties or just press Alt+Enter.

image

In Configuration tab you can find Instance count and enter the desirable value.

ConfigurationSettings Element

If you’ve developed any .NET application, than ConfigurationSettings element concept should be very familiar to you.  You used this technique many times in your web.config or app.config files.  It serves the same purpose as appSettings element in .config file.

You can have only one ConfigurationSettings section in your Service Configuration file.  This element is not required that means that you can completely omit this section if you don’t set any custom settings.  ConfigurationSettings element can have any number of Setting elements. A Setting element is a mapping of a name to a string value.  A setting name must be declared in a service definition file (ServiceDefinition.csdef).

For example, in our LearnAzure application we hard coded “Hello Azure!” text in the Default.aspx file (See Part1).  We can easily make the hard coded text configurable.

First thing we’ll do is to add our setting name “myText” to the Service Definition file.

<Setting name="myText"/>

Below is complete ServiceDefinition.csdef file.

<?xml version="1.0" encoding="utf-8"?>
<ServiceDefinition name="LearnAzure" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition">
  <WebRole name="LearnAzureWeb">
    <InputEndpoints>
      <InputEndpoint name="HttpIn" protocol="http" port="80" />
    </InputEndpoints>
    <ConfigurationSettings>
      <Setting name="DiagnosticsConnectionString" />
      <Setting name="myText"/>
    </ConfigurationSettings>
  </WebRole>
</ServiceDefinition>

Next we need to add the Setting element with a name and value into ConfigurationSettings section of our Service Configuration file.

<Setting name="myText" value="Hello Azure from the Configuration!" />

Here’s the copy of the complete ServiceConfiguration.cscfg file:

<?xml version="1.0"?>
<ServiceConfiguration serviceName="LearnAzure" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration">
  <Role name="LearnAzureWeb">
    <Instances count="1" />
    <ConfigurationSettings>
      <Setting name="DiagnosticsConnectionString" value="UseDevelopmentStorage=true" />
      <Setting name="myText" value="Hello Azure from the Configuration!" />
    </ConfigurationSettings>
  </Role>
</ServiceConfiguration>

You don’t have to manually modify custom settings.  Visual Studio provides us with GUI to add, remove, or modify our settings.  Select property on our Role and on the left chose the Settings tab.

image

We are done with configuration.  Now let use “myText” in our source code. In our Default.aspx file we need to replace

    <div>
    Hello Azure!
    </div

with

<div>
<asp:Label ID="mainTextLbl" runat="server" />
</div>

We just added a new Label control.

The only thing left is to read the value from the configuration file and assign it to our mainTextLbl Label control.  We’ll do it on page Load event in Default.aspx.cs file.

protected void Page_Load(object sender, EventArgs e)
{
    mainTextLbl.Text = RoleEnvironment.GetConfigurationSettingValue("myText");
}

Now we can compile and run our application on local computer.

image

Now you know how to set basic custom settings for an Azure application.

Certificates.

I believe that discussion of certificates deserves its own article.  I’ll try to talk about it in the future posts.

Why another XML configuration file?

You are probably wondering why do we need another XML configuration file (in this case ServiceConfiguration.cscfg).  We can perfectly set the setting in my Web.config or app.config files.   That’s true but then you’ll have to repackage and redeploy the whole application again.

You can modify ServiceConfiguration.cscfg file from your Azure portal and no redeployment will be required.

To change configuration just login to your Windows Azure portal, select the service and click on Configure button.

image

From Service Tuning page you can modify the existing Service Configuration file or upload a new one.

image

Summary

Now we have basic knowledge how to configure our Azure application.  We learn about Instances and custom settings.  In future article we’ll learn about certificates.

kick it on DotNetKicks.com

Posted in Azure | Tagged: | Leave a Comment »

Part 1: Hello Azure – Learn Azure with me.

Posted by Vadim on January 19, 2010

Windows_Azure_logo[1] I want to learn Windows Azure.  I already have done some reading on the subject and created some simple Windows Azure applications.  However, I believe that writing articles about Cloud Services will help me to get stronger understanding of the platform.

I will not tell you what Windows Azure is.  I hope that you’re reading this because you know what it is and ready to learn it.  I also hope that you already downloaded and installed Windows Azure Platform on your computer.  If you haven’t done it, you can download it from Microsoft Windows Azure site.

My goal for this article:

  1. Create LearnAzure Cloud Service that displays “Hello Azure!” message.
  2. Set up your service online.
  3. Deploy the application to Azure Fabric.

Create LearnAzure Cloud Service.

Start Visual Studio.  I’m going to use VS 2010 Beta 2 but it should work just fine with VS 2008.

Press Ctrl+Shift+N to create a new project.  You also can select File –> New –> Project… from Visual Studio menu.  You should see New Project dialog.

From Installed Templates select Cloud Service (if you don’t see Cloud Service template, than you need to install Windows Azure SDK).   For the project name I typed “LearnAzure”.image

Click on the OK button and you will see a New Cloud Service Project dialog box.  In this dialog box, from the Roles, select ASP.NET Web Role because we want to create an ASP.NET Windows Azure application.  Click on the right arrow to make ASP.NET Web Role appear in Cloud Service Solution list.  By default Visual Studio will give “WebRole1” to your ASP.NET Web Role.  This name is too generic; let’s rename it to “LearnAzureWeb”.  To rename, move your mouse over WebRole1 and click on the little pencil icon on the right of the role.  Now you can rename it to LearnAzureWeb.image 

image After Visual Studio is done, you should have LearnAzure solution that has two projects: LearnAzure and LearnAzureWeb. LearnAzureWeb looks almost like any other ASP.NET application but there few differences.

If you expend References in our ASP.NET Web projects, you’ll see three additional references to Windows Azure assemblies:

  • Microsoft.WindowsAzure.Diagnostics
  • Microsoft.WindowsAzure.ServiceRuntime
  • Microsoft.WindowsAzure.StorageClient

Use Diagnostics namespace for your logging needs.
Use ServiceRuntime namespace when you need to interact with Windows Azure fabric.
Use StorageClient namespace when you need to work with storage services.

These assemblies are located in Program Files\Windows Azure SDK\v1.0\ref folder.

I know that right now this is not enough information for you to understand exactly what these names are for, and how to use them.  But remember, this is just a “Hello Azure!” article.  We’ll have plenty of time to discuss more advance subjects in the future posts.

You also can see WebRole.cs file in your LearnAzureWeb project.  WebRole class provides callbacks to initialize, run, and stop instances of our ASP.NET role.

We have a working Azure application without writing a single line of code.  However, if we start the application by pressing Ctrl+F5 or F5 in case you wanto to start it with debugger, you will see an empty web page.

image In your system tray you can find a new blue window flag icon.  It tells you that Windows Azure simulation environment is running.  It also means that  the Development Fabric and the Development Storage services were started.  You can right click on this icon to see User Interfaces either for the Development Fabric or Development Storage services.  You also can

shutdown any of these services using this icon.

We are done but I hate to look at an empty web page; therefore, I’m going to add “Hello Azure!” to the body of Default.aspx page.

<body>
    <form id="form1" runat="server">
    <div>
    Hello Azure!
    </div>
    </form>
</body>

Here’s the output of our brand new Windows Azure application:

image

Setup your service online.

Now we know how to run our Hello Azure Cloud Service on Simulation Environment.  Next we need to setup the service online.  I assume that you already went to Microsoft Windows Azure site and have an Azure account setup.

In order to deploy our Hello Azure app. you need to log into your Azure portal with the Live ID you registered with.  Below you can see my  Windows Azure page.  I have only one project: PDC08 CTP.

image Next click on the project name. In my case I’m going to click on “PDC08 CTP” as it’s my project name.  You should see the project page.  On this page you can create a new hosted services and storage account.  On my page you can see that a storage account “diagnosticsdata” that I created earlier.

image

I don’t have any hosted services yet. You and I are going to create “Learn Azure” hosted service.  To create a new service, just click on New Service link; you have two these links on this page.  One just above the left navigation bar and another on the right of the project name.  You should see Create an new service page, similar to the image below.

image On this page, we can create either a Storage Account or Hosted Service.  We already decided that we want to create “Learn Azure” hosted service.  Let’s click on Hosted Services link.  You should see Create a Service page.  Provide a service label and description for the service and then click the Next button.

image You should go to the second part of Create a Service.  On this page you need to enter a Public Service Name and choose an Affinity Group.  The Public Service Name must be unique.  I wanted to enter “LearnAzure” but it’s not available; therefore, I chose “LearnAzureWithMe”.  The Public Service Name you’ll choose will be the first part of the URL for your service.  Because it’s part of a URL, it must be unique and cannot have white spaces.  Unfortunately, you have to come up with a different name because “LearnAzureWithMe” belongs to me now.  You can click on the “Check Availability” button to see if the name you selected is still available.

The second part of the form is related to Hosted Service Affinity Group.  Microsoft has many different datacenters around the world.  You want to select a region that the best represents your audience / customers to get better performance.  Also if you have services that are related you might want to deploy them to different datacenters for disaster recovery or geo-distribution purposes.

image Press the Create button to create your hosted service.

Deploy the application to Azure Fabric.

Finally we have a cloud space where to deploy our “Hello Azure!” application.  But before we do so, we need to create the Service Package (.cspkg).  We could use CSPack.exe utility that you can find in Azure SDK folder but it’s much easier to create the Service Package from Visual Studio by right clicking on LearnAzure Cloud Service project and select “Publish”.

image

Visual Studio executes CSPack.exe to create the Service Package. After all is done, you should see the folder containing the Service Package (LearnAzure.cspkg) and Service Configuration file (ServiceConfiguration.cscfg).  .cspkg is a glorified zip file, you should be able to open it with any zip utility if you want to see what inside the package.

image The next step is to deploy the Service Package and Service Configuration file.  You can deploy directly to production, but I would recommend that you deploy to staging environment first.  In order to deploy the application you need to go back to your Azure Portal.  If you don’t see a staging ice cube next to the production one, click on the little arrow that is right of production cube.

image Click on Deploy button under the staging ice cube.  On the next screen, browse for your Service Package and Service Configuration file.  You also will need to give a label for this deployment, my label is “v. 0.1”.

image Click on Deploy button in order to deploy “Hello Azure!” application to Staging environment.  The deployment process can take couple of minutes.  After all is done the gray cube should magically transform to nice ice blue cube.  Your Azure application is deploy but to test it, you need to click on Run button under Staging cube.  You will see that the status flipped to “Initializing”.  It might take few minutes for the status to change to “Ready”.  You can test your application by navigating to your staging Web Site URL.

Next logical step after you tested our application on staging is to promote it to production.  It’s very easy done by clicking on a circle with two arrows inside.  If you need more clues to find the circle, it’s between Production and Staging cubes.  You don’t actually move the application to different place.  After you click on the circle, Windows Azure just flips production and staging environments.  The old staging environment becomes our new production one and vice versa.

image It takes only few moments to promote from staging to production because Windows Azure makes only small configuration change.

Now I can point my browser to http://learnazurewithme.cloudapp.net/ to use my perfectly useless application.

image

Summary

In this article, we learned how to create a simple Azure application.  We also talked about new files and references that need to be added in order to run our app. in the cloud.  Now you can tell all of your friends how to setup and deploy the Windows Azure application.

Next, we’re going to learn how to use Azure Service Configuration.

kick it on DotNetKicks.com

Posted in Azure, Tutorial | Tagged: | 4 Comments »

 
Follow

Get every new post delivered to your Inbox.