<?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>Degree Blogg</title>
	<atom:link href="http://blog.degree.no/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.degree.no</link>
	<description>Better to be a geek than an idiot!</description>
	<lastBuildDate>Wed, 22 Feb 2012 02:47:46 +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>LINQ &#8211; how to build queries dynamically</title>
		<link>http://blog.degree.no/2012/02/linq-how-to-build-queries-dynamically/</link>
		<comments>http://blog.degree.no/2012/02/linq-how-to-build-queries-dynamically/#comments</comments>
		<pubDate>Wed, 22 Feb 2012 02:43:21 +0000</pubDate>
		<dc:creator>Andreas</dc:creator>
				<category><![CDATA[Degree Blogg]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://blog.degree.no/2012/02/linq-how-to-build-queries-dynamically/</guid>
		<description><![CDATA[In a previous post I described a way to build dynamic WHERE clauses to achieve the WHERE [value] IN [array] functionality using LINQ. This post will show how you can combine LINQ with lambda to achieve a different type of dynamic / runtime query building. (The example is using Entity Framework 4.2). I came across [...]]]></description>
			<content:encoded><![CDATA[<p>In a <a href="http://blog.degree.no/2012/01/linq-how-to-build-a-dynamic-where-clause-c/" target="_blank">previous post</a> I described a way to build dynamic WHERE clauses to achieve the <em><strong>WHERE [value] IN [array]</strong></em> functionality using LINQ. This post will show how you can combine LINQ with lambda to achieve a different type of dynamic / runtime query building. (The example is using <em>Entity Framework 4.2</em>).</p>
<p>I came across a need for this when dealing with Guid columns in SQL Server. In code, Guid.Empty isn’t <em>NULL</em>, it’s “00000000-0000-0000-0000-000000000000”. This doesn’t go too well with the unique index of the table, which of course ignores <em>NULL</em> values but considers “00000000-0000-0000-0000-000000000000” a real value – which it is! So the challenge was to alter the LINQ query depending on one of the input parameters of the method. If the Guid parameter is equal to Guid.Empty, I want to query the database for <em>NULL</em> values in that column. If the Guid <em>has</em> a valid value, query the database using it the way it is. </p>
<p>I made this work by adding a conditional IF, but for readability I have split it up in an old fashion IF / ELSE. Define the LINQ query, and based on the input parameter “parentFolderId” define the WHERE statement using <em>lambda</em> :</p>
<pre class="csharpcode">var existingFolder = from f <span class="kwrd">in</span> db.Folders
             select f;

<span class="kwrd">if</span> (Guid.Empty.Equals(parentFolderId))
{
    <span class="rem">// parent folder is empty, which is NULL in DB (Guid.Empty = '00000000-0000-0000-0000-000000000000')</span>
    existingFolder = existingFolder.Where(p =&gt; p.FolderName == folderName &amp;&amp; p.ParentFolderID == <span class="kwrd">null</span>);
}
<span class="kwrd">else</span>
{
    existingFolder = existingFolder.Where(p =&gt; p.FolderName == folderName &amp;&amp; p.ParentFolderID == parentFolderId);
}

<span class="kwrd">if</span> (existingFolder.FirstOrDefault() != <span class="kwrd">null</span>)
    <span class="kwrd">return</span> <span class="kwrd">false</span>; <span class="rem">// folder already exists</span>

// create <span class="kwrd">new</span> folder</pre>
<p>Remember that a LINQ query isn’t executed until the result set is accessed. In this case the database isn’t queried until the line where “existingFolder.FirstOrDefault()” is executed, and the desired result is achieved with minimal code.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.degree.no/2012/02/linq-how-to-build-queries-dynamically/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XenApp 6.5 &#8211; STA could not be contacted</title>
		<link>http://blog.degree.no/2012/02/xenapp-6-5-sta-contacted/</link>
		<comments>http://blog.degree.no/2012/02/xenapp-6-5-sta-contacted/#comments</comments>
		<pubDate>Tue, 21 Feb 2012 11:21:48 +0000</pubDate>
		<dc:creator>Aage Andre</dc:creator>
				<category><![CDATA[Degree Blogg]]></category>

		<guid isPermaLink="false">http://blog.degree.no/?p=1942</guid>
		<description><![CDATA[Struggled for a day after setting up Secure Gateway for XenApp 6.5 with these two errors in event log: Site path: C:\inetpub\wwwroot\Citrix\XenApp. The Citrix XML Service object was not found: 404 Object not found. This message was reported from the XML Service at address http://xenapp.internaldomain.local:8080/scripts/ctxsta.dll  http://com.citrix.xml.CtxSTAProtocol.RequestTicket. The specified Secure Ticket Authority could not be contacted [...]]]></description>
			<content:encoded><![CDATA[<p>Struggled for a day after setting up Secure Gateway for XenApp 6.5 with these two errors in event log:</p>
<p><em>Site path: C:\inetpub</em><wbr><em>\wwwroot\Cit</em><wbr><em>rix\XenApp.</em><br />
<em>The Citrix XML Service object was not found: 404 Object not found. This message was reported from the XML Service at address <a href="http://xenapp.internaldomain.local:8080/scripts/ctxtsa.dll">http://xena<wbr>pp.internald<wbr>omain.local:<wbr>8080/scripts<wbr>/ctxsta.dll</wbr></wbr></wbr></wbr></a></em><wbr><em>  <a href="http://com.citrix.xml.ctxstaprotocol.requestticket/">http://com.<wbr>citrix.xml.C<wbr>txSTAProtoco<wbr>l.RequestTic<wbr>ket</wbr></wbr></wbr></wbr></a>. The specified Secure Ticket Authority could not be contacted and has been temporaril</em><wbr><em>y removed from the list of active services.</em></wbr></wbr></wbr></wbr></p>
<p><em>Site path: C:\inetpub</em><wbr><em>\wwwroot\Cit</em><wbr><em>rix\XenApp.</em><br />
<em> All the configured<wbr> Secure Ticket Authoritie<wbr>s failed to respond to this XML transactio<wbr>n.</wbr></wbr></wbr></em></wbr></wbr></p>
<p>&nbsp;</p>
<p>Mostly, google will give you the answer. What I didn't see anywhere, is that the configuration is <strong>case sensitive</strong>.</p>
<p>So when you set up the web interface and Secure Gateway:</p>
<p>Wrong: http://servername01.domain.local:8080/scripts/ctxsta.dll<br />
Correct: http://servername01.domain.local:8080/Scripts/CtxSTA.dll</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.degree.no/2012/02/xenapp-6-5-sta-contacted/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Windows Azure Storage Emulator &#8211; Blob service does not start</title>
		<link>http://blog.degree.no/2012/02/windows-azure-storage-emulator-blob-service-does-not-start/</link>
		<comments>http://blog.degree.no/2012/02/windows-azure-storage-emulator-blob-service-does-not-start/#comments</comments>
		<pubDate>Tue, 21 Feb 2012 03:33:54 +0000</pubDate>
		<dc:creator>Andreas</dc:creator>
				<category><![CDATA[Degree Blogg]]></category>
		<category><![CDATA[Azure]]></category>
		<category><![CDATA[Azure SDK]]></category>

		<guid isPermaLink="false">http://blog.degree.no/2012/02/windows-azure-storage-emulator-blob-service-does-not-start/</guid>
		<description><![CDATA[One of the features shipped with Windows Azure SDK for Visual Studio 2010 is the Azure Storage emulator. This little add-on enables you to run your very own Azure Cloud storage service locally while developing, and needless to say this makes everything quite a lot simpler. When first initialized, the emulator creates a database in [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.degree.no/wp-content/uploads/image33.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px 0px 0px 20px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" align="right" src="http://blog.degree.no/wp-content/uploads/image_thumb33.png" width="185" height="106" /></a>One of the features shipped with Windows Azure SDK for Visual Studio 2010 is the Azure Storage emulator. This little add-on enables you to run your very own Azure Cloud storage service locally while developing, and needless to say this makes everything quite a lot simpler.</p>
<p>When first initialized, the emulator creates a database in Microsoft SQL Server Express (which you can change to your local SQL Server if you want). It also sets up three services to emulate the Blob, Queue and Table types on different ports:</p>
<p><a href="http://blog.degree.no/wp-content/uploads/image32.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://blog.degree.no/wp-content/uploads/image_thumb32.png" width="359" height="121" /></a></p>
<p>If you receive the following error message when attempting to start one of the services (typically the Blob service)</p>
<p><strong><em>Process cannot access the file because it is being used by another process</em></strong></p>
<p>it actually means that the <em>port</em> is taken, not a <em>file</em>. Run “Netstat /a” from your command prompt to find the culprit that’s taking up your precious port (which will probably be your <strong>torrent client</strong> – don’t tell RIAA!).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.degree.no/2012/02/windows-azure-storage-emulator-blob-service-does-not-start/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ORM &amp; Linq &#8211; Know your queries and indexes!</title>
		<link>http://blog.degree.no/2012/02/orm-linq-queries-indexes/</link>
		<comments>http://blog.degree.no/2012/02/orm-linq-queries-indexes/#comments</comments>
		<pubDate>Fri, 17 Feb 2012 19:09:58 +0000</pubDate>
		<dc:creator>thorhalvor</dc:creator>
				<category><![CDATA[Degree Blogg]]></category>

		<guid isPermaLink="false">http://blog.degree.no/?p=1928</guid>
		<description><![CDATA[In many projects I have been working on we don't have database administrators (DBAs). At least not the kind of DBAs that optimize the queries/views etc. It’s mostly up to us developers. Nowadays we abstract database using O/R Mappers like nHibernate and Entity Framework. Doing this we don’t have to think about if we should [...]]]></description>
			<content:encoded><![CDATA[<p>In many projects I have been working on we don't have database administrators (DBAs). At least not the kind of DBAs that optimize the queries/views etc. It’s mostly up to us developers. Nowadays we abstract database using O/R Mappers like nHibernate and Entity Framework. Doing this we don’t have to think about if we should use an INNER or LEFT OUTER JOIN but we can just use the Query-objects given by the framework.</p>
<p>This blogpost’s main focus is not database optimization specifically, but more the importance of thinking and doing something about it even when using ORMs.</p>
<p>When creating Views in the database or writing SELECTs in general most developers remember to add INDEXES on the WHERE clauses, but when going through a O/R Mapper we sometimes forget. We have abstracted all of the database and our mindset is not "there".</p>
<p>Some examples:</p>
<pre class="csharpcode">var customer = _session.Query&lt;Customer&gt;()
                .Where(x =&gt; x.Email == <a href="mailto:“myemail@tempuri.org">“myemail@tempuri.org</a>”);</pre>
<p>&nbsp;</p>
<p>or a more advanced one:</p>
<pre class="csharpcode">var linq = (from product <span class="kwrd">in</span> session.Query&lt;Product&gt;()
join category <span class="kwrd">in</span> session.Query&lt;Category&gt;()
on product.Category.Id equals category.Id
<span class="kwrd">where</span> category.CategoryName == <span class="str">"Condiments"</span>
            &amp;&amp; !product.Discontinued
select product).ToList();</pre>
<p>The first example above is very simple and normally would take milliseconds to run. But what if we had millions of records in the database, then the query might take seconds. Particularly if we don’t have the Email column indexed in the database. In the second example maybe you don’t have a clue what kind of SELECT that was actually executed and then its hard to know what to optimize in the SQL Server…</p>
<p>Last example:</p>
<pre class="csharpcode">var blogpost = _session.Query&lt;BlogPost&gt;()
                .Where(x =&gt; x.Content.Contains(<span class="str">"nHibernate"</span>));</pre>
<p>&nbsp;</p>
<p>What is so special about this example? I guess you have used the Contains method hundred of times when working with Strings. But in this case it is on the ORM and the SELECT that is executed is most likely a ‘LIKE '”%nHibernate%’” who might trigger full table scan. (Depends on the scenarios, but a custom Full-Text Search might be vice here..)</p>
<p>To find out the SELECTs really executed on the SQL server you might have used the SQL Service Profiler and Database Engine Tuning Advisor. But most times we don’t. If you are using NHibernate they log all the queries on the DEBUG level using log4net.  But another perfect tool for this profiling is <a href="http://ayende.com/blog">Ayendes</a> <a href="http://nhprof.com/">NHProfiler</a>/<a href="http://efprof.com/">EFProfiler</a> ++. The tools won’t just display the SELECTs but also help you doing them better.</p>
<p><img style="display: block; float: none; margin-left: auto; margin-right: auto;" src="http://efprof.com/Uploads/WindowsLiveWriter/ScreenShots_CBBB/image_2.png" alt="" width="361" height="262" /></p>
<p>As he writes on <a href="http://efprof.com/">Efprof.com</a></p>
<p><em>"Entity Framework Profiler is a real-time visual debugger allowing a development team to gain valuable insight and perspective into their usage of Entity Framework. The product is architected with input coming from many top industry leaders within the OR/M community. Alerts are presented in a concise code-review manner indicating patterns of misuse by your application. To streamline your efforts to correct the misuse, we provide links to the problematic code section that triggered the alert."</em></p>
<p><em></em>So, when you are abstracting the database using various frameworks you should always know and care about your queries. If you don’t, you probably get issues in the production environments.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.degree.no/2012/02/orm-linq-queries-indexes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ADFS 2.0 / Claims authentication / Sharepoint 2010</title>
		<link>http://blog.degree.no/2012/02/adfs-2-0-claims-authentication-sharepoint-2010/</link>
		<comments>http://blog.degree.no/2012/02/adfs-2-0-claims-authentication-sharepoint-2010/#comments</comments>
		<pubDate>Tue, 14 Feb 2012 00:57:51 +0000</pubDate>
		<dc:creator>Andreas</dc:creator>
				<category><![CDATA[Degree Blogg]]></category>
		<category><![CDATA[ADFS 2.0]]></category>
		<category><![CDATA[Sharepoint 2010]]></category>

		<guid isPermaLink="false">http://blog.degree.no/2012/02/adfs-2-0-claims-authentication-sharepoint-2010/</guid>
		<description><![CDATA[You encounter the following error message in your event log: An operation failed because the following certificate has validation errors: [….] Errors: The root of the certificate chain is not a trusted root authority.. This might seem strange, because this will appear even if you have the CA certificate in your certificate store. The reason [...]]]></description>
			<content:encoded><![CDATA[<p>You encounter the following error message in your event log:</p>
<p><strong>An operation failed because the following certificate has validation errors: [….] Errors: The root of the certificate chain is not a trusted root authority..</strong></p>
<p>This might seem strange, because this will appear even if you have the CA certificate in your certificate store. The reason is that Sharepoint has it’s own registry of certificates, and you will have to add the CA there as well.</p>
<p>1. Open “ADFS 2.0 Management”   <br />2. Expand Service – Certificates    <br />3. Right click the primary (if more than one) certificate under Token-signing, and select View Certificate    <br />4. Choose the Details tab, and click “Copy to file…”    <br />5. Complete the wizard, saving the certificate as “DER encoded binary” (name it ADFSRoot.cer or something)    <br />6. Copy the .cer file over to your Sharepoint server</p>
<p>Now you have to add this certificate to Sharepoints list of root authorities. You’ll be using the Sharepoint 2010 Management Shell for this operation:   <br />1. Start Sharepoint 2010 Management Shell    <br />2. Run the following two commands (change the path to where your .cer is located):    </p>
<p>
<pre class="csharpcode">$root = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2(<span class="str">&quot;C:\TEMP\ADFSroot.cer&quot;</span>)</pre>
</p>
<pre class="csharpcode">New-SPTrustedRootAuthority -Name <span class="str">&quot;ADFS Token SigningRoot Authority&quot;</span> -Certificate $root</pre>
<p>3. The certificate properties will be listed as a confirmation that the certificate has been added.</p>
<p>If your certificate chain contains more than one certificate, you will have to do this with each one giving them a unique name.</p>
<p>Thanks to <a href="http://blogs.technet.com/b/speschka/archive/2010/02/13/root-of-certificate-chain-not-trusted-error-with-claims-authentication.aspx" target="_blank">Steve Peschka</a> for providing an excellent guide.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.degree.no/2012/02/adfs-2-0-claims-authentication-sharepoint-2010/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Citrix XenApp 6.5 and XenDesktop 5.5 SQL Database Configuration</title>
		<link>http://blog.degree.no/2012/02/citrix-xenapp-6-5-xendesktop-5-5-sql-database-configuration/</link>
		<comments>http://blog.degree.no/2012/02/citrix-xenapp-6-5-xendesktop-5-5-sql-database-configuration/#comments</comments>
		<pubDate>Mon, 06 Feb 2012 09:11:49 +0000</pubDate>
		<dc:creator>Aage Andre</dc:creator>
				<category><![CDATA[Degree Blogg]]></category>

		<guid isPermaLink="false">http://blog.degree.no/?p=1919</guid>
		<description><![CDATA[Finding information on Citrix products where you're not using the "default, quick setup, this is the way to do it in lab-environment" is always a pain. For some reason, people who are good at Citrix won't share info, and e-docs are pretty much useless, telling everything you can see with your own eyes("After you start [...]]]></description>
			<content:encoded><![CDATA[<p>Finding information on Citrix products where you're not using the "default, quick setup, this is the way to do it in lab-environment" is always a pain. For some reason, people who are good at Citrix won't share info, and e-docs are pretty much useless, telling everything you can see with your own eyes("After you start setup.exe, click Next to go to the next step". You don't say??)</p>
<p>When setting up XenApp 6.5 for the first time, there was absolutely no information on the database requirements to be found. The config-tool won't create the DB for you, so you'll have to do it manually, but info is hard to find.</p>
<p>I ended up booting my EVA that i downloaded for trial from Citrix and checking the collation on that database. Turns it was set to Latin1_General_CP1_CI_AS. So create your DB with that collation, and you should be good.<br />
(If I remember correctly, this is the same collation as XenDesktop uses, which has equal little info. I remember the only place I found it was in the comments of the generated scripts during setup)</p>
<p>Other than collation, default settings should be fine. I set Recovery model to Full, but either way, it shouldn't have an impact.</p>
<p><em>If you don't know how to set collation, create the DB like this:<strong><br />
</strong></em><em><strong>CREATE DATABASE CitrixXenAppDB COLLATE SQL_Latin1_General_CP1_CI_AS</strong></em></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.degree.no/2012/02/citrix-xenapp-6-5-xendesktop-5-5-sql-database-configuration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Accepting invalid SSL certificates programmatically (C#)</title>
		<link>http://blog.degree.no/2012/02/accepting-invalid-ssl-certificates-programmatically-c/</link>
		<comments>http://blog.degree.no/2012/02/accepting-invalid-ssl-certificates-programmatically-c/#comments</comments>
		<pubDate>Fri, 03 Feb 2012 03:58:39 +0000</pubDate>
		<dc:creator>Andreas</dc:creator>
				<category><![CDATA[Degree Blogg]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[SSL]]></category>

		<guid isPermaLink="false">http://blog.degree.no/2012/02/accepting-invalid-ssl-certificates-programmatically-c/</guid>
		<description><![CDATA[This might initially sound like a very bad idea, because it undermines one of the fundamental reasons for using SSL in the first place. But it’s suprising how often I come across situations where this comes in very handy, especially during development and testing when valid certificates aren’t present and you still want to test [...]]]></description>
			<content:encoded><![CDATA[<p>This might initially sound like a very bad idea, because it undermines one of the fundamental reasons for using SSL in the first place. But it’s suprising how often I come across situations where this comes in very handy, especially during development and testing when valid certificates aren’t present and you still want to test your code over a secured encrypted channel.</p>
<p>Add a static method for handling the validation logic (or to skip it entirely):</p>
<pre class="csharpcode"><span class="rem">// callback for validating SSL certificate during handshake</span>
<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> CustomCertificateValidatior(<span class="kwrd">object</span> sender,
    X509Certificate certificate, X509Chain chain,
    SslPolicyErrors policyErrors)
{
    <span class="rem">// anything goes!</span>
    <span class="kwrd">return</span> <span class="kwrd">true</span>;

    <span class="rem">// PS: you could put your own validation logic here, </span>
    <span class="rem">// through accessing the certificate properties:</span>
    <span class="rem">// var publicKey = certificate.GetPublicKey();</span>

}</pre>
<p>You then just add a RemoteCertificateValidationCallback before you make the SOAP / HTTP request, and your custom validator will take care of the validation.</p>
<p>&#160;</p>
<pre class="csharpcode"><span class="rem">// method where request is made</span>

<span class="rem">// ensure SSL certificate validation uses custom method</span>
ServicePointManager.ServerCertificateValidationCallback +=
       <span class="kwrd">new</span> RemoteCertificateValidationCallback(CustomCertificateValidatior);

<span class="rem">// initiate a SOAP or HTTP request like normal</span>
<span class="rem">// and your custom method will be used for validation</span>

// ..</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.degree.no/2012/02/accepting-invalid-ssl-certificates-programmatically-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sharepoint 2010 &#8211; access site usage statistics</title>
		<link>http://blog.degree.no/2012/01/sharepoint-2010-access-site-usage-statistics/</link>
		<comments>http://blog.degree.no/2012/01/sharepoint-2010-access-site-usage-statistics/#comments</comments>
		<pubDate>Wed, 25 Jan 2012 05:48:12 +0000</pubDate>
		<dc:creator>Andreas</dc:creator>
				<category><![CDATA[Degree Blogg]]></category>
		<category><![CDATA[Sharepoint 2010]]></category>

		<guid isPermaLink="false">http://blog.degree.no/2012/01/sharepoint-2010-access-site-usage-statistics/</guid>
		<description><![CDATA[OK, so you made the assumption that Microsofts Sharepoint team would have provided a simple way to access something as common (and not to mention extremely useful!) as site usage statistics. Which pages and resources are accessed at what time for how long how often the browser type http status and last but definately not [...]]]></description>
			<content:encoded><![CDATA[<p>OK, so you made the assumption that Microsofts Sharepoint team would have provided a simple way to access something as common (and not to mention extremely useful!) as <strong>site usage statistics</strong>. Which pages and resources are accessed </p>
<ul>
<li>at what time</li>
<li>for how long</li>
<li>how often</li>
<li>the browser type </li>
<li>http status</li>
<li>and last but definately not least: by <em>who.</em> </li>
</ul>
<p>And not only did you assume this would be easily accessible, you also told a client you’d have it done in a couple of hours. I assume some of you that ended up here either got lucky straight away, or you have already spent way more time than expected and added yet another element to your list of reasons why Sharepoint will make you loose your hair prematurely.</p>
<p>If you assumed that this data should be available <em>somewhere</em> you were right. The trick is to know how to access it from your custom web part. The data is stored in the WSS_Logging database, in a table called <strong><em>RequestUsage</em></strong>. You can run a simple query just to see what’s in there and which fields you have access to:</p>
<pre class="csharpcode"><span class="kwrd">SELECT</span> *
<span class="kwrd">FROM</span> [RequestUsage] </pre>
<p><font size="2"></font></p>
<p><font size="2">Then you can start getting a bit more creative. You see, the RequestUsage table contains statistics for all sorts of requests – like requests to the MetadataWebService. So depending on your needs, filter out the type of document types / extensions / paths you are interested in. I needed just to know the hit count of .aspx pages in a specific sub site, so my query looked somewhat like this:</font></p>
<pre class="csharpcode"><span class="kwrd">SELECT</span> <span class="kwrd">distinct</span>(DocumentPath), <span class="kwrd">COUNT</span>(*) <span class="kwrd">as</span> DocCount
    <span class="kwrd">FROM</span> [RequestUsage]
    <span class="kwrd">WHERE</span> DocumentPath <span class="kwrd">LIKE</span> <span class="str">'/Marketing%'</span>
      <span class="kwrd">AND</span> ( DocumentPath <span class="kwrd">LIKE</span> <span class="str">'%.aspx'</span>   )
<span class="kwrd">GROUP</span> <span class="kwrd">BY</span> DocumentPath      </pre>
<p><font size="2"></font></p>
<p><font size="2">This is not a lesson in SQL, but that query gives me a nice list of all .aspx documents accessed under the Marketing sub site with the corresponding hit count. To get the top 5 out of that result, you’ll end up with something like this:</font></p>
<pre class="csharpcode"><span class="kwrd">with</span> cte <span class="kwrd">as</span> (
    <span class="kwrd">SELECT</span> <span class="kwrd">distinct</span>(DocumentPath), <span class="kwrd">COUNT</span>(*) <span class="kwrd">as</span> DocCount
    <span class="kwrd">FROM</span> [RequestUsage]
    <span class="kwrd">WHERE</span> DocumentPath <span class="kwrd">LIKE</span> <span class="str">'/Marketing%'</span>
      <span class="kwrd">AND</span> ( DocumentPath <span class="kwrd">LIKE</span> <span class="str">'%.aspx'</span>   )
    <span class="kwrd">GROUP</span> <span class="kwrd">BY</span> DocumentPath )
<span class="kwrd">select</span> <span class="kwrd">top</span> 5 DocumentPath, DocCount <span class="kwrd">from</span> cte <span class="kwrd">order</span> <span class="kwrd">by</span> DocCount desc</pre>
<p>&#160;</p>
<p>So we have a query we would like to run, and then you can display the result in a web part. There are numerous ways to do that, and I won’t cover it here but I’ll show the C# code for running this query. The following code snippet is put together from my actual project, and should give you enough information to piece together a working method. Take note of how the connection string for the WSS_Logging database is retrieved:</p>
<pre class="csharpcode"><span class="rem">// run with elevated privileges</span>
SPSecurity.RunWithElevatedPrivileges(<span class="kwrd">delegate</span>()
{
    <span class="kwrd">string</span> connectionString = SPUsageApplication.DefaultApplication.UsageDatabase.DatabaseConnectionString;
    SqlConnection connection = <span class="kwrd">new</span> SqlConnection(connectionString);

    <span class="rem">// build your query</span>
    StringBuilder sb = <span class="kwrd">new</span> StringBuilder();
    sb.Append(<span class="str">&quot;with cte &quot;</span>);
    sb.Append(<span class="str">&quot;as &quot;</span>);
    sb.Append(<span class="str">&quot;( &quot;</span>);
    sb.Append(<span class="str">&quot;SELECT distinct(DocumentPath), COUNT(*) as DocCount &quot;</span>);
    sb.Append(<span class="str">&quot;FROM [RequestUsage] &quot;</span>);

    <span class="rem">// ...</span>
    <span class="rem">// add all the WHERE filters you want here</span>
    <span class="rem">// ...</span>

    sb.Append(<span class="str">&quot; GROUP BY DocumentPath &quot;</span>);
    sb.Append(<span class="str">&quot;&quot;</span>);
    sb.Append(<span class="str">&quot;) select top &quot;</span> + ItemCount + <span class="str">&quot; DocumentPath, DocCount from cte order by DocCount desc&quot;</span>);
    <span class="kwrd">string</span> sql = sb.ToString();

    SqlCommand command = <span class="kwrd">new</span> SqlCommand();
    command.Connection = connection;
    command.CommandText = <span class="kwrd">string</span>.Format(sql, SPContext.Current.Web.ServerRelativeUrl);
    command.CommandType = System.Data.CommandType.Text;
    command.Connection.Open();

    SqlDataReader reader = command.ExecuteReader();
    <span class="kwrd">while</span> (reader.Read())
    {
        <span class="rem">// access the fields, for example document name</span>
        <span class="kwrd">string</span> docName = reader[<span class="str">&quot;DocumentPath&quot;</span>].ToString().Substring(reader[<span class="str">&quot;DocumentPath&quot;</span>].ToString().LastIndexOf(<span class="str">'/'</span>) + 1);
        docName = HttpUtility.UrlDecode(docName);

        <span class="rem">// build an HTML table, add items to a list or whatever you prefer</span>
        <span class="rem">// ..</span>
    }

    <span class="rem">// close the db connection</span>
    command.Connection.Close();

}</pre>
<p><font size="2"></font></p>
<p><font size="2">The magic lies in how you build and define the filter to suit your requirements. </font></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.degree.no/2012/01/sharepoint-2010-access-site-usage-statistics/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom mapping? No, I use Automapper!</title>
		<link>http://blog.degree.no/2012/01/custom-mapping-no-i-use-automapper/</link>
		<comments>http://blog.degree.no/2012/01/custom-mapping-no-i-use-automapper/#comments</comments>
		<pubDate>Thu, 19 Jan 2012 09:52:37 +0000</pubDate>
		<dc:creator>thorhalvor</dc:creator>
				<category><![CDATA[Degree Blogg]]></category>
		<category><![CDATA[AutoMapper]]></category>
		<category><![CDATA[Mapping]]></category>

		<guid isPermaLink="false">http://blog.degree.no/?p=1896</guid>
		<description><![CDATA[In the previous posts i wrote about web applications communicating with the backend through a JSON REST API. I mentioned that I like to design specific REST methods for the given Views. That means we have to do some mapping from the objects given by the backend to the viewmodel objects. Writing a custom mapping [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://blog.degree.no/2012/01/my-favorite-web-application-architecture/">previous posts</a> i wrote about web applications communicating with the backend through a JSON REST API. I mentioned that I like to design specific REST methods for the given Views. That means we have to do some mapping from the objects given by the backend to the viewmodel objects. Writing a custom mapping class is not rocket science but it is really boring to maintain when properties are removed or introduced during its lifetime.</p>
<p>Using Automapper from <a href="http://lostechies.com/jimmybogard/">Jimmy Bogard</a> can in some best-cases reduce the code needed to only two lines of code. No matter how many properties exist in the object.</p>
<p><a href="https://github.com/AutoMapper/AutoMapper">Automapper has moved to github</a> and you can read more about it there, and it is also available as an <a href="http://nuget.org/packages/AutoMapper">nuget pacakge</a>.</p>
<p>I will not go in-depth, but let me give you some examples:</p>
<p>I have a Customer object with Firstname and Lastname. I also have an CustomerViewModel object with the same properties. To verify i have wrote the test below. Linenumber 5 and 6 are the only lines of code needed to perform the map.</p>
<p><strong>Basic</strong></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum"> 1: </span>[Test]</pre>
<pre><span class="lnum"> 2: </span><span class="kwrd">public</span> <span class="kwrd">void</span> WhenMappingCustomerToViewModel_ThenAllPropertiesShouldBeMapped()</pre>
<pre class="alt"><span class="lnum"> 3: </span>{</pre>
<pre><span class="lnum"> 4: </span>    var customer = <span class="kwrd">new</span> Customer{Firstname = <span class="str">"John"</span>,Lastname = <span class="str">"Johnsen"</span>};;</pre>
<pre class="alt"><span class="lnum"> 5: </span>    Mapper.CreateMap&lt;Customer, CustomerViewModel&gt;();</pre>
<pre><span class="lnum"> 6: </span></pre>
<pre class="alt"><span class="lnum"> 7: </span>    var customerViewModel = Mapper.Map&lt;Customer&gt;(customer);</pre>
<pre><span class="lnum"> 8: </span></pre>
<pre class="alt"><span class="lnum"> 9: </span>    Assert.AreEqual(customer.Firstname,customerViewModel.Firstname);</pre>
<pre><span class="lnum"> 10: </span>    Assert.AreEqual(customer.Lastname,customerViewModel.Lastname);</pre>
<pre class="alt"><span class="lnum"> 11: </span>}</pre>
</div>
<p><strong>AssertConfigurationIsValid</strong></p>
<p>I will give you some more advanced examples later on in this posts, I will just start telling you about Automappers method “AssertConfigurationIsValid”. A very simple test that you always should add in your tests suite:</p>
<div class="csharpcode">
<pre class="alt"><span class="lnum"> 1: </span>[Test]</pre>
<pre><span class="lnum"> 2: </span><span class="kwrd">public</span> <span class="kwrd">void</span> WhenMappingCustomerToViewModel_ConfigurationShouldBeValid()</pre>
<pre class="alt"><span class="lnum"> 3: </span>{</pre>
<pre><span class="lnum"> 4: </span>    Mapper.CreateMap&lt;Customer, CustomerViewModel&gt;();</pre>
<pre class="alt"><span class="lnum"> 5: </span>    Mapper.AssertConfigurationIsValid();</pre>
<pre><span class="lnum"> 6: </span>}</pre>
</div>
<p>AssertConfiguraitonIsValid will raise an exception if some of the properties in CustomerViewModel is NOT mapped from the Customer object. If for example only the CustomerViewModel has an Age property the given exception will be raised:</p>
<pre class="csharpcode">AutoMapper.AutoMapperConfigurationException : The following 1 properties on ns+CustomerViewModel are not mapped:
Age
Add a custom mapping expression, ignore, or rename the property on ns+Customer.</pre>
<p><strong>Lower- UpperCase does not matter</strong></p>
<p>In Javscript and Json it is a standard to have lowercase properties. So if my CustomerViewModel had properties firstname and lastname and Customer has FirstName and LastName everything will just work. I do not have to change the mappingclass.</p>
<p><strong>Flattening</strong></p>
<p><strong></strong>If the Customer has an object of type Address, and Address has the property Line1, then this value will be automatically mapped if the CustomerViewModel has an property called AddressLine1. Eks Customer.Address.Line1 will be automatically mapped to CustomerViewModel.AddressLine1.</p>
<p><strong>Projection</strong></p>
<p><strong></strong>The Customer might have a property DateOfBirth of type DateTime, but in CustomerViewModel I have a property called Birthdate of type string. And I want this string to be in the format <em>ddMMyyyy</em>. In these cases i have to add a line when calling Mapper.CreateMap()</p>
<pre class="csharpcode">Mapper.CreateMap&lt;Customer, CustomerViewModel&gt;()
    .ForMember(d =&gt; d.BirthDate, o =&gt; o.MapFrom(s =&gt; s.DateOfBirth.ToString(<span class="str">"ddMMyyyy"</span>)));</pre>
<p>&nbsp;</p>
<p><strong>Mapping a IEnumerable&lt;T&gt;</strong> (<em>added later because of specific request in email</em>)</p>
<p>The framework support mapping of IEnumerable&lt;T&gt; as long as you have created a map for T.</p>
<div class="csharpcode">
<pre class="alt"><span class="lnum"> 1: </span>[Test]</pre>
<pre><span class="lnum"> 2: </span><span class="kwrd">public</span> <span class="kwrd">void</span> WhenMappingAListOfCustomersToViewModel_ThenAListWithAllTheViewModelsShouldBeMapped()</pre>
<pre class="alt"><span class="lnum"> 3: </span>{</pre>
<pre><span class="lnum"> 4: </span>    var customer = <span class="kwrd">new</span> Customer{Firstname = <span class="str">"John"</span>,Lastname = <span class="str">"Johnsen"</span>};</pre>
<pre class="alt"><span class="lnum"> 5: </span>    var customer2 = <span class="kwrd">new</span> Customer{Firstname = <span class="str">"hans"</span>,Lastname = <span class="str">"hansen"</span>};</pre>
<pre><span class="lnum"> 6: </span>    var customList = <span class="kwrd">new</span> List&lt;Customer&gt; { customer, customer2 };</pre>
<pre class="alt"><span class="lnum"> 7: </span></pre>
<pre><span class="lnum"> 8: </span>    Mapper.CreateMap&lt;Customer, CustomerViewModel&gt;()</pre>
<pre class="alt"><span class="lnum"> 9: </span>        .ForMember(d =&gt; d.BirthDate, o =&gt; o.MapFrom(s =&gt; s.DateOfBirth.ToString(<span class="str">"ddMMyyyy"</span>)));</pre>
<pre><span class="lnum"> 10: </span></pre>
<pre class="alt"><span class="lnum"> 11: </span>    var customerViewModelList = Mapper.Map&lt;IEnumerable&lt;Customer&gt;&gt;(customList);</pre>
<pre><span class="lnum"> 12: </span></pre>
<pre class="alt"><span class="lnum"> 13: </span>    Assert.AreEqual(customList.Count(), customerViewModelList.Count());</pre>
<pre><span class="lnum"> 14: </span>}</pre>
</div>
<p>&nbsp;</p>
<p>So to summarize, Automapper is really powerful and can save you many hours of boring mapping implementation.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.degree.no/2012/01/custom-mapping-no-i-use-automapper/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>CORS = XmlHttpRequest to other servers &#8211; without JSONP</title>
		<link>http://blog.degree.no/2012/01/cors-xmlhttprequest-to-other-servers-without-jsonp/</link>
		<comments>http://blog.degree.no/2012/01/cors-xmlhttprequest-to-other-servers-without-jsonp/#comments</comments>
		<pubDate>Wed, 18 Jan 2012 14:43:04 +0000</pubDate>
		<dc:creator>Njål</dc:creator>
				<category><![CDATA[Degree Blogg]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Http 1.1]]></category>
		<category><![CDATA[IIS]]></category>
		<category><![CDATA[IIS 7.0]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JSONP]]></category>

		<guid isPermaLink="false">http://blog.degree.no/?p=1883</guid>
		<description><![CDATA[&#160; As Webstep guru Thor Halvor explained in the this excellent blogpost – there are security restrictions to prevent/limit cross domain access of XMLHttpRequest’s – the cornerstone of AJAX. Flash and silverlight has the same restrictions – and solves this by using crossdomain.xml and clientaccesspolicy.xml. These files are placed on the server you want to [...]]]></description>
			<content:encoded><![CDATA[<p>&nbsp;</p>
<p><a href="http://blog.degree.no/wp-content/uploads/image31.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px 21px 10px 10px; padding-left: 0px; padding-right: 0px; display: inline; float: left; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" align="left" src="http://blog.degree.no/wp-content/uploads/image_thumb31.png" width="260" height="200"></a>As Webstep guru Thor Halvor explained in the this <a href="http://blog.degree.no/2012/01/jsonp-in-asp-net-mvc-3/">excellent</a> blogpost – there are security restrictions to prevent/limit cross domain access of XMLHttpRequest’s – the cornerstone of AJAX. </p>
<p>Flash and silverlight has the same restrictions – and solves this by using <em>crossdomain.xml</em> and <em>clientaccesspolicy.xml</em>. These files are placed on the server you want to communicate with – and must contain * or the domain you want to contact the server from.</p>
<p>Anyways – there is a similar mechanism that XMLHttpRequest supports. This mechanism is called <strong>CORS – Cross-origin resource sharing</strong>. It is a newer(2004) and preferred alternative to JSONP – and works more or less like the xml files mentioned above. The only difference is that it isn’t implemented as a file – it’s part of the HTTP Header. This makes it a bit more difficult to set up than the others.</p>
<p>When a javascript on siteA wants to make a request to siteB – then the script first makes an initial OPTIONS request to site B – and looks at the HTTP Header it receives.</p>
<pre class="csharpcode"><strong>Access-Control-Allow-Origin: *</strong></pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>&nbsp;</p>
<p>If the value is * – then it means that XmlHttpRequests can communicate with that site – from any other server – and a regular XMLHttpRequest can be made just like you were communication with your own server. You can of course type in domain names here to prevent everybody from using your API.</p>
<p>Here’s how to configure this on an Microsoft IIS Server – Web.Config – under the &lt;configuration&gt; node</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">system.webServer</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">httpProtocol</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">customHeaders</span><span class="kwrd">&gt;</span>
       <span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">name</span><span class="kwrd">="Access-Control-Allow-Origin"</span> <span class="attr">value</span><span class="kwrd">="*"</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">customHeaders</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">httpProtocol</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">system.webServer</span><span class="kwrd">&gt;</span></pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>&nbsp;</p>
<p>So to sum it up: use CORS whenever possible, instead of hacking your way around with JSONP. You’ll have prettier code, better error handling and it’s safer to use with regard to XSS Attacks as far as I have understood. Also – CORS supports all types of HTTP requests (Get/Post/Put,Delete), while JSONP only supports Get. </p>
<p>Read more about CORS here:<br /><a href="http://my.opera.com/core/blog/2011/10/28/cors-goes-mainline">http://my.opera.com/core/blog/2011/10/28/cors-goes-mainline</a></p>
<p>A third (and the newest) alternative is <a href="http://dev.w3.org/2006/waf/UMP/">UMP</a> – I might blog more about this some other time.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.degree.no/2012/01/cors-xmlhttprequest-to-other-servers-without-jsonp/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

