<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Vidar's Musings &#187; vidarkongsli</title>
	<atom:link href="http://www.kongsli.net/nblog/author/vidarkongsli/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.kongsli.net/nblog</link>
	<description>Deep thoughts on shallow topics</description>
	<lastBuildDate>Fri, 27 Jan 2012 07:36:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>ASCII vs ISO-8859-1</title>
		<link>http://www.kongsli.net/nblog/2012/01/27/ascii-vs-iso-8859-1/</link>
		<comments>http://www.kongsli.net/nblog/2012/01/27/ascii-vs-iso-8859-1/#comments</comments>
		<pubDate>Fri, 27 Jan 2012 07:36:55 +0000</pubDate>
		<dc:creator>vidarkongsli</dc:creator>
				<category><![CDATA[Microsoft technologies]]></category>
		<category><![CDATA[Software development]]></category>

		<guid isPermaLink="false">http://www.kongsli.net/nblog/?p=389</guid>
		<description><![CDATA[Note to self: var ascii7BitEncoding = Encoding.ASCII; // ASCII var ascii8BitEncodingIsh = Encoding.GetEncoding("iso-8859-1"); // Extended ASCII for almost all practical purposes Where Extended ASCII differs from ISO-8859-*, according to Wikipedia: One notable way in which ISO character sets differ from code pages is that the character positions 128 to 159, corresponding to ASCII control characters [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Note to self:</strong></p>

<p><pre class="csharp" name="code">
var ascii7BitEncoding = Encoding.ASCII; // ASCII
var ascii8BitEncodingIsh = Encoding.GetEncoding("iso-8859-1"); // Extended ASCII for almost all practical purposes
</pre></p>

<p>Where Extended ASCII differs from ISO-8859-*, according to <a title="Wikipedia:Extended ASCII" href="http://en.wikipedia.org/wiki/Extended_ASCII">Wikipedia</a>:</p>

<p><em>One notable way in which ISO character sets differ from code pages is that the character positions 128 to 159, corresponding to ASCII control characters with the high-order bit set, are specifically unused and undefined in the ISO standards, though they had often been used for printable characters in proprietary code pages, a breaking of ISO standards that was almost universal.</em></p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.kongsli.net%2Fnblog%2F2012%2F01%2F27%2Fascii-vs-iso-8859-1%2F&amp;title=ASCII%20vs%20ISO-8859-1" id="wpa2a_2"><img src="http://www.kongsli.net/nblog/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.kongsli.net/nblog/2012/01/27/ascii-vs-iso-8859-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Enabling Web Transforms when debugging ASP.NET apps</title>
		<link>http://www.kongsli.net/nblog/2012/01/13/enabling-web-transforms-when-debugging-asp-net-apps/</link>
		<comments>http://www.kongsli.net/nblog/2012/01/13/enabling-web-transforms-when-debugging-asp-net-apps/#comments</comments>
		<pubDate>Fri, 13 Jan 2012 13:47:23 +0000</pubDate>
		<dc:creator>vidarkongsli</dc:creator>
				<category><![CDATA[Microsoft technologies]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[aspdotnet]]></category>
		<category><![CDATA[msbuild]]></category>
		<category><![CDATA[visual studio]]></category>
		<category><![CDATA[web transforms]]></category>

		<guid isPermaLink="false">http://www.kongsli.net/nblog/?p=344</guid>
		<description><![CDATA[Web Transformations is a great feature. When a web application is packaged or published, the Web.config file is transformed dependent on which Visual Studio / MSBuild configuration you are running, enabling environment-specific settings to change accordingly. However, to my mind there is a shortcoming. Since the transformation happens during packaging or publishing of the application, [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/dd465326.aspx">Web Transformations</a> is a great feature. When a web application is packaged or published, the <code>Web.config</code> file is transformed dependent on which Visual Studio / MSBuild configuration you are running, enabling environment-specific settings to change accordingly.</p>

<p>However, to my mind there is a shortcoming. Since the transformation happens during packaging or publishing of the application, transformation rules do not take effect when debugging a web application (typically by hitting <strong>F5</strong> in Visual Studio) because the application is served from the project directory. Here&#8217;s how to solve this: essentially, we can change the the project setup so that the transformation happens right after the project build step. Here&#8217;s how:</p>

<h3>Step 1: Unload the project in Visual Studio</h3>

<p>In the Solution Explorer in Visual Studio, right-click on the project and select <strong>Unload project</strong> from the context menu:</p>

<p><a href="http://www.kongsli.net/nblog/wp-content/uploads/2011/12/unload_project.png"><img class="alignnone size-full wp-image-343" title="unload_project" src="http://www.kongsli.net/nblog/wp-content/uploads/2011/12/unload_project.png" alt="" width="469" height="724" /></a></p>

<h3>Step 2: Rename Web.config on the file system</h3>

<p>In the Windows Explorer, browse to the project directory, and rename <code>Web.config</code> to <code>Web.template.config</code>:</p>

<p><a href="http://www.kongsli.net/nblog/wp-content/uploads/2011/12/rename-web-config.png"><img src="http://www.kongsli.net/nblog/wp-content/uploads/2011/12/rename-web-config.png" alt="" title="rename-web-config" width="604" height="171" class="alignnone size-full wp-image-340" /></a></p>

<h3>Step 3: Rename Web.config in the project file</h3>

<p>What we will do here, is to rename the existing <code>Web.config</code> to <code>Web.template.config</code> in the project file (.csproj or .vbproj). This will be the file that we keep in the version control system, and the final <code>Web.config</code> will instead be generated for us when building the application.</p>

<p>In the Solutuion Explorer in Visual Studio, right-click on the project and select <strong>Edit &lt;project name&gt;</strong>:</p>

<p><a href="http://www.kongsli.net/nblog/wp-content/uploads/2011/12/edit-project.png"><img src="http://www.kongsli.net/nblog/wp-content/uploads/2011/12/edit-project.png" alt="" title="edit project" width="513" height="206" class="alignnone size-full wp-image-339" /></a></p>

<p>Search for &#8220;web.config&#8221; in the project file to locate where the <code>Web.config</code> and transformation files definitions. It looks something like so:</p>

<p><pre class="xml" name="code">
&lt;Content Include="Web.config" /&gt;
&lt;Content Include="Web.Debug.config"&gt;
   &lt;DependentUpon>Web.config&lt;/DependentUpon&gt;
&lt;/Content&gt;
&lt;Content Include="Web.Release.config"&gt;
   &lt;DependentUpon>Web.config&lt;/DependentUpon&gt;
&lt;/Content&gt;
</pre></p>

<p>In the project file, for instance on the line after the one with <code>Web.config</code>, add the following:</p>

<p><pre class="xml" name="code">
&lt;None Include="Web.template.config" /&gt;
</pre></p>

<p>Then, change the text of the <code>DependentUpon</code> element to read <code>Web.template.config</code> instead of <code>Web.config</code>. Finally, change the <code>Content</code> elements for for <code>Web.Debug.config</code> and <code>Web.Release.config</code> to <code>None</code> elements. This prevents these files from being included in the deployment package. They don&#8217;t need to be, as the transformations have already been run. All in all, the snippet from above should now read:</p>

<p><pre class="xml" name="code">
&lt;Content Include="Web.config" /&gt;
&lt;None Include="Web.template.config" /&gt;
&lt;None Include="Web.Debug.config"&gt;
   &lt;DependentUpon>Web.template.config&lt;/DependentUpon&gt;
&lt;/None&gt;
&lt;None Include="Web.Release.config"&gt;
   &lt;DependentUpon>Web.template.config&lt;/DependentUpon&gt;
&lt;/None&gt;
</pre></p>

<h3>Step 4: Running transformation when building</h3>

<p>Now that we have a reference to <code>Web.template.config</code> in the project file, the next step is to run the transformation during the build step. Add a custom target that runs the transformation and then include it at the begining of the build task using the {{BuildDependsOn}} property. The resulting XML snippet looks like so:</p>

<p><pre class="xml" name="code">
&lt;PropertyGroup&gt;
  &lt;BuildDependsOn&gt;
    CustomWebConfigTransform;
    $(BuildDependsOn);
  &lt;/BuildDependsOn&gt;
&lt;/PropertyGroup&gt;
&lt;Target Name="CustomWebConfigTransform"&gt;
   &lt;TransformXml&gt; source="Web.template.config"
      transform="Web.$(Configuration).config"
      destination="Web.config" /&gt;
&lt;/Target&gt;
</pre></p>

<p>Save the file and reload the project into the Visual Studio solution. Then, in the Solution Explorer, observe that the <code>Web.config</code> file now is denoted as missing, and that the <code>Web.template.config</code> is present with the two transformation files beneath it in the file tree:</p>

<p><a href="http://www.kongsli.net/nblog/wp-content/uploads/2011/12/solution-explorer-changed.png"><img src="http://www.kongsli.net/nblog/wp-content/uploads/2011/12/solution-explorer-changed.png" alt="" title="solution-explorer-changed" width="264" height="345" class="alignnone size-full wp-image-342" /></a></p>

<h3>Step 5: Test running transformations during build</h3>

<p>In this step, we will test that the transformations will be run when launching the application by hitting <code>F5</code> in Visual Studio. First, we need to create a configuration example in <code>Web.Debug.config</code>. Remove all the gunk that Microsoft so helpfully has filled the file with during project creation, and insert one simple <code>appSettings</code> entry, making the <code>Web.Debug.config</code> look like this:</p>

<p><pre class="xml" name="code">
&lt;configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"&gt;
  &lt;appSettings&gt;
    &lt;add key="Configuration" value="Debug" xdt:Transform="Insert"/&gt;
  &lt;/appSettings&gt;
&lt;/configuration&gt;
</pre></p>

<p>Take care to include the <code>xdt</code> XML namespace definition. Without it, the transformations will not be run.</p>

<p>Open up an <code>ASPX</code> page, for instance <code>Default.aspx</code>, and enter a label that will display the value of our confiugration setting:</p>

<p><pre class="xml" name="code">
&lt;p&gt;
   Configuration: &lt;asp:Label ID="Configuration" runat="server" /&gt;
&lt;/p&gt;</pre></p>

<p>Next, enter this in the code behind:</p>

<p><pre class="c-sharp" name="code">
protected void Page_Load(object sender, EventArgs e)
{
   Configuration.Text = ConfigurationManager.AppSettings["Configuration"];
}
</pre></p>

<p>Hit <strong>F5</strong> to run the application and verify that it in fact is able to read from the transformed <code>Web.config</code>:</p>

<p><a href="http://www.kongsli.net/nblog/wp-content/uploads/2011/12/result.png"><img src="http://www.kongsli.net/nblog/wp-content/uploads/2011/12/result.png" alt="" title="result" width="546" height="216" class="alignnone size-full wp-image-341" /></a></p>

<h3>Step 6: Disable transformations during packaging and publishing</h3>

<p>Since <code>msbuild</code> by default runs the transformations, we need to disable this to prevent the transformations to be applied twice. To do this, unload the project from the solution as we did in step 1, and then edit the project file in Visual Studio. For each of the configurations that you have in your solution, disable the built-in transformation runs by adding the <code>TransformWebConfigEnabled</code> element and setting it to false. Like so:</p>

<p><pre class="c-sharp" name="code">
&lt;PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "&gt;
   &lt;TransformWebConfigEnabled&gt;False&lt;/TransformWebConfigEnabled&gt;
   ...
&lt;/PropertyGroup&gt;
</pre></p>

<h3>Summary / other tweaks</h3>

<p>What we have achieved, is that the transformations are applied when building the application, making the transformed file available when running the application locally from Visual Studio. Another tip with regards to Web Transformations is to use the <a href="http://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5">SlowCheetah</a> Visual Studio Add-in that Scott Hanselman has <a href="http://www.hanselman.com/blog/SlowCheetahWebconfigTransformationSyntaxNowGeneralizedForAnyXMLConfigurationFile.aspx">described very well here</a>. It will give you a nice transformation preview on the context menu in Visual Studio which is extremely helpful.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.kongsli.net%2Fnblog%2F2012%2F01%2F13%2Fenabling-web-transforms-when-debugging-asp-net-apps%2F&amp;title=Enabling%20Web%20Transforms%20when%20debugging%20ASP.NET%20apps" id="wpa2a_4"><img src="http://www.kongsli.net/nblog/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.kongsli.net/nblog/2012/01/13/enabling-web-transforms-when-debugging-asp-net-apps/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NLog: writing log entries to Azure Table Storage</title>
		<link>http://www.kongsli.net/nblog/2012/01/05/nlog-writing-log-entries-to-azure-table-storage/</link>
		<comments>http://www.kongsli.net/nblog/2012/01/05/nlog-writing-log-entries-to-azure-table-storage/#comments</comments>
		<pubDate>Thu, 05 Jan 2012 13:49:20 +0000</pubDate>
		<dc:creator>vidarkongsli</dc:creator>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Microsoft technologies]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[cloud]]></category>
		<category><![CDATA[nlog]]></category>
		<category><![CDATA[tablestorage]]></category>

		<guid isPermaLink="false">http://www.kongsli.net/nblog/?p=372</guid>
		<description><![CDATA[In August last year, I blogged about how to get Log4Net log entries written to Azure Table Storage. In this article, I will show how the same thing can be easily achieved using NLog. The concepts in NLog is very similar to Log4Net. More or less, replace the word &#8220;appender&#8221; in Log4Net lingo with &#8220;target&#8221;, [...]]]></description>
			<content:encoded><![CDATA[<p>In August last year, I blogged about how to get <a href="http://www.kongsli.net/nblog/2011/08/15/log4net-writing-log-entries-to-azure-table-storage/">Log4Net log entries written to Azure Table Storage</a>. In this article, I will show how the same thing can be easily achieved using <a href="http://nlog-project.org/">NLog</a>.</p>

<p>The concepts in NLog is very similar to Log4Net. More or less, replace the word &#8220;appender&#8221; in Log4Net lingo with &#8220;target&#8221;, and you&#8217;re game.</p>

<p>First, let&#8217;s create a class for log entries:</p>

<p><pre class="c-sharp" name="code">
public class LogEntry : TableServiceEntity
{
    public LogEntry()
    {
        var now = DateTime.UtcNow;
        PartitionKey = string.Format("{0:yyyy-MM}", now);
        RowKey = string.Format("{0:dd HH:mm:ss.fff}-{1}", now, Guid.NewGuid());
    }
    #region Table columns
    public string Message { get; set; }
    public string Level { get; set; }
    public string LoggerName { get; set; }
    public string RoleInstance { get; set; }
    public string DeploymentId { get; set; }
    public string StackTrace { get; set; }
    #endregion
}
</pre></p>

<p>Next, we need to do is to create a class that represents the table storage service. It needs to inherit from <code>TableServiceContext</code>:</p>

<p><pre class="c-sharp" name="code">
public class LogServiceContext : TableServiceContext
{
    public LogServiceContext(string baseAddress, StorageCredentials credentials) : base(baseAddress, credentials) { }
    internal void Log(LogEntry logEntry)
    {
        AddObject("LogEntries", logEntry);
        SaveChanges();
    }
    public IQueryable&lt;LogEntry&gt; LogEntries
    {
        get
        {
            return CreateQuery&lt;LogEntry&gt;("LogEntries");
        }
    }
}
</pre></p>

<p>Finally, as far as code is concerned, a class that is a custom NLog target that gets called when the NLog framework needs to log something:</p>

<p><pre class="c-sharp" name="code">
[Target("AzureStorage")]
public class AzureStorageTarget : Target
{
    private LogServiceContext _ctx;
    private string _tableEndpoint;
    [Required]
    public string TableStorageConnectionStringName { get; set; }
    protected override void InitializeTarget()
    {
        base.InitializeTarget();
        var cloudStorageAccount =
            CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue(TableStorageConnectionStringName));
        _tableEndpoint = cloudStorageAccount.TableEndpoint.AbsoluteUri;
        CloudTableClient.CreateTablesFromModel(typeof(LogServiceContext), _tableEndpoint, cloudStorageAccount.Credentials);
        _ctx = new LogServiceContext(cloudStorageAccount.TableEndpoint.AbsoluteUri, cloudStorageAccount.Credentials);
    }
    protected override void Write(LogEventInfo loggingEvent)
    {
        Action doWriteToLog = () =>
        {
            try
            {
                _ctx.Log(new LogEntry
                {
                    RoleInstance = RoleEnvironment.CurrentRoleInstance.Id,
                    DeploymentId = RoleEnvironment.DeploymentId,
                    Timestamp = loggingEvent.TimeStamp,
                    Message = loggingEvent.FormattedMessage,
                    Level = loggingEvent.Level.Name,
                    LoggerName = loggingEvent.LoggerName,
                    StackTrace = loggingEvent.StackTrace != null ? loggingEvent.StackTrace.ToString() : null
                });
            }
            catch (DataServiceRequestException e)
            {
                InternalLogger.Error(string.Format("{0}: Could not write log entry to {1}: {2}",
                    GetType().AssemblyQualifiedName, _tableEndpoint, e.Message), e);
            }
        };
        doWriteToLog.BeginInvoke(null, null);
    }
}
</pre></p>

<p>So, to make it work, we need to register the target with the NLog framework. This is done in the <code>NLog.config</code> file:</p>

<p><pre class="c-sharp" name="code">
&lt;?xml version="1.0"?&gt;
&lt;nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;
  &lt;extensions&gt;
    &lt;add assembly="Demo.NLog.Azure" /&gt;
  &lt;/extensions&gt;
  &lt;targets&gt;
    &lt;target name="azure" type="AzureStorage" tableStorageConnectionStringName="Log4Net.ConenctionString" /&gt;
  &lt;/targets&gt;
  &lt;rules&gt;
    &lt;logger name="*" minlevel="Info" writeTo="azure" /&gt;
  &lt;/rules&gt;
&lt;/nlog&gt;
</pre></p>

<p>
For information about how to set your <code>ServiceDefinition.csdef</code> and <code>ServiceConfiguration.cscfg</code> files, see my <a href="http://www.kongsli.net/nblog/2011/08/15/log4net-writing-log-entries-to-azure-table-storage/">previous post</a>.You can find the code for this example on <a href="https://github.com/vidarkongsli/azuretablestoragetarget">GitHub</a>. Suggestions for improvement are very welcome.
</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.kongsli.net%2Fnblog%2F2012%2F01%2F05%2Fnlog-writing-log-entries-to-azure-table-storage%2F&amp;title=NLog%3A%20writing%20log%20entries%20to%20Azure%20Table%20Storage" id="wpa2a_6"><img src="http://www.kongsli.net/nblog/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.kongsli.net/nblog/2012/01/05/nlog-writing-log-entries-to-azure-table-storage/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting user information programmatically from Windows Identity Foundation</title>
		<link>http://www.kongsli.net/nblog/2011/08/29/getting-user-information-programmatically-from-windows-identity-foundation/</link>
		<comments>http://www.kongsli.net/nblog/2011/08/29/getting-user-information-programmatically-from-windows-identity-foundation/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 12:54:27 +0000</pubDate>
		<dc:creator>vidarkongsli</dc:creator>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Microsoft technologies]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[acs]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[aspdotnet]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[wif]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.kongsli.net/nblog/?p=302</guid>
		<description><![CDATA[You can use the Windows Identity Foundation SDK to replace the authentication scheme of your ASP.NET web application. Most notably, this is useful for making your application claims-aware, which allows it to seamlessly play together with solutions like Active Directory Federation Services or the Windows Azure AppFabric Access Service. This is useful for a various [...]]]></description>
			<content:encoded><![CDATA[<p>You can use the Windows Identity Foundation SDK to replace the authentication scheme of your ASP.NET web application. Most notably, this is useful for making your application claims-aware, which allows it to seamlessly play together with solutions like Active Directory Federation Services or the Windows Azure AppFabric Access Service. This is useful for a various number of SSO and federated authentication scenarios.</p>

<p>Basically, what you do is that you switch off the built-in authentication in ASP.NET like forms-based authentication, and let WIF act as a proxy in front of your application. WIF uses the authorization settings in <code>web.config</code> (/configuration/system.web/authorization and /configuration/location/system.web/authorization elements) and authenticates the user before the ASP.NET application receives the request. See <a href="http://msdn.microsoft.com/en-us/library/ee517293.aspx" title="MSDN: WS-Federated Authentication Module Overview">WS-Federated Authentication Module Overview</a> for details</p>

<p>So, when the application receives the request, the user is already authenticated, which is fine. However, there are times when the application needs to know who the user is, or getting access to the other claims that were provided from the identity service. Luckily, this is available on the HTTP context. Say, for instance, if you wish to find the email address of the logged-in user, you can do it like so:</p>

<p><pre class="c-sharp" name="code">
protected void Page_Load(object sender, EventArgs e)
{
    var claimsIdentity = Context.User.Identity as IClaimsIdentity;
    foreach (var claim in claimsIdentity.Claims)
    {
        if (claim.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress")
        {
            var email = claim.Value;
        }
    }
}
</pre></p>

<p>If the user was authenticated using claims, <code>Context.User.Identity</code> will be an <code>IClaimsIdentity</code> which will contain a number of claims about the user. We can then iterate over these claims to find the one that we want.</p>

<p>The claim types are denoted using XML namespaces, which are a little bit cumbersome to work with. So, to make it easier to access, we iterate over the list of claims, and make all the claims available on a common object:</p>

<p><pre class="c-sharp" name="code">
public static class IdentityExtension
{
    public static DynamicUser GetUserFromClaims(this HttpContext context)
    {
        var claimsIdentity = context.User.Identity as IClaimsIdentity;
        if (claimsIdentity == null) throw new FailedAuthenticationFaultException();
        return new DynamicUser(claimsIdentity.Claims);
    }
}
public class DynamicUser : DynamicObject
{
    private readonly ClaimCollection _claims;
    public DynamicUser(ClaimCollection claims)
    {
        _claims = claims;
        Id = ClaimsValue("nameidentifier")[0];
    }
    public string Id { get; private set; }
    public bool IsInRole(string role)
    {
        return ClaimsValue("role").Any(c =&gt; c.Equals(role, StringComparison.OrdinalIgnoreCase));
    }
    private string[] ClaimsValue(string claimSuffix)
    {
        return _claims.Where(c =&gt; c.ClaimType.EndsWith(claimSuffix)).Select(c =&gt; c.Value).ToArray();
    }
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        var claimValue = ClaimsValue(binder.Name.ToLowerInvariant());
        if (claimValue.Length == 0)
        {
            return base.TryGetMember(binder, out result);
        }
        if (claimValue.Length == 1)
        {
            result = claimValue[0];
        }
        else
        {
            result = claimValue;
        }
        return true;
    }
}
</pre></p>

<p>Then, we can access the claim values using a prefix of the actual XML namespace of the claim type:</p>

<p><pre class="c-sharp" name="code">
protected void Page_Load(object sender, EventArgs e)
{
    var user = Context.GetUserFromClaims();
    var id = user.Id;
    var username = user.Name; // "John Doe"
}
</pre></p>

<p>When hooking up the application to Windows Azure AppFabric Access Control Service (ACS), which claims that the application will receive depends on your <a href="http://msdn.microsoft.com/en-us/library/gg185923.aspx">rule group configuration</a>. Here are some examples:</p>

<table border="1">
<tr><th>Claim type</th><th>Shorthand</th><th>Example value</th></tr>
<tr>
<td>http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier</td>
<td><code>user.Id</code></td>
<td>NHsTR1UXFI9xYk1xIRUNfucZ4/a5OWiILHlNyNEXozP=</td>
</tr>
<tr>
<td>http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name</td>
<td><code>user.Name</code></td>
<td>John Doe</td>
</tr>
<tr>
<td>http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress</td>
<td><code>user.Emailaddress</code></td>
<td>john.doe@hotmail.com</td>
</tr>
</table>

<p>If you set up <a href="http://msdn.microsoft.com/en-us/library/gg185923.aspx">role claim rules</a> in ACS, you can even get information about the user&#8217;s roles so that you can do authorization in the code:</p>

<p><pre class="c-sharp" name="code">
protected void Page_Load(object sender, EventArgs e)
{
    var user = Context.GetUserFromClaims();
    var isAdmin = user.IsInRole("administrator"):
}
</pre></p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.kongsli.net%2Fnblog%2F2011%2F08%2F29%2Fgetting-user-information-programmatically-from-windows-identity-foundation%2F&amp;title=Getting%20user%20information%20programmatically%20from%20Windows%20Identity%20Foundation" id="wpa2a_8"><img src="http://www.kongsli.net/nblog/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.kongsli.net/nblog/2011/08/29/getting-user-information-programmatically-from-windows-identity-foundation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Log4Net: writing log entries to Azure Table Storage</title>
		<link>http://www.kongsli.net/nblog/2011/08/15/log4net-writing-log-entries-to-azure-table-storage/</link>
		<comments>http://www.kongsli.net/nblog/2011/08/15/log4net-writing-log-entries-to-azure-table-storage/#comments</comments>
		<pubDate>Mon, 15 Aug 2011 12:09:38 +0000</pubDate>
		<dc:creator>vidarkongsli</dc:creator>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Microsoft technologies]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[cloud]]></category>
		<category><![CDATA[log4net]]></category>
		<category><![CDATA[tablestorage]]></category>

		<guid isPermaLink="false">http://www.kongsli.net/nblog/?p=318</guid>
		<description><![CDATA[Earlier, I blogged about how one can leverage Azure Diagnostics to easily set up Log4Net for your application running in Azure, and how to customize the log entries for the Azure environment. An alternative to doing this two-step process of first writing to the local disk and then transfer the logs to Azure blob storage, [...]]]></description>
			<content:encoded><![CDATA[<p>Earlier, I blogged about how one can <a href="http://www.kongsli.net/nblog/2011/08/03/using-log4net-in-azure-compute/">leverage Azure Diagnostics</a> to easily set up <a href="http://logging.apache.org/log4net/">Log4Net</a> for your application running in Azure, and <a href="http://www.kongsli.net/nblog/2011/08/08/customizing-log4net-log-entries-on-azure/">how to customize the log entries for the Azure environment</a>.</p>

<p>An alternative to doing this two-step process of first writing to the local disk and then transfer the logs to Azure blob storage, is to write the log entries directly to Azure table storage (or in principal, to Azure blob storage for that matter). This is what I will do here.</p>

<p>Each log entry that the application writes will be a single row in a table in the Azure Table Storage. The log message itself and various meta data about it will be inserted into separate columns in the table. In order to achieve this, we first create a class that represents each entry in the table:</p>

<p><pre class="c-sharp" name="code">
public class LogEntry : TableServiceEntity
{
    public LogEntry()
    {
        var now = DateTime.UtcNow;
        PartitionKey = string.Format("{0:yyyy-MM}", now);
        RowKey = string.Format("{0:dd HH:mm:ss.fff}-{1}", now, Guid.NewGuid());
    }
    #region Table columns
    public string Message { get; set; }
    public string Level { get; set; }
    public string LoggerName { get; set; }
    public string Domain { get; set; }
    public string ThreadName { get; set; }
    public string Identity { get; set; }
    public string RoleInstance { get; set; }
    public string DeploymentId { get; set; }
    #endregion
}
</pre></p>

<p>Note that the <code>PartitionKey</code> is the current year and month, and the <code>RowKey</code> is a combination of the date, time and a GUID. This is done to make the querying of the log entries efficient for our purpose. So, the next thing we need to do is to create a class that represents the table storage service. It needs to inherit from <code>TableServiceContext</code>:</p>

<p><pre class="c-sharp" name="code">
internal class LogServiceContext : TableServiceContext
{
    public LogServiceContext(string baseAddress, StorageCredentials credentials) : base(baseAddress, credentials) {}
    internal void Log(LogEntry logEntry)
    {
        AddObject("LogEntries", logEntry);
        SaveChanges();
    }
    public IQueryable&lt;LogEntry&gt; LogEntries
    {
        get
        {
            return CreateQuery&lt;LogEntry&gt;("LogEntries");
        }
    }
}
</pre></p>

<p>The method that we will actually use in our code is the <code>Log</code> method which takes a <code>LogEntry</code> instance and persists it to table storage. What we need next, is to create a new Appender for Log4Net which interacts with the table store to store the log entries:</p>

<p><pre class="c-sharp" name="code">
public class AzureTableStorageAppender : AppenderSkeleton
{
    public string TableStorageConnectionStringName { get; set; }
    private LogServiceContext _ctx;
    private string _tableEndpoint;
    public override void ActivateOptions()
    {
        base.ActivateOptions();
        var cloudStorageAccount =
            CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue(TableStorageConnectionStringName));
        _tableEndpoint = cloudStorageAccount.TableEndpoint.AbsoluteUri;
        CloudTableClient.CreateTablesFromModel(typeof(LogServiceContext), _tableEndpoint, cloudStorageAccount.Credentials);
        _ctx = new LogServiceContext(cloudStorageAccount.TableEndpoint.AbsoluteUri, cloudStorageAccount.Credentials);
    }
    protected override void Append(LoggingEvent loggingEvent)
    {
        Action doWriteToLog = () =&gt; {
            try
            {
                _ctx.Log(new LogEntry
                {
                    RoleInstance = RoleEnvironment.CurrentRoleInstance.Id,
                    DeploymentId = RoleEnvironment.DeploymentId,
                    Timestamp = loggingEvent.TimeStamp,
                    Message = loggingEvent.RenderedMessage,
                    Level = loggingEvent.Level.Name,
                    LoggerName = loggingEvent.LoggerName,
                    Domain = loggingEvent.Domain,
                    ThreadName = loggingEvent.ThreadName,
                    Identity = loggingEvent.Identity
                });
            }
            catch (DataServiceRequestException e)
            {
                ErrorHandler.Error(string.Format("{0}: Could not write log entry to {1}: {2}",
                    GetType().AssemblyQualifiedName, _tableEndpoint, e.Message));
            }
        };
        doWriteToLog.BeginInvoke(null, null);
    }
}
</pre></p>

<p>In the code above, the actually writing to the log is done asynchronically in order to prevent the log write to slow down the request handling. We are now done with all the coding. What is left is to use our new <code>AzureTableStorageAppender</code>. Here is the <code>log4net.config</code>:</p>

<p><pre class="xml" name="code">
&lt;log4net&gt;
  &lt;appender name="AzureTableStoreAppender" type="Demo.Log4Net.Azure.AzureTableStorageAppender, Demo.Log4Net.Azure"&gt;
    &lt;param name="TableStorageConnectionStringName" value="Log4Net.ConenctionString" /&gt;
  &lt;/appender&gt;
  &lt;root&gt;
    &lt;level value="DEBUG" /&gt;
    &lt;appender-ref ref="AzureTableStoreAppender" /&gt;
  &lt;/root&gt;
&lt;/log4net&gt;
</pre></p>

<p>Notice the <code>TableSTorageConnectionStringName</code> attribute of the <code>param</code> element in the configuration. It corresponds to the property of the same name in the <code>AzureTableStorageAppender</code>. Furthermore, take take notice that it&#8217;s value is <code>'Log4Net.ConnectionString'</code>, which corresponds to a custom configuration setting that we will add to <code>ServiceDefinition.csdef</code> file:</p>

<p><pre class="xml" name="code">
&lt;ServiceDefinition ...&gt;
  &lt;WebRole ...&gt;
    &lt;ConfigurationSettings&gt;
      &lt;Setting name="Log4Net.ConenctionString"/&gt;
    &lt;/ConfigurationSettings&gt;
    ...
  &lt;/WebRole&gt;
&lt;/ServiceDefinition&gt;
</pre></p>

<p>We also need to give the <code>Log4Net.ConfigurationString</code> setting a value in the <code>ServiceConfiguration.cscfg</code> file. It should be a connection string that points to the storage account to use for storing the log entries. In this example, let&#8217;s use the development storage:</p>

<p><pre class="xml" name="code">
&lt;ServiceConfiguration ...&gt;
  &lt;Role ...&gt;
    &lt;ConfigurationSettings&gt;
      &lt;Setting name="Log4Net.ConenctionString" value="UseDevelopmentStorage=true"/&gt;
    &lt;/ConfigurationSettings&gt;
  &lt;/Role&gt;
&lt;/ServiceConfiguration&gt;
</pre></p>

<p>&#8230;and that&#8217;s it. You should now find the log entries in the table storage:</p>

<p><a href="http://www.kongsli.net/nblog/wp-content/uploads/2011/08/Skjermbilde-2011-08-03-kl.-12.57.21.png"><img src="http://www.kongsli.net/nblog/wp-content/uploads/2011/08/Skjermbilde-2011-08-03-kl.-12.57.21.png" alt="" title="Log entries in table storage" width="924" height="149" class="alignnone size-full wp-image-324" /></a></p>

<p>You can find the code for this example on <a href="https://github.com/vidarkongsli/azuretablestorageappender">GitHub</a>. Suggestions for improvement are very welcome.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.kongsli.net%2Fnblog%2F2011%2F08%2F15%2Flog4net-writing-log-entries-to-azure-table-storage%2F&amp;title=Log4Net%3A%20writing%20log%20entries%20to%20Azure%20Table%20Storage" id="wpa2a_10"><img src="http://www.kongsli.net/nblog/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.kongsli.net/nblog/2011/08/15/log4net-writing-log-entries-to-azure-table-storage/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Customizing Log4net log entries on Azure</title>
		<link>http://www.kongsli.net/nblog/2011/08/08/customizing-log4net-log-entries-on-azure/</link>
		<comments>http://www.kongsli.net/nblog/2011/08/08/customizing-log4net-log-entries-on-azure/#comments</comments>
		<pubDate>Mon, 08 Aug 2011 11:16:08 +0000</pubDate>
		<dc:creator>vidarkongsli</dc:creator>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Microsoft technologies]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[cloud]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[log4net]]></category>
		<category><![CDATA[PaaS]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://www.kongsli.net/nblog/?p=291</guid>
		<description><![CDATA[I have earlier blogged about how to use Log4Net on Azure compute. With this solution the log files from the various running instances gets transferred to a common container on Azure blob store. When I mine the log data, I usually merge all the log files together an run text utils like grep or sed [...]]]></description>
			<content:encoded><![CDATA[<p>I have earlier <a href="http://www.kongsli.net/nblog/?p=266">blogged about how to use Log4Net on Azure compute</a>. With this solution the log files from the various running instances gets transferred to a common container on Azure blob store. When I mine the log data, I usually merge all the log files together an run text utils like grep or sed on them.</p>

<p>One challenge when merging the log files together is that we then lose the information about which instance the different log entries came from. In order to fix this, we can customize the log entries to that we keep this information.</p>

<p>The first we need to do, is to create a new layout class that inherits from PatternLayout:</p>

<p><pre class="c-sharp" name="code">
using log4net.Layout;
namespace Demo.Log4Net.Azure
{
    public class AzurePatternLayout : PatternLayout
    {
        public AzurePatternLayout()
        {
             // TODO: add converters
        }
    }
}
</pre></p>

<p>Next, we need to register this class in the log4net configuration:</p>

<p><pre class="xml" name="code">
&lt;log4net&gt;
  &lt;appender ...&gt;
    &lt;layout type="Demo.Log4Net.Azure.AzurePatternLayout, Demo.Log4Net.Azure"&gt;
      &lt;conversionPattern ... /&gt;
    &lt;/layout&gt;
  &lt;/appender&gt;
  ...
&lt;/log4net&gt;
</pre></p>

<p>So now that we have a new <code>PatternLayout</code> class, we can add some logic into it for adding Azure-specific log information into the entries. To do so, we first need a new <code>Converter</code> class:</p>

<p><pre class="c-sharp" name="code">
using System.IO;
using log4net.Util;
using Microsoft.WindowsAzure.ServiceRuntime;
namespace Demo.Log4Net.Azure
{
    internal class AzureInstanceIdPatternConverter : PatternConverter
    {
        protected override void Convert(TextWriter writer, object state)
        {
            writer.Write(RoleEnvironment.CurrentRoleInstance.Id);
        }
    }
}
</pre></p>

<p>Now, we register the new <code>AzureInstanceIdPatternConverter</code> in the constructor of <code>AzurePatternLayout</code>:</p>

<p><pre class="c-sharp" name="code">
public class AzurePatternLayout : PatternLayout
{
    public AzurePatternLayout()
    {
        AddConverter("roleinstance", typeof(AzureInstanceIdPatternConverter));
    }
}
</pre></p>

<p>Then we can change the <code>conversionPattern</code> element of the Log4Net configuration to use the new Azure environment information:</p>

<p><pre class="xml" name="code">
&lt;layout type="Demo.Log4Net.Azure.AzurePatternLayout, Demo.Log4Net.Azure"&gt;
  &lt;conversionPattern value="%date [%roleinstance] [%thread] %-5level %logger [%appdomain] - %message%newline" /&gt;
&lt;/layout&gt;
</pre></p>

<p>&#8230;.which will make the log entries look something like this:</p>

<div id="attachment_296" class="wp-caption alignnone" style="width: 889px"><a href="http://www.kongsli.net/nblog/wp-content/uploads/2011/08/Skjermbilde-2011-08-01-kl.-09.11.48.png"><img src="http://www.kongsli.net/nblog/wp-content/uploads/2011/08/Skjermbilde-2011-08-01-kl.-09.11.48.png" alt="" title="Custom log entries" width="879" height="111" class="size-full wp-image-296" /></a><p class="wp-caption-text">Custom log entries</p></div>

<p>(The screenshot shows instance ids generated by DevFabric, not an instance in the cloud)</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.kongsli.net%2Fnblog%2F2011%2F08%2F08%2Fcustomizing-log4net-log-entries-on-azure%2F&amp;title=Customizing%20Log4net%20log%20entries%20on%20Azure" id="wpa2a_12"><img src="http://www.kongsli.net/nblog/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.kongsli.net/nblog/2011/08/08/customizing-log4net-log-entries-on-azure/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using Log4Net in Azure Compute</title>
		<link>http://www.kongsli.net/nblog/2011/08/03/using-log4net-in-azure-compute/</link>
		<comments>http://www.kongsli.net/nblog/2011/08/03/using-log4net-in-azure-compute/#comments</comments>
		<pubDate>Wed, 03 Aug 2011 12:57:50 +0000</pubDate>
		<dc:creator>vidarkongsli</dc:creator>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Microsoft technologies]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[cloud]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[iis]]></category>
		<category><![CDATA[log4net]]></category>
		<category><![CDATA[PaaS]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://www.kongsli.net/nblog/?p=266</guid>
		<description><![CDATA[Log4Net is a popular logging framework, and if you have an existing application that you wish to move to Azure compute, you probably want to avoid rewriting your application to use another logging framework. Luckily, keeping Log4Net as your logging tool in Azure is certainly possible, but there are a few hoops you have to [...]]]></description>
			<content:encoded><![CDATA[<p>Log4Net is a popular logging framework, and if you have an existing application that you wish to move to Azure compute, you probably want to avoid rewriting your application to use another logging framework. Luckily, keeping Log4Net as your logging tool in Azure is certainly possible, but there are a few hoops you have to jump through to get there.</p>

<p>There are several ways to achieve this goal. I decided to rely as much as possible on a feature provided in Azure Compute that allows for automatically synchronizing certain directories on the instance&#8217;s local file system to Azure blob storage. Using this approach, there are only very few changes that need to be done in the application, and indeed none of the existing code needs to be altered.</p>

<h3>Baseline: an existing application which uses Log4Net</h3>

<p>In order for this example to work, we need an application that we what to move to the cloud:</p>

<ol>
<li>Start off with <code>File->New-&gt;Project...</code> in Visual Studio and use the &#8220;ASP.NET Web Application&#8221; template</li>
<li>Add Log4Net capabilities to the application. This can be done by adding a reference to <a title="Log4Net in Nuget gallery" href="http://nuget.org/List/Packages/log4net">Log4Net using Nuget</a>, and then configuring it like <a title="About Phil Haack" href="http://haacked.com/articles/AboutHaacked.aspx">Phil Haack</a> has described <a title="Quick and Dirty Guide to Configuring Log4Net For Web Applications" href="http://haacked.com/archive/2005/03/07/ConfiguringLog4NetForWebApplications.aspx">here</a>.</li>
</ol>

<p>Then, run the web application locally in Visual Studio to assert that the logging works.</p>

<h3>Enabling the application for Azure</h3>

<p>Starting off with the simple ASP.NET web application we created in the previous section, do the following:</p>

<ol>
<li>Right-click on the solution in Visual Studio to select <code>Add-&gt;New Project</code>. Use the Windows Azure Project template, and do not add any roles in the dialog box initially.</li>
<li>Set the newly created cloud project as the startup project in the solution.</li>
<li>Right-click on the Roles-folder of the newly created Azure project and select <code>Add-&gt;Web role project in solution...</code> to add the web application project as an Azure Web role.</li>
</ol>

<div id="attachment_282" class="wp-caption alignnone" style="width: 524px"><a href="http://www.kongsli.net/nblog/wp-content/uploads/2011/08/Skjermbilde-2011-07-28-kl.-15.24.53.png"><img src="http://www.kongsli.net/nblog/wp-content/uploads/2011/08/Skjermbilde-2011-07-28-kl.-15.24.53.png" alt="" title="Adding a web role" width="514" height="127" class="size-full wp-image-282" /></a><p class="wp-caption-text">Adding an Azure Compute web role to an existing ASP.NET solution</p></div>

<p>Now, press <code>F5</code> to run the application in the local Azure development environment (DevFabric) to see that it works (functionally, not logging-wise)</p>

<p>So, we are done with the prerequisites. Now to the interesting parts!</p>

<h3>Setting log directory for Azure</h3>

<p>The first issue we will grapple with is the fact that in Azure Compute, the application effectively runs in a sandbox with limited access to the file system, which means that the &#8220;standard&#8221; approach logging to a file does not work. Basically, the Azure compute role has only access to a certain subdirectory of the file system and the exact location needs to be retrieved by the application at runtime.</p>

<p>In order to retain the existing logging in the application, locating the path to the role&#8217;s designated area on the disk can be solved by subclassing one of the appenders that Log4Net provides out of the box. I chose the <code>RollingFileAppender</code> because it provides the ability to split the log into several files. This is beneficial from an operations perspective. Here&#8217;s what the custom appender looks like:</p>

<p><pre class="c-sharp" name="code">
using System.Diagnostics;
using System.IO;
using log4net.Appender;
using Microsoft.WindowsAzure.ServiceRuntime;
namespace Demo.Log4Net.Azure
{
    public class AzureAppender : RollingFileAppender
    {
        public override string File
        {
            set
            {
                base.File = RoleEnvironment.GetLocalResource("Log4Net").RootPath + @"\" 
                    + new FileInfo(value).Name + "_"
                    + Process.GetCurrentProcess().ProcessName;
            }
        }
    }
}
</pre></p>

<p>What happens here, is that when the configuration is read when the logging framework initializes, it calls our method to set the log file name. This corresponds to the file element in the XML configuration for the appender:</p>

<p><pre class="xml" name="code">
&lt;log4net&gt;
  &lt;appender&gt;
    &lt;param name="File" value="app.log" /&gt;
    ...
  &lt;/appender&gt;
  ...
&lt;/log4net&gt;
</pre></p>

<p>What happens here, is that the application asks the role environment for the whereabouts of the local resource called &#8220;Log4Net&#8221;. This resource is a directory that we specify designated for containing our logs and needs to be specified in the <code>ServiceDefinition.csdef</code> file:</p>

<p><pre class="xml" name="code">
&lt;ServiceDefinition&gt;
  &lt;WebRole name="WebRole1"&gt;
    &lt;LocalResources&gt;
        &lt;LocalStorage name="Log4Net" sizeInMB="2048" cleanOnRoleRecycle="true"/&gt; 
    &lt;/LocalResources&gt;
  &lt;/WebRole&gt;
&lt;/ServiceDefinition&gt;
</pre></p>

<p>When we have the path of the local resource, it is used to construct an absolute path for the log file. Also note that the current process name is appended to the filename. This is done because if you run the application as a WebRole in &#8220;Full IIS&#8221; mode in Azure, the web application and the <code>RoleEntryPoint</code> code run in different processes. (If you look at blog entries on the Internet for Azure information, you should have in mind that the &#8220;Full IIS&#8221; mode was introduced with the Azure SDK version 1.3 in late 2010, and information that predates this might not be valid for the current Azure version.) This means that if there are log entries in the <code>RoleEntryPoint</code> as well as in the rest of your application, two processes would potentially try to keep a write lock on the file at the same time. Therefore, we use one log file for each process. Note that this is not a relevant topic for Worker roles. For more on the execution model, take a look <a title="New Full IIS Capabilities: Differences from Hosted Web Core" href="http://blogs.msdn.com/b/windowsazure/archive/2010/12/02/new-full-iis-capabilities-differences-from-hosted-web-core.aspx">here</a>.</p>

<p>
So, now that the new custom appender is ready, we need to change the Log4Net configuration to use it. Basically, we change the assembly type in the appender configuration section so that the configuration looks like this:</p>

<p><pre class="xml" name="code">
&lt;log4net&gt;
  &lt;appender name="AzureRollingLogFileAppender" type="Demo.Log4Net.Azure.AzureAppender, Demo.Log4Net.Azure"&gt;
    &lt;param name="File" value="app.log" /&gt;
    &lt;param name="AppendToFile" value="true" /&gt;
    &lt;param name="RollingStyle" value="Date" /&gt;
    &lt;param name="StaticLogFileName" value="false" /&gt;
    &lt;param name="DatePattern" value=".yyyy-MM-dd.lo\g" /&gt;
    &lt;layout type="log4net.Layout.PatternLayout"&gt;
      &lt;conversionPattern value="%date [%thread] %-5level %logger [%appdomain] - %message%newline" /&gt;
    &lt;/layout&gt;
  &lt;/appender&gt;
  &lt;root&gt;
    &lt;level value="DEBUG" /&gt;
    &lt;appender-ref ref="AzureRollingLogFileAppender" /&gt;
  &lt;/root&gt;
&lt;/log4net&gt;
</pre></p>

<p>Now it&#8217;s time to run the application to see if the logging works. First, deploy to devfabric, and then open the Windows Azure Compute Emulator. Right-click on the running instance, and click on <code>Open local store...</code>.</p>

<div id="attachment_283" class="wp-caption alignnone" style="width: 326px"><a href="http://www.kongsli.net/nblog/wp-content/uploads/2011/08/Skjermbilde-2011-07-28-kl.-15.50.55.png"><img src="http://www.kongsli.net/nblog/wp-content/uploads/2011/08/Skjermbilde-2011-07-28-kl.-15.50.55.png" alt="" title="Open local folder in devstore" width="316" height="188" class="size-full wp-image-283" /></a><p class="wp-caption-text">Open the local store for a role instance running in DevFabric</p></div>

<p>Then navigate to the &#8216;<code>directory\Log4Net</code>&#8216; to find the log files:</p>

<div id="attachment_288" class="wp-caption alignnone" style="width: 598px"><a href="http://www.kongsli.net/nblog/wp-content/uploads/2011/08/Skjermbilde-2011-08-01-kl.-08.37.35.png"><img src="http://www.kongsli.net/nblog/wp-content/uploads/2011/08/Skjermbilde-2011-08-01-kl.-08.37.35.png" alt="" title="Log files in local store in DevFabric" width="588" height="135" class="size-full wp-image-288" /></a><p class="wp-caption-text">Log files in local store in DevFabric</p></div>

<h3>Persisting logs to Azure blob storage</h3>

<p>The next issue we need to handle, is the fact that the local file system in an Azure role instance is not persistent. Local data will be lost when the application is redeployed (and also when the Role recycles, if you have chosen to do so). Furthermore, the only way to access the local file system is using a Remote Desktop Connection. In theory, you could probably also make the directory a shared drive accessible over the Internet, but you probably would not want to do that. Besides, it will be a headache if you have a lot of instances.</p>

<p>So, the solution that Azure offers to this, is to have a scheduled synchronization of certain of the local resources (directories) to the Azure blob store. What we need to do, is to add the following code to the descendant of <code>RoleEntryPoint</code>:</p>

<p><pre class="c-sharp" name="code">
public class WebRole : RoleEntryPoint
{
    public override bool OnStart()
    {
        var diagnosticsConfig = DiagnosticMonitor.GetDefaultInitialConfiguration();
        diagnosticsConfig.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(5);
        diagnosticsConfig.Directories.DataSources.Add(
                new DirectoryConfiguration
                {
                    Path = RoleEnvironment.GetLocalResource("Log4Net").RootPath,
                    DirectoryQuotaInMB = 2048,
                    Container = "wad-log4net"
                }
        );
        DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", diagnosticsConfig);
        return base.OnStart();
    }
}
</pre></p>

<p>&#8230;and that&#8217;s it. Now you can try to run the application and observe a container called &#8216;wad-log4net&#8217; will be created in your blob service account that will contain the logs:</p>

<div id="attachment_284" class="wp-caption alignnone" style="width: 651px"><a href="http://www.kongsli.net/nblog/wp-content/uploads/2011/08/Skjermbilde-2011-07-28-kl.-16.08.13.png"><img src="http://www.kongsli.net/nblog/wp-content/uploads/2011/08/Skjermbilde-2011-07-28-kl.-16.08.13.png" alt="" title="Logs in blob storage" width="641" height="200" class="size-full wp-image-284" /></a><p class="wp-caption-text">Logs in Azure blob store</p></div>

<p>(I use the <a href="http://clumsyleaf.com/products/azurexplorer" title="Homepage: AzureXplorer">AzureXplorer</a> extension for Visual Studio)</p>

<p>The solution shown here targeted an ASP.NET application running as a WebRole, but the setup works equally well for Worker roles.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.kongsli.net%2Fnblog%2F2011%2F08%2F03%2Fusing-log4net-in-azure-compute%2F&amp;title=Using%20Log4Net%20in%20Azure%20Compute" id="wpa2a_14"><img src="http://www.kongsli.net/nblog/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.kongsli.net/nblog/2011/08/03/using-log4net-in-azure-compute/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Azure DevFabric: clean out old deploments</title>
		<link>http://www.kongsli.net/nblog/2011/04/17/azure-devfabric-clean-out-old-deploments/</link>
		<comments>http://www.kongsli.net/nblog/2011/04/17/azure-devfabric-clean-out-old-deploments/#comments</comments>
		<pubDate>Sun, 17 Apr 2011 19:21:59 +0000</pubDate>
		<dc:creator>vidarkongsli</dc:creator>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Microsoft technologies]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[cloud]]></category>
		<category><![CDATA[compute]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[devfabric]]></category>
		<category><![CDATA[disk space]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://www.kongsli.net/nblog/?p=256</guid>
		<description><![CDATA[During development of an Azure application, I noticed that my disk kept running full. First time it happended, I thought nothing of it and just ran disk cleanup to clear out some obsolent files. Problem solved. At least, so I thought. Some hours later, I got a disk full warning once again. It turned out [...]]]></description>
			<content:encoded><![CDATA[<p>During development of an Azure application, I noticed that my disk kept running full. First time it happended, I thought nothing of it and just ran disk cleanup to clear out some obsolent files. Problem solved. At least, so I thought. Some hours later, I got a disk full warning once again. It turned out that it was caused by old local DevFabric deployments that used up disk space. Even though the deployments have been shut off, the deployment files lingered on. This is how the %USERPROFILE%\AppData directory looked like:</p>

<p style="text-align: center;"><a href="http://www.kongsli.net/nblog/wp-content/uploads/2011/04/devstore.png"><img class="aligncenter size-medium wp-image-257" title="devstore" src="http://www.kongsli.net/nblog/wp-content/uploads/2011/04/devstore-248x300.png" alt="" width="291" height="352" /></a></p>

<p style="text-align: left;">What I had to do to fix this, was to run the following command:</p>

<p><pre class="batch">csrun /devfabric:clean</pre>
Then, the old deployment files were deleted:</p>

<p><a href="http://www.kongsli.net/nblog/wp-content/uploads/2011/04/devstore_after.png"><img class="aligncenter size-full wp-image-258" title="devstore_after" src="http://www.kongsli.net/nblog/wp-content/uploads/2011/04/devstore_after.png" alt="" width="503" height="164" /></a></p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.kongsli.net%2Fnblog%2F2011%2F04%2F17%2Fazure-devfabric-clean-out-old-deploments%2F&amp;title=Azure%20DevFabric%3A%20clean%20out%20old%20deploments" id="wpa2a_16"><img src="http://www.kongsli.net/nblog/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.kongsli.net/nblog/2011/04/17/azure-devfabric-clean-out-old-deploments/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Adding WCF REST services to existing ASP.NET web application</title>
		<link>http://www.kongsli.net/nblog/2011/04/06/adding-wcf-rest-services-to-existing-asp-net-web-application/</link>
		<comments>http://www.kongsli.net/nblog/2011/04/06/adding-wcf-rest-services-to-existing-asp-net-web-application/#comments</comments>
		<pubDate>Wed, 06 Apr 2011 13:14:09 +0000</pubDate>
		<dc:creator>vidarkongsli</dc:creator>
				<category><![CDATA[Microsoft technologies]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[System integration]]></category>
		<category><![CDATA[.net4]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[wcf]]></category>
		<category><![CDATA[wcf4]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.kongsli.net/nblog/?p=243</guid>
		<description><![CDATA[If you want to create a new WCF services application with REST support, the WCF REST Templates are brilliant. However, if you have an existing ASP.NET application from which you want to expose REST services, there are a few manual steps you need to take to get it up and running: Add assembly references Add [...]]]></description>
			<content:encoded><![CDATA[<p>If you want to create a new WCF services application with REST support, the <a href="http://visualstudiogallery.msdn.microsoft.com/fbc7e5c1-a0d2-41bd-9d7b-e54c845394cd">WCF REST Templates</a> are brilliant. However, if you have an existing ASP.NET application from which you want to expose REST services, there are a few manual steps you need to take to get it up and running:</p>

<h2>Add assembly references</h2>

<p>Add references to the following assemblies in your existing web project:</p>

<ul>
<li>System.ServiceModel</li>
<li>System.ServiceModel.Activation</li>
<li>System.ServiceModel.Web</li>
</ul>

<h2>Create service class</h2>

<p>Create a new service class where you will implement the service:</p>

<p><pre class="c-sharp" name="code">
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class LetterService
{
    [WebGet(UriTemplate = "")]
    public List&lt;string&gt; GetList()
    {
        return new List&lt;string&gt;{"a", "b", "c"};
    }
}
</pre></p>

<h2>Register service route</h2>

<p>In <code>Global.asax.cs</code>, define a route to the service:</p>

<p><pre class="c-sharp" name="code">
void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.Add(new ServiceRoute("letter", new WebServiceHostFactory(), typeof(LetterService)));
}
</pre></p>

<h2>Enable ASP.NET compatability</h2>

<p>Add the following to <code>web.config</code>:</p>

<p><pre class="xml" name="code">
&lt;configuration&gt;
   &lt;system.serviceModel&gt;
      &lt;serviceHostingEnvironment aspNetCompatibilityEnabled="true"/&gt;
   &lt;/system.serviceModel&gt;
&lt;/configuration&gt;
</pre></p>

<p>&#8230;and you are good to go! The service will be available on <code>http://&lt;server&gt;/letter</code></p>

<h2>Optional: enable help</h2>

<p>In order to get a nice help page for clients connecting to the service, add the following under the <code>system.serviceModel</code> element in <code>web.config</code>:</p>

<p><pre class="xml" name="code">
&lt;standardEndpoints&gt;
   &lt;webHttpEndpoint&gt;
      &lt;standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" /&gt;
   &lt;/webHttpEndpoint&gt;
&lt;/standardEndpoints&gt;
</pre></p>

<p>Then, help will be available on <code>http://&lt;server&gt;/letter/help</code></p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.kongsli.net%2Fnblog%2F2011%2F04%2F06%2Fadding-wcf-rest-services-to-existing-asp-net-web-application%2F&amp;title=Adding%20WCF%20REST%20services%20to%20existing%20ASP.NET%20web%20application" id="wpa2a_18"><img src="http://www.kongsli.net/nblog/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.kongsli.net/nblog/2011/04/06/adding-wcf-rest-services-to-existing-asp-net-web-application/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Creating Azure blob storage shared access signatures using JavaScript</title>
		<link>http://www.kongsli.net/nblog/2011/03/16/creating-azure-blob-storage-shared-access-signatures-using-javascript/</link>
		<comments>http://www.kongsli.net/nblog/2011/03/16/creating-azure-blob-storage-shared-access-signatures-using-javascript/#comments</comments>
		<pubDate>Wed, 16 Mar 2011 07:00:41 +0000</pubDate>
		<dc:creator>vidarkongsli</dc:creator>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Microsoft technologies]]></category>
		<category><![CDATA[Software development]]></category>

		<guid isPermaLink="false">http://www.kongsli.net/nblog/?p=205</guid>
		<description><![CDATA[There are quite a lot of examples on the Internet on how to create a shared access signature for Azure storage. However, the examples are often in C# or pseudo-code. A Shared Access Signature is basically what is called a message authentication code &#8211; MAC &#8211; that is used to grant a user access to [...]]]></description>
			<content:encoded><![CDATA[<p>There are quite a lot of examples on the Internet on how to <a href="http://msdn.microsoft.com/en-us/library/ee395415.aspx">create a shared access signature</a> for <a href="http://www.microsoft.com/windowsazure/storage/default.aspx">Azure storage</a>. However, the examples are often in C# or pseudo-code.</p>

<p>A Shared Access Signature is basically what is called a <a href="http://en.wikipedia.org/wiki/Message_authentication_code">message authentication code</a> &#8211; MAC &#8211; that is used to grant a user access to a restricted resource, often for a certain period of time. (In other words, a MAC typically has a validity period). In the case of Azure, a so-called Hashed MAC is used &#8211; <a href="http://en.wikipedia.org/wiki/HMAC">HMAC</a>. This is achieved using standard cryptography functionality, namely the <a href="http://en.wikipedia.org/wiki/Secure_Hash_Algorithm">SHA-256</a> hash algorithm. By using standard cryptography functionality, creating such MACs is also available in other programming languages and platforms.</p>

<p>In this blog entry I will show how to create MACs for Azure blob storage using JavaScript.</p>

<p>The first thing we need, is a library with cryptography functions. I chose <a href="http://code.google.com/p/crypto-js/">Crypto-JS</a>:
<pre class="html" name="code">&lt;script type="text/javascript" src="http://crypto-js.googlecode.com/files/2.0.0-crypto-sha256.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="http://crypto-js.googlecode.com/files/2.0.0-hmac.min.js"&gt;&lt;/script&gt;</pre>
Next, we create a function to generate the signature we need:
<pre class="javascript" name="code">Date.prototype.toIso8061 = function() {
   var d = this;
   function p(i) { return ("0"  + i).slice(-2); }
   return "yyyy-MM-ddThh:mm:ssZ"
      .replace(/yyyy/, d.getUTCFullYear())
      .replace(/MM/, p(d.getUTCMonth()))
      .replace(/dd/, p(d.getUTCDay()))
      .replace(/hh/, p(d.getUTCHours()))
      .replace(/mm/, p(d.getUTCMinutes()))
      .replace(/ss/, p(d.getUTCSeconds()));
};
function generateSignature(base64EncodedSharedKey, startTime, endTime, account, container, blobName) {
   var stringToSign = "r\n{0}\n{1}\n/{2}/{3}/{4}\n"
      .replace(/&#123;0&#125;/, startTime.toIso8061())
      .replace(/&#123;1&#125;/, endTime.toIso8061())
      .replace(/&#123;2&#125;/, account)
      .replace(/&#123;3&#125;/, container)
      .replace(/&#123;4&#125;/, blobName);
   var accessKeyBytes = Crypto.util.base64ToBytes(base64EncodedSharedKey);
   return Crypto.util.bytesToBase64(Crypto.HMAC(Crypto.SHA256, stringToSign, accessKeyBytes, { asBytes: true }));
}</pre>
Then, we can construct a URL that we will use to request a resource from the blob store:
<pre class="javascript" name="code">var start = new Date(); // Start of the validity period of the MAC
var end = new Date(start.getTime() + (1000 * 60 * 30)); // End of the validity period, half an hour from now
var signature = generateSignature(startTime, endTime, "myaccount", "foryoureyesonly", "liveorletdie.avi");
var queryString = "?st={0}&amp;se={1}&amp;sr=b&amp;sp=r&amp;sig={2}"
   .replace(/&#123;0&#125;/, encodeURIComponent(startTime.toIso8061()))
   .replace(/&#123;1&#125;/, encodeURIComponent(endTime.toIso8061()))
   .replace(/&#123;2&#125;/, encodeURIComponent(signature));
var url = "http://myaccount.blob.core.windows.net/foryoureyesonly/liveorletdie.avi" + queryString;</pre></p>

<h2>Security warning</h2>

<p>Although possible to do, it is not always advisable to generate the signature in a browser because generating the signature requires access to the shared key. The shared key is highly sensitive data, it is often not advisable to trust the browser client with this information if it should not be disclosed to the browser user. There are, however, some use cases where this is OK. I am planning to blog about one of them later on. Also, the code above can easily be used in a server-side scenario, such as a solution based on <a href="http://nodejs.org">node.js</a>.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.kongsli.net%2Fnblog%2F2011%2F03%2F16%2Fcreating-azure-blob-storage-shared-access-signatures-using-javascript%2F&amp;title=Creating%20Azure%20blob%20storage%20shared%20access%20signatures%20using%20JavaScript" id="wpa2a_20"><img src="http://www.kongsli.net/nblog/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.kongsli.net/nblog/2011/03/16/creating-azure-blob-storage-shared-access-signatures-using-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
<enclosure url="http://myaccount.blob.core.windows.net/foryoureyesonly/liveorletdie.avi" length="0" type="video/avi" />
		</item>
	</channel>
</rss>

