<?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>Andrei Marukovich&#039;s blog &#187; .NET</title>
	<atom:link href="http://lunarfrog.com/blog/category/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://lunarfrog.com/blog</link>
	<description>Willing to learn and share</description>
	<lastBuildDate>Mon, 23 Jan 2012 18:16:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Deceptive simplicity of async and await</title>
		<link>http://lunarfrog.com/blog/2012/01/23/simplicity-of-async-and-await/</link>
		<comments>http://lunarfrog.com/blog/2012/01/23/simplicity-of-async-and-await/#comments</comments>
		<pubDate>Mon, 23 Jan 2012 06:47:50 +0000</pubDate>
		<dc:creator>Andrei Marukovich</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[async]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WinRT]]></category>

		<guid isPermaLink="false">http://lunarfrog.com/blog/?p=182</guid>
		<description><![CDATA[By introducing the new async/await keywords in C# 5 and by adding asynchronous APIs in .NET 4.5, Microsoft significantly lowered the bar for entering into the realm of the asynchronous programming. However, while presenting the new features of the upcoming .NET Framework release, answering the questions and helping to resolve the first issues I came [...]]]></description>
			<content:encoded><![CDATA[<p>By introducing the new async/await keywords in C# 5 and by adding asynchronous APIs in .NET 4.5, Microsoft significantly lowered the bar for entering into the realm of the asynchronous programming. However, while presenting the new features of the upcoming .NET Framework release, answering the questions and helping to resolve the first issues I came to realization that this bar might be set too low. </p>
<p>These new additions help us to create asynchronously running methods using the familiar synchronous development model. We don’t need to segment our code to extract the parts to be executed in a separate thread or to be a callback. We don’t have to think about the threads or tasks anymore – just add await and the rest is done automatically. </p>
<p>That’s cool – I really like these new features and I believe they can simplify our lives, but only when used properly. Current development stack (Win7/.NET Framework 4) does not enforce the asynchronous development model. The async functionality can be introduced into existing synchronous application once the developer has fully realized the advantages of the async APIs and has mastered their proper usage. </p>
<p>WinRT and .NET 4.5 are different &#8211; this stack forces us to use async model. Again, this is not a bad thing but it requires some discipline and some preliminary knowledge. Right now many developers are new to the field and are experiencing the following:</p>
<p>Developer: <em>“I want to use this function to read some data”</em><br />
Compiler: <em>“Good, but you may want to use await to get the string”</em><br />
Developer: <em>“OK, await is added. Can I get the string?”</em><br />
Compiler: <em>“Sure, just add async in the method header”</em><br />
Developer: <em>“Added. F5!”</em><br />
Developer: <em>“Hey, it does not work! Where is my string?”</em></p>
<p>The code looks good, it can be compiled but does not work. Why? Here are two most common mistakes I have seen so far.</p>
<h4>Example 1</h4>
<p><strong><em>WriteFileAsync </em></strong>function definition:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">async <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> WriteFileAsync<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> filename, <span style="color: #6666cc; font-weight: bold;">string</span> contents<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    var localFolder <span style="color: #008000;">=</span> Windows<span style="color: #008000;">.</span><span style="color: #0000FF;">Storage</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ApplicationData</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Current</span><span style="color: #008000;">.</span><span style="color: #0000FF;">LocalFolder</span><span style="color: #008000;">;</span>
    var file <span style="color: #008000;">=</span> await localFolder<span style="color: #008000;">.</span><span style="color: #0000FF;">CreateFileAsync</span><span style="color: #008000;">&#40;</span>filename, 
                           Windows<span style="color: #008000;">.</span><span style="color: #0000FF;">Storage</span><span style="color: #008000;">.</span><span style="color: #0000FF;">CreationCollisionOption</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ReplaceExisting</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    var fs <span style="color: #008000;">=</span> await file<span style="color: #008000;">.</span><span style="color: #0000FF;">OpenAsync</span><span style="color: #008000;">&#40;</span>Windows<span style="color: #008000;">.</span><span style="color: #0000FF;">Storage</span><span style="color: #008000;">.</span><span style="color: #0000FF;">FileAccessMode</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ReadWrite</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>     
    <span style="color: #008080; font-style: italic;">//...</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>And this function is called as</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">WriteFileAsync<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;FileName&quot;</span>, <span style="color: #666666;">&quot;Some Text&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>In some cases this code will work properly. But only in some – if there is a code that depends on the file content or tries to access the same file and this code is called after WriteFileAsync(), the developer will be faced with an exception or unpredicted results.</p>
<p>The problem here is that the developer use awaits for the system calls but <strong><em>WriteFileAsync</em></strong> by itself is not awaitable and any code following after <strong><em>WriteFileAsync()</em></strong> call will be executed before all the expected saving operations are done. To fix the issue the method should be modified</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">async <span style="color: #0600FF; font-weight: bold;">public</span> Task WriteFileAsync<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> filename, <span style="color: #6666cc; font-weight: bold;">string</span> contents<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">//...</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>And the function should be called as</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">await WriteFileAsync<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;FileName&quot;</span>, <span style="color: #666666;">&quot;Some Text&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h4>Example 2</h4>
<p>To implement Windows 8 Sharing contract, an application should handle <strong><em>DataTransferManager.DataRequested</em></strong> event. Below you can see an example of such a handler:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">async <span style="color: #6666cc; font-weight: bold;">void</span> DataRequestedHandler<span style="color: #008000;">&#40;</span>DataTransferManager sender, DataRequestedEventArgs args<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    _fileStream <span style="color: #008000;">=</span> await _lastSelectedFile<span style="color: #008000;">.</span><span style="color: #0000FF;">OpenAsync</span><span style="color: #008000;">&#40;</span>FileAccessMode<span style="color: #008000;">.</span><span style="color: #0000FF;">Read</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    args<span style="color: #008000;">.</span><span style="color: #0000FF;">Request</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Data</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Properties</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Title</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Data Title&quot;</span><span style="color: #008000;">;</span>
    args<span style="color: #008000;">.</span><span style="color: #0000FF;">Request</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Data</span><span style="color: #008000;">.</span><span style="color: #0000FF;">SetBitmap</span><span style="color: #008000;">&#40;</span>_fileStream<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Not surprisingly, this sample does not work either. <strong><em>DataTransferManager </em></strong>does not expect that handler is asynchronous and when the await keyword returns control to the manager, the latter sees an empty data request object, assumes that the contract is not properly implemented and will not show the application on the Share panel. The fix is easy, we just need to move <strong><em>OpenAsync </em></strong>out of the method and to remove <strong><em>async</em></strong> keyword from the header, but this example demonstrates another kind of side effects – we should be very careful with the async functions when some data are expected to be returned to the external code.</p>
<p>These mistakes look trivial but chances are they will appear quite often due to deceptive simplicity of the new syntax. Hopefully, the next version of Visual Studio and/or ReSharper will be able to detect such situations and warn about them. </p>
<p>What is your opinion? Do you see a problem here?</p>
<div class="bottomcontainerBox" style="">
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Flunarfrog.com%2Fblog%2F2012%2F01%2F23%2Fsimplicity-of-async-and-await%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></iframe></div>
			<div style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://lunarfrog.com/blog/2012/01/23/simplicity-of-async-and-await/"></g:plusone>
			</div>
			<div style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://lunarfrog.com/blog/2012/01/23/simplicity-of-async-and-await/"  data-text="Deceptive simplicity of async and await" data-count="horizontal" data-via="taggedfrog">Tweet</a>
			</div><div style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://lunarfrog.com/blog/2012/01/23/simplicity-of-async-and-await/" data-counter="right"></script></div>			
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://lunarfrog.com/blog/2012/01/23/simplicity-of-async-and-await/"></script></div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div>]]></content:encoded>
			<wfw:commentRss>http://lunarfrog.com/blog/2012/01/23/simplicity-of-async-and-await/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>My Metro Toronto UG presentation slides and samples</title>
		<link>http://lunarfrog.com/blog/2012/01/18/metrotorontoug-windows8/</link>
		<comments>http://lunarfrog.com/blog/2012/01/18/metrotorontoug-windows8/#comments</comments>
		<pubDate>Thu, 19 Jan 2012 02:17:37 +0000</pubDate>
		<dc:creator>Andrei Marukovich</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Talk]]></category>
		<category><![CDATA[Windows 8]]></category>
		<category><![CDATA[WinRT]]></category>

		<guid isPermaLink="false">http://lunarfrog.com/blog/?p=171</guid>
		<description><![CDATA[The slides and sample code from my &#8220;Windows 8 Development &#8211; Deeper Dive&#8221; presentation for Metro Toronto User Group are available for download. The samples archive contains two demo projects: MetroDemo demonstrates file system APIs and implementation of Share, File Picker and Search contracts. TilesDemo demonstrates the basic manipulations with the application tiles. Some comments [...]]]></description>
			<content:encoded><![CDATA[<p>The slides and sample code from my &#8220;Windows 8 Development &#8211; Deeper Dive&#8221; presentation for Metro Toronto User Group are <a href="http://lunarfrog.com/downloads/Talks/20120117-MetroTorontoUG-Win8.zip">available for download</a>.</p>
<div><b>The samples archive contains two demo projects:</b></div>
<ol>
<li>MetroDemo demonstrates file system APIs and implementation of Share, File Picker and Search contracts.</li>
<li>TilesDemo demonstrates the basic manipulations with the application tiles.</li>
</ol>
<p><div><b>Some comments about the MetroDemo project:</b></div>
<ul>
<li>In addition to the contracts demonstrated during the demo, the attached code demonstrates an implementation of the Search contract.</li>
<li>To see the demo in action your Pictures Library must contain at least one image tagged with some keywords. The keyword can be added in Windows Explorer by selecting the images and entering this data on the Details pane.</li>
<li>What is ObservableVector.cs: ObservableCollection class is supported by Windows 8 Developer Preview but the change notification events are ignored by WinRT UI controls. ObservableVector class is a workaround to resolve the issue – it wraps an ObservableCollection object and allows us to send the notifications to the UI. </li>
</ul>
<div>&nbsp;</div>
<div class="bottomcontainerBox" style="">
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Flunarfrog.com%2Fblog%2F2012%2F01%2F18%2Fmetrotorontoug-windows8%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></iframe></div>
			<div style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://lunarfrog.com/blog/2012/01/18/metrotorontoug-windows8/"></g:plusone>
			</div>
			<div style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://lunarfrog.com/blog/2012/01/18/metrotorontoug-windows8/"  data-text="My Metro Toronto UG presentation slides and samples" data-count="horizontal" data-via="taggedfrog">Tweet</a>
			</div><div style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://lunarfrog.com/blog/2012/01/18/metrotorontoug-windows8/" data-counter="right"></script></div>			
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://lunarfrog.com/blog/2012/01/18/metrotorontoug-windows8/"></script></div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div>]]></content:encoded>
			<wfw:commentRss>http://lunarfrog.com/blog/2012/01/18/metrotorontoug-windows8/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>On deploying ASP.NET MVC site as a desktop application</title>
		<link>http://lunarfrog.com/blog/2011/12/09/aspnetsite-as-desktop-app/</link>
		<comments>http://lunarfrog.com/blog/2011/12/09/aspnetsite-as-desktop-app/#comments</comments>
		<pubDate>Fri, 09 Dec 2011 16:52:29 +0000</pubDate>
		<dc:creator>Andrei Marukovich</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Fileversum]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://lunarfrog.com/blog/?p=147</guid>
		<description><![CDATA[Sometimes you may find you in a situation when you have an ASP.NET web application and want to deploy it to a desktop PC. For example, for one of my projects I have the following requirements: Simple installation on any Windows-based PC. Installation and configuration should not require knowledge of the Web technologies. Ability to [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes you may find you in a situation when you have an ASP.NET web application and want to deploy it to a desktop PC. For example, for one of my projects I have the following requirements:</p>
<ul>
<li>Simple installation on any Windows-based PC. Installation and configuration should not require knowledge of the Web technologies.</li>
<li>Ability to start, stop and configure the Web application from a custom desktop application.</li>
<li>The Web application should be accessible for a local user and all the network users.</li>
<li>In the same time it should be a regular ASP.NET application that can be deployed as a hosted solution.</li>
</ul>
<p>It is clear that such solution will be composed from 3 main components: Web application, control application (in my case it is based on .NET/WPF), Web server. And the main question is “What should I use as a server?” To satisfy the project’s requirements, the server should have the following characteristics:</p>
<ul>
<li>Easily redistributable</li>
<li>Configurable via API, configuration files or command line</li>
<li>Should be controllable externally (Start/Stop via API, command line, etc.)</li>
<li>Network support</li>
</ul>
<p>&nbsp;</p>
<h4>CassiniDev</h4>
<p>Already having an experience with CassiniDev server as a solution for the integration tests execution, I tried this one first. CassiniDev is an open-source project that includes a standalone Wev server with GUI and a library. The library, <strong><em>CassiniDev4-Lib.dll</em></strong>, contains <strong><em>CassiniDevServer </em></strong>class – an in-process Web server implementation.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">_server <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> CassiniDevServer<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
_server<span style="color: #008000;">.</span><span style="color: #0000FF;">StartServer</span><span style="color: #008000;">&#40;</span>@“\path\to\web\content”<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Basically, that’s it &#8211; with two lines of code you have a server that hosts your ASP.NET application. At first look this is what is required: </p>
<ul>
<li>there is no need to install anything – the server is a part of the control application</li>
<li>CassiniDevServer can be easily configured and controlled</li>
</ul>
<p>But there are some cavities and probably the main one is performance. CassiniDev handles all the HTTP requests sequentially, in one thread. It is acceptable for testing but is not practical in production. </p>
<p>Another issue that kicks CassiniDev out of completion is an auto-shutdown after 60-seconds of idleness – it simply stops to handle any incoming requests.</p>
<h4>IIS Express</h4>
<p>IIS Express is a lightweight version of IIS. It runs as a separate process like full version of IIS web server, but this process is executed under the user’s account. IIS Express is a standalone application and can be started/stopped using a command line, unlike service-based full IIS.</p>
<p>Theoretically IIS Express is xcopy-deployable, but EULA states that IIS Express can only be redistributed using an official installer package. That means if you want to use IIS Express, it should be added as a prerequisite to your installer and will be installed as separated product.</p>
<p>IIS Express uses the same configuration mechanism as full IIS. Probably the easiest way to host the site on IIE Express, is to create own <strong><em>applicationhost.config</em></strong>, deploy it on the target system and use it to start the server:</p>
<p><em><strong>&#8220;C:\Program Files\IIS Express\iisexpress.exe&#8221; /config:D:\Fileversum\config\applicationhost.config</strong></em> </p>
<p>Even IIS Express is installed into the system it will not be started automatically on the Windows start. You have to do it by yourself by creating some kind of launcher or incorporating this functionality into the control application, to be able to start/stop the server on-demand.</p>
<p>By default IIS Express does not require elevated permissions, but in the same time it default configuration does not support network requests and port 80. You need the administrative privileges to unlock these features. <a href="http://www.hanselman.com/blog/WorkingWithSSLAtDevelopmentTimeIsEasierWithIISExpress.aspx">The post by Scott Hanselman</a> describes the required manipulations, but in short you need to do the following:</p>
<ul>
<li>Configure applicationhost.config to bind your site with the public IP address.</li>
<li>Allow incoming connections and add a new Windows Firewall rule using <strong><em>netsh </em></strong>utility.</li>
</ul>
<p>Note that <strong><em>netsh </em></strong>does not exist in Windows XP and <strong><em>httpcfg </em></strong>should be used instead. That means an additional complexity for the installation script.</p>
<h4>UltiDev Web Server Pro</h4>
<p>UltiDev Web Server Pro is a successor for UltiDev Cassini Web Server, a freeware redistributable Web server. The product is relatively new, but it is in active development and demonstrates a good stability, performance and a reach feature set.</p>
<p>Like IIS Express, UWS is a standalone out-of-process Web server. It runs as a service, includes GUI frontend but also provides an API and the command line tools. UltiDev Server cannot be privately deployed, you have to install it. Fortunately the server redistributable packages for InstallShield, Advanced Installer and VS bootstrapper are available. </p>
<p>If you prefer to register your site during the installation, UWS provides a command line utility that can be used for this propose. If you need more control under the site’s lifecycle, a .NET-based API exposed from <strong><em>UWS.Configuration.dll</em></strong> library might be an option. Below you can see a sample code demonstrating site registration:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var app <span style="color: #008000;">=</span> Metabase<span style="color: #008000;">.</span><span style="color: #0000FF;">GetWebAppEntry</span><span style="color: #008000;">&#40;</span>ApplicationGUID, <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
app<span style="color: #008000;">.</span><span style="color: #0000FF;">VirtualDirectory</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;/Fileversum&quot;</span><span style="color: #008000;">;</span>
app<span style="color: #008000;">.</span><span style="color: #0000FF;">PhysicalDirectory</span> <span style="color: #008000;">=</span> @“\path\to\web\content”<span style="color: #008000;">;</span>
app<span style="color: #008000;">.</span><span style="color: #0000FF;">ApplicationName</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Fileversum&quot;</span><span style="color: #008000;">;</span>
app<span style="color: #008000;">.</span><span style="color: #0000FF;">AppType</span> <span style="color: #008000;">=</span> ApplicationType<span style="color: #008000;">.</span><span style="color: #0000FF;">AspNetOrStaticHtml</span><span style="color: #008000;">;</span>
app<span style="color: #008000;">.</span><span style="color: #0000FF;">ListenAddresses</span><span style="color: #008000;">.</span><span style="color: #0000FF;">AddRange</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#123;</span> <span style="color: #008000;">new</span> ListenAddress<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">80</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
Metabase<span style="color: #008000;">.</span><span style="color: #0000FF;">RegisterApplication</span><span style="color: #008000;">&#40;</span>RuntimeVersion<span style="color: #008000;">.</span><span style="color: #0000FF;">AspNet_4</span>, <span style="color: #0600FF; font-weight: bold;">true</span>, app<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>And un-registration:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Metabase<span style="color: #008000;">.</span><span style="color: #0000FF;">UnregisterApplication</span><span style="color: #008000;">&#40;</span>ApplicationGUID<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Both operations (registration and un-registration) require the administrative rights. So if this code is incorporated into the control application, it must be able to request the elevated partitions.</p>
<p>As soon as the site is registered, it will be available for the local and the network users. No additional actions are required to start the server or site after Windows reboot.</p>
<p>Additionally, to simplify the site deployment, UWS supports auto detection of the available ports.</p>
<div class="bottomcontainerBox" style="">
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Flunarfrog.com%2Fblog%2F2011%2F12%2F09%2Faspnetsite-as-desktop-app%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></iframe></div>
			<div style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://lunarfrog.com/blog/2011/12/09/aspnetsite-as-desktop-app/"></g:plusone>
			</div>
			<div style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://lunarfrog.com/blog/2011/12/09/aspnetsite-as-desktop-app/"  data-text="On deploying ASP.NET MVC site as a desktop application" data-count="horizontal" data-via="taggedfrog">Tweet</a>
			</div><div style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://lunarfrog.com/blog/2011/12/09/aspnetsite-as-desktop-app/" data-counter="right"></script></div>			
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://lunarfrog.com/blog/2011/12/09/aspnetsite-as-desktop-app/"></script></div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div>]]></content:encoded>
			<wfw:commentRss>http://lunarfrog.com/blog/2011/12/09/aspnetsite-as-desktop-app/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>My CTTDNUG presentation slides and samples</title>
		<link>http://lunarfrog.com/blog/2011/12/01/cttdnug-presentation/</link>
		<comments>http://lunarfrog.com/blog/2011/12/01/cttdnug-presentation/#comments</comments>
		<pubDate>Fri, 02 Dec 2011 04:08:39 +0000</pubDate>
		<dc:creator>Andrei Marukovich</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Talk]]></category>
		<category><![CDATA[Windows 8]]></category>
		<category><![CDATA[WinRT]]></category>

		<guid isPermaLink="false">http://lunarfrog.com/blog/?p=141</guid>
		<description><![CDATA[I published the slides and sample code from my presentation about Windows 8 at Canada&#8217;s Technology Triangle .NET User Group meeting. The slides are also available on Slideshare. Feel free to contact me if you want to discuss them. Tweet]]></description>
			<content:encoded><![CDATA[<p>I published the <a href="http://lunarfrog.com/downloads/Talks/20111130-CTTDNUG-Win8.zip">slides and sample code</a> from my presentation about Windows 8 at Canada&#8217;s Technology Triangle .NET User Group meeting. The slides are also available on <a href="http://www.slideshare.net/LunarFrog/a-developers-view-of-windows-8">Slideshare</a>.</p>
<p>Feel free to contact me if you want to discuss them.</p>
<div class="bottomcontainerBox" style="">
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Flunarfrog.com%2Fblog%2F2011%2F12%2F01%2Fcttdnug-presentation%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></iframe></div>
			<div style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://lunarfrog.com/blog/2011/12/01/cttdnug-presentation/"></g:plusone>
			</div>
			<div style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://lunarfrog.com/blog/2011/12/01/cttdnug-presentation/"  data-text="My CTTDNUG presentation slides and samples" data-count="horizontal" data-via="taggedfrog">Tweet</a>
			</div><div style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://lunarfrog.com/blog/2011/12/01/cttdnug-presentation/" data-counter="right"></script></div>			
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://lunarfrog.com/blog/2011/12/01/cttdnug-presentation/"></script></div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div>]]></content:encoded>
			<wfw:commentRss>http://lunarfrog.com/blog/2011/12/01/cttdnug-presentation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>TechDays Canada 2010: My talk on Wednesday in Toronto</title>
		<link>http://lunarfrog.com/blog/2010/10/22/techdays-2010-talk/</link>
		<comments>http://lunarfrog.com/blog/2010/10/22/techdays-2010-talk/#comments</comments>
		<pubDate>Fri, 22 Oct 2010 23:52:31 +0000</pubDate>
		<dc:creator>Andrei Marukovich</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Talk]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://lunarfrog.com/blog/?p=27</guid>
		<description><![CDATA[Updated 2011/03/30: CTTDNUG presentation source code Updated 2010/11/03: Presentation slides, demo project This week, on Wednesday the 27th and Thursday the 28th of October, the TechDays Canada 2010 will take place in Toronto and I will be presenting a session on Wednesday the 27th at 2:20pm. The talk is called “Some Behind-the-Scenes Details about WPF [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Updated 2011/03/30:</strong> <a href="http://lunarfrog.com/downloads/blog/cttdnug_demo.zip">CTTDNUG presentation source code</a></p>
<p><strong>Updated 2010/11/03:</strong> <a href="http://lunarfrog.com/downloads/blog/TechDays2010LFT340.zip">Presentation slides</a>, <a title="demo project" href="http://lunarfrog.com/downloads/blog/Demo.zip">demo project</a></p>
<p>This week, on Wednesday the 27<sup>th</sup> and Thursday the 28<sup>th</sup> of October, the TechDays Canada 2010 will take place in Toronto and I will be presenting a session on Wednesday the 27<sup>th</sup> at 2:20pm.</p>
<p>The talk is called <em><strong>“Some Behind-the-Scenes Details about WPF MVVM Frameworks”</strong></em> and is about the Model-View-ViewModel pattern implementation details. Here&#8217;s the abstract:</p>
<p><em>Currently MVVM is a pattern of choice among WPF community but as any pattern, it allows different interpretations and implementations. As a result, we have multiple MVVM frameworks and a variety of ways to solve the common pattern-related problems. Some of the frameworks are lightweight, some are heavy but usually every of them will miss at least one nice feature you want to have. This session proposes to explore different approaches used by the frameworks to perform the common tasks. If you want to have a MVVM foundation fully satisfy your project needs, this session can be a good start point for you. During the session, we will talk about different ways to bind the presentation layers, to discover ViewModels and make them blendable.</em></p>
<p>Below you can find a list of the described patterns with the names of the framework where they are used:</p>
<p><strong> </strong><strong>1. ViewModelLocator</strong></p>
<p style="padding-left: 30px;"><a href="http://mvvmlight.codeplex.com/">MVVM Light Toolkit</a> (<a href="http://www.galasoft.ch/mvvm/getstarted/">Laurent Bugnion</a>)</p>
<p><strong>2.</strong><strong> Attached   Behaviors and MVVM</strong></p>
<p style="padding-left: 30px;"><a href="http://nroute.codeplex.com/">nRoute</a><strong> </strong>(<a href="http://www.orktane.com/Blog/">Rishi</a>)<strong> </strong></p>
<p style="padding-left: 30px;"><a href="http://mvvmhelpers.codeplex.com/">JulMar MVVM Helpers + Behaviors</a> (<a href="http://www.julmar.com/blog/mark/">Mark Smith</a>)</p>
<p><strong>3. </strong><strong>Using   attached properties for ViewModel instantiation</strong></p>
<p style="padding-left: 30px;"><a href="http://mefedmvvm.codeplex.com/">MEFedMVVM</a> (<a href="http://marlongrech.wordpress.com/">Marlon Grech</a>)</p>
<p style="padding-left: 30px;"><a href="http://cinch.codeplex.com/">Cinch</a> (<a href="http://sachabarber.net/">Sacha Barber</a>)</p>
<p><strong>4. Conventional   binding, handling   View lifecycle events from ViewModel</strong></p>
<p style="padding-left: 30px;"><a href="http://caliburnmicro.codeplex.com/">Caliburn.Micro</a> (<a href="http://devlicio.us/blogs/rob_eisenberg/">Rob Eisenberg</a>)</p>
<p><strong>5. </strong><strong>Handling   dialogs as services</strong></p>
<p style="padding-left: 30px;"><a href="http://wpfonyx.codeplex.com/">Onyx</a> (<a href="http://digitaltapestry.wordpress.com/">William E. Kempf</a>)</p>
<p><strong>6. </strong><strong>ViewModelBase   optimizations</strong></p>
<p style="padding-left: 30px;"><a href="http://viewmodelsupport.codeplex.com/">ViewModelSupport</a> (<a href="http://houseofbilz.com/archives/2010/05/08/adventures-in-mvvm-my-viewmodel-base/">Brian Genisio</a>)</p>
<p style="padding-left: 30px;">
<p><strong>Additional Resources</strong></p>
<ul>
<li><a href="http://www.japf.fr/silverlight/mvvm/index.html">MVVM Frameworks Explorer</a> &#8211; MVVM frameworks comparison (Silverlight app)</li>
<li><a href="http://www.paulstovell.com/mvvm-instantiation-approaches">List of basic instantiation approaches</a></li>
<li><a href="http://groups.google.com/group/wpf-disciples">WPF Disciples</a> &#8211; Group for all WPF lovers, to share knowledge on WPF</li>
<li><a href="http://live.visitmix.com/MIX10/Sessions/EX15">Build Your Own MVVM Framework</a> by Rob Eisenberg, MIX10 (video)</li>
</ul>
<ul>
<li><a href="http://lunarfrog.com/downloads/blog/TechDays2010LFT340.zip">Presentation slides</a></li>
<li><a title="demo project" href="http://lunarfrog.com/downloads/blog/Demo.zip">Demo project</a></li>
</ul>
<div class="bottomcontainerBox" style="">
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Flunarfrog.com%2Fblog%2F2010%2F10%2F22%2Ftechdays-2010-talk%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></iframe></div>
			<div style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://lunarfrog.com/blog/2010/10/22/techdays-2010-talk/"></g:plusone>
			</div>
			<div style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://lunarfrog.com/blog/2010/10/22/techdays-2010-talk/"  data-text="TechDays Canada 2010: My talk on Wednesday in Toronto" data-count="horizontal" data-via="taggedfrog">Tweet</a>
			</div><div style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://lunarfrog.com/blog/2010/10/22/techdays-2010-talk/" data-counter="right"></script></div>			
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://lunarfrog.com/blog/2010/10/22/techdays-2010-talk/"></script></div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div>]]></content:encoded>
			<wfw:commentRss>http://lunarfrog.com/blog/2010/10/22/techdays-2010-talk/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Паттерн Dependency Injection и введение в Ninject &#8211; DI фреймворк для .NET</title>
		<link>http://lunarfrog.com/blog/2009/11/30/%d0%bf%d0%b0%d1%82%d1%82%d0%b5%d1%80%d0%bd-dependency-injection-%d0%b8-%d0%b2%d0%b2%d0%b5%d0%b4%d0%b5%d0%bd%d0%b8%d0%b5-%d0%b2-ninject-di-%d1%84%d1%80%d0%b5%d0%b9%d0%bc%d0%b2%d0%be%d1%80%d0%ba/</link>
		<comments>http://lunarfrog.com/blog/2009/11/30/%d0%bf%d0%b0%d1%82%d1%82%d0%b5%d1%80%d0%bd-dependency-injection-%d0%b8-%d0%b2%d0%b2%d0%b5%d0%b4%d0%b5%d0%bd%d0%b8%d0%b5-%d0%b2-ninject-di-%d1%84%d1%80%d0%b5%d0%b9%d0%bc%d0%b2%d0%be%d1%80%d0%ba/#comments</comments>
		<pubDate>Tue, 01 Dec 2009 02:53:25 +0000</pubDate>
		<dc:creator>Andrei Marukovich</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://lunarfrog.com/blogs/?p=17</guid>
		<description><![CDATA[В статье показывается пример тесно связанных классов, проводиться их рефакторинг с реализацией паттерна Dependency Injection (внедрение зависимости) и демонстрируется применение фреймворка Ninject, облегчающего внедрение зависимостей. public class Engine &#123; public double GetSize&#40;&#41; &#123; return 2.5; // in liters &#125; &#125; &#160; public class Car &#123; private readonly Engine _engine; &#160; public Car&#40;&#41; &#123; _engine = [...]]]></description>
			<content:encoded><![CDATA[<p>В статье показывается пример тесно связанных классов, проводиться их рефакторинг с реализацией паттерна Dependency Injection (внедрение зависимости) и демонстрируется применение фреймворка Ninject, облегчающего внедрение зависимостей.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Engine
<span style="color: #008000;">&#123;</span>
   <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">double</span> GetSize<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
   <span style="color: #008000;">&#123;</span>
      <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #FF0000;">2.5</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// in liters</span>
   <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Car
<span style="color: #008000;">&#123;</span>
   <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> Engine _engine<span style="color: #008000;">;</span>
&nbsp;
   <span style="color: #0600FF; font-weight: bold;">public</span> Car<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
   <span style="color: #008000;">&#123;</span>
      _engine <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Engine<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #008000;">&#125;</span>
&nbsp;
   <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> GetDescription<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
   <span style="color: #008000;">&#123;</span>
      Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>“Engine size<span style="color: #008000;">:</span> <span style="color: #008000;">&#123;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&#125;</span>”, _engine<span style="color: #008000;">.</span><span style="color: #0000FF;">GetSize</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #6666cc; font-weight: bold;">class</span> Program
<span style="color: #008000;">&#123;</span>
   <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
   <span style="color: #008000;">&#123;</span>
      Car car <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Car<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
      car<span style="color: #008000;">.</span><span style="color: #0000FF;">GetDescription</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Каждый из нас писал подобный код хотя бы раз в жизни. А те, в чьи обязанности входит проверка кода начинающих программистов, могут видеть это достаточно часто. С синтаксической и логической точек зрения в нем нет ничего криминального. Код отлично отработает, выполнив все от него ожидаемое, и в нем абсолютно ничего не надо трогать, если это часть программы состоящей из пяти классов. Вопросы возникают, когда такой код появляется в реальном проекте, насчитывающем десятки классов, имеющем длинный жизненный цикл и большую вероятность изменения пользовательских требований, способа хранения данных или поддерживаемого оборудования.</p>
<p>Чем же он плох? Если кратко, то зависимостью конкретного класса Car от конкретного класса Engine. Представим, что конструктор класса Engine измениться – в этом случае придется менять и Car. Или, к примеру, появиться еще один двигатель. И что бы машина смогла его использовать, опять-таки, понадобиться изменить класс Car. Кроме того, подобная жестко запрограммированная  зависимость снижает тестируемость классов – класс Car невозможно протестировать отдельно от Engine или заменить Engine на ложный объект, для симуляции непредвиденных обстоятельств.</p>
<p>Что же можно сделать для улучшения кода? Первое – ввести интерфейс IEngine, который будет реализовываться классом Engine.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">interface</span> IEngine
<span style="color: #008000;">&#123;</span>
   <span style="color: #6666cc; font-weight: bold;">double</span> GetSize<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Engine <span style="color: #008000;">:</span> IEngine
<span style="color: #008000;">&#123;</span>
   <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">double</span> GetSize<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
   <span style="color: #008000;">&#123;</span>
      <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #FF0000;">2.5</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// in liters</span>
   <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Далее, изменить класс Car, что бы вместо класса Engine в нем использовался интерфейс IEngine. И второе, не менее важное изменение – класс Car не должен создавать двигатель сам, теперь конструктор получает ссылку на объект, реализующий интерфейс IEngine.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Car
<span style="color: #008000;">&#123;</span>
   <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> IEngine _engine<span style="color: #008000;">;</span>
&nbsp;
   <span style="color: #0600FF; font-weight: bold;">public</span> Car<span style="color: #008000;">&#40;</span>IEngine engine<span style="color: #008000;">&#41;</span>
   <span style="color: #008000;">&#123;</span>
      _engine <span style="color: #008000;">=</span> engine<span style="color: #008000;">;</span>
   <span style="color: #008000;">&#125;</span>
&nbsp;
   <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> GetDescription<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
   <span style="color: #008000;">&#123;</span>
      Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>“Engine size<span style="color: #008000;">:</span> <span style="color: #008000;">&#123;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&#125;</span>L”, _engine<span style="color: #008000;">.</span><span style="color: #0000FF;">GetSize</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>И последнее, что необходимо сделать – это изменить функцию Main.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">class</span> Program
<span style="color: #008000;">&#123;</span>
   <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
   <span style="color: #008000;">&#123;</span>
      IEngine engine <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Engine<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
      Car car <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Car<span style="color: #008000;">&#40;</span>engine<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      car<span style="color: #008000;">.</span><span style="color: #0000FF;">GetDescription</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Получившееся в результате решение легче расширяемо, более тестируемо и является примером реализации паттерна Dependency Injection (внедрение зависимости) – зависимость машина-двигатель конфигурируется не внутри класса, а двигатель, созданный вне класса, внедряется в него.</p>
<p>Минус такого решения – потерялась простота создания нового экземпляра класса Car. Представьте, если в программе достаточно много подобных зависимостей, их все придется создавать вручную снова и снова. Поэтому, мы пойдем дальше и посмотрим, как можно облегчить жизнь используя Ninject, фреймворк для автоматического внедрения зависимостей.</p>
<h3>Ninject</h3>
<p>Основную идею использования DI фреймворков для создания объектов можно описать так: &#8220;Мне нужен объект класса A, создай его, и меня не интересует, что и как ты для этого будешь делать&#8221;. И вот как будет выглядеть создание машины с использованием Ninject:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">class</span> Program
<span style="color: #008000;">&#123;</span>
   <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
   <span style="color: #008000;">&#123;</span>
      <span style="color: #008080; font-style: italic;">// Ninject Initialization</span>
      IKernel ninjectKernel <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StandardKernel<span style="color: #008000;">&#40;</span> <span style="color: #008000;">new</span> MyConfigModule<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      <span style="color: #008080; font-style: italic;">// Using Car</span>
      Car car <span style="color: #008000;">=</span> ninjectKernel<span style="color: #008000;">.</span><span style="color: #0000FF;">Get</span><span style="color: #008000;">&lt;</span>Car<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
      car<span style="color: #008000;">.</span><span style="color: #0000FF;">GetDescription</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Что такое ninjectKernel станет понятно чуть позже, а сейчас стоит обратить внимание на отсутствие любого упоминания IEngine или Engine. Благодаря предварительной конфигурации Ninject знает, что машине требуется двигатель и когда его просят создать новый экземпляр класса Car, он самостоятельно создает Engine и передает его в конструктор Car. Таким образом, все что требуется – это запросить класс. Все зависимости, необходимые для его создания или работы, DI фреймворк разрешит самостоятельно. Если, конечно, он был предварительно правильно сконфигурирован.</p>
<p>Ninject можно или загрузить с сайта <a rel="nofollow" href="http://ninject.org">Ninject.org</a> в виде стабильной версии, или взять в виде актуальных исходных файлов из репозитория. Я рекомендую воспользоваться вторым способом, так как версия, находящаяся в репозитории, поддерживает несколько новых возможностей, в том числе код для интеграции с ASP.NET MVC.</p>
<p>Для начала работы с Ninject, в проект необходимо добавить ссылку на сборку <em>Ninject.Core.dll</em>, реализующую базовые возможности фреймворка. Второй шаг – конфигурирование. К сожалению, Dependency Injection – это не магия и что бы Ninject знал, каким образом разрешать зависимости, он должен быть проинструктирован. Для нашей программы необходимы только две инструкции:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Bind<span style="color: #008000;">&lt;</span>IEngine<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">To</span><span style="color: #008000;">&lt;</span>Engine<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
Bind<span style="color: #008000;">&lt;</span>Car<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ToSelf</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>В то время как многие DI фреймворки полагаются на конфигурационные XML файлы, Ninject имеет простой, интуитивно понятный API для задания зависимостей, использующий привычный синтаксис языка и позволяющий задействовать все возможности IDE.</p>
<p>Первая инструкция связывает интерфейс IEngine с классом Engine таким образом, что всякий раз, когда Ninject обнаружит необходимость в объекте типа IEngine, то будет создан объект Engine. Вторая инструкция описывает желаемое поведение при запросе на создание экземпляра класса Car – необходимо создать этот экземпляр, все просто. На самом деле, вторая инструкция не обязательна – такое поведение реализуется фреймворком по умолчанию. При необходимости автосвязывание классов можно и отключить, и настраивать все самому.</p>
<p>Теперь возникает вопрос – а где выполнять конфигурирование? Конфигурирование выполняется в виртуальном методе Load класса, реализующего интерфейс IModule. Проще всего будет наследовать такой класс от класса StandardModule.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> MyConfigModule <span style="color: #008000;">:</span> StandardModule
<span style="color: #008000;">&#123;</span>
   <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">override</span> <span style="color: #6666cc; font-weight: bold;">void</span> Load<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
   <span style="color: #008000;">&#123;</span>
      Bind<span style="color: #008000;">&lt;</span>Car<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ToSelf</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
      Bind<span style="color: #008000;">&lt;</span>IEngine<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">To</span><span style="color: #008000;">&lt;</span>Engine<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>При желании, может быть создано несколько таких модулей, например для разделения конфигураций для различных частей программы. Далее эти модули используются для создания контейнера, который и будет выполнять для нас всю грязную работу.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">IKernel kernel <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StandardKernel<span style="color: #008000;">&#40;</span>cfg1, cfg2, …<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Информации, приведенной выше, достаточно для начала работы с Ninject, но недостаточно для реализации более сложных сценариев. Такие возможности как контекстно-зависимое связывание, связывание, основанное на соглашениях, контроль времени жизни, существенно расширяют возможности применения Ninject и будут описаны в следующей статье.</p>
<div class="bottomcontainerBox" style="">
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Flunarfrog.com%2Fblog%2F2009%2F11%2F30%2F%25d0%25bf%25d0%25b0%25d1%2582%25d1%2582%25d0%25b5%25d1%2580%25d0%25bd-dependency-injection-%25d0%25b8-%25d0%25b2%25d0%25b2%25d0%25b5%25d0%25b4%25d0%25b5%25d0%25bd%25d0%25b8%25d0%25b5-%25d0%25b2-ninject-di-%25d1%2584%25d1%2580%25d0%25b5%25d0%25b9%25d0%25bc%25d0%25b2%25d0%25be%25d1%2580%25d0%25ba%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></iframe></div>
			<div style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://lunarfrog.com/blog/2009/11/30/%d0%bf%d0%b0%d1%82%d1%82%d0%b5%d1%80%d0%bd-dependency-injection-%d0%b8-%d0%b2%d0%b2%d0%b5%d0%b4%d0%b5%d0%bd%d0%b8%d0%b5-%d0%b2-ninject-di-%d1%84%d1%80%d0%b5%d0%b9%d0%bc%d0%b2%d0%be%d1%80%d0%ba/"></g:plusone>
			</div>
			<div style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://lunarfrog.com/blog/2009/11/30/%d0%bf%d0%b0%d1%82%d1%82%d0%b5%d1%80%d0%bd-dependency-injection-%d0%b8-%d0%b2%d0%b2%d0%b5%d0%b4%d0%b5%d0%bd%d0%b8%d0%b5-%d0%b2-ninject-di-%d1%84%d1%80%d0%b5%d0%b9%d0%bc%d0%b2%d0%be%d1%80%d0%ba/"  data-text="Паттерн Dependency Injection и введение в Ninject &#8211; DI фреймворк для .NET" data-count="horizontal" data-via="taggedfrog">Tweet</a>
			</div><div style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://lunarfrog.com/blog/2009/11/30/%d0%bf%d0%b0%d1%82%d1%82%d0%b5%d1%80%d0%bd-dependency-injection-%d0%b8-%d0%b2%d0%b2%d0%b5%d0%b4%d0%b5%d0%bd%d0%b8%d0%b5-%d0%b2-ninject-di-%d1%84%d1%80%d0%b5%d0%b9%d0%bc%d0%b2%d0%be%d1%80%d0%ba/" data-counter="right"></script></div>			
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://lunarfrog.com/blog/2009/11/30/%d0%bf%d0%b0%d1%82%d1%82%d0%b5%d1%80%d0%bd-dependency-injection-%d0%b8-%d0%b2%d0%b2%d0%b5%d0%b4%d0%b5%d0%bd%d0%b8%d0%b5-%d0%b2-ninject-di-%d1%84%d1%80%d0%b5%d0%b9%d0%bc%d0%b2%d0%be%d1%80%d0%ba/"></script></div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div>]]></content:encoded>
			<wfw:commentRss>http://lunarfrog.com/blog/2009/11/30/%d0%bf%d0%b0%d1%82%d1%82%d0%b5%d1%80%d0%bd-dependency-injection-%d0%b8-%d0%b2%d0%b2%d0%b5%d0%b4%d0%b5%d0%bd%d0%b8%d0%b5-%d0%b2-ninject-di-%d1%84%d1%80%d0%b5%d0%b9%d0%bc%d0%b2%d0%be%d1%80%d0%ba/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Библиотека Code Contracts: контрактное программирование под .NET</title>
		<link>http://lunarfrog.com/blog/2009/11/30/%d0%b1%d0%b8%d0%b1%d0%bb%d0%b8%d0%be%d1%82%d0%b5%d0%ba%d0%b0-code-contracts-%d0%ba%d0%be%d0%bd%d1%82%d1%80%d0%b0%d0%ba%d1%82%d0%bd%d0%be%d0%b5-%d0%bf%d1%80%d0%be%d0%b3%d1%80%d0%b0%d0%bc%d0%bc%d0%b8/</link>
		<comments>http://lunarfrog.com/blog/2009/11/30/%d0%b1%d0%b8%d0%b1%d0%bb%d0%b8%d0%be%d1%82%d0%b5%d0%ba%d0%b0-code-contracts-%d0%ba%d0%be%d0%bd%d1%82%d1%80%d0%b0%d0%ba%d1%82%d0%bd%d0%be%d0%b5-%d0%bf%d1%80%d0%be%d0%b3%d1%80%d0%b0%d0%bc%d0%bc%d0%b8/#comments</comments>
		<pubDate>Tue, 01 Dec 2009 02:50:18 +0000</pubDate>
		<dc:creator>Andrei Marukovich</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://lunarfrog.com/blogs/?p=11</guid>
		<description><![CDATA[Code Contracts library for .NET 3.5: introduction in Russian. Code Contracts provide a language-agnostic way to express coding assumptions in .NET programs. The contracts take the form of pre-conditions, post-conditions, and object invariants and act as checked documentation of your external and internal APIs. Контрактное программирование &#8211; это метод проектирования программ, предполагающий четкое специфицирование интерфейсов [...]]]></description>
			<content:encoded><![CDATA[<p>Code Contracts library for .NET 3.5: introduction in Russian. Code Contracts provide a language-agnostic way to express coding assumptions in .NET programs. The contracts take the form of pre-conditions, post-conditions, and object invariants and act as checked documentation of your external and internal APIs.</p>
<p>Контрактное программирование &#8211; это метод проектирования программ, предполагающий четкое специфицирование интерфейсов и описание обязанностей компонентов системы при взаимодействии друг с другом.</p>
<p>Обычно, контракт включает три основные группы элементов:</p>
<ul class="arrows">
<li>предусловия &#8211; обязательства, которые должны быть выполнены вызывающей стороной перед вызовом метода</li>
<li>постусловия &#8211; обязательства, гарантирующиеся вызываемым методом</li>
<li>инварианты класса &#8211; обязательства, что свойства класса будут удовлетворять определенным требованиям. Например, инвариантом для класса PositiveNumber, может быть утверждение, что хранимое число всегда больше или равно 0.</li>
</ul>
<p>Таким образом, этот метод обеспечивает уверенность вызываемого компонента, что он получит только надлежащие входные данные, а результат, возвращенный вызывающему компоненту, будет корректным.</p>
<p>На PDC2008 было анонсировано появление в .NET 4.0 набора функций реализующих поддержку контрактного программирования и входящих в новое пространство имен <em>System.Diagnostics.Contracts</em>. На практике это будет выглядеть так:</p>
<pre class="code"><span class="op">class</span> Account
{
   <span class="op">public double</span> Balance { <span class="op">get</span>; <span class="op">set</span>; }

   <span class="op">public void</span> Deposit(<span class="op">double</span> amount)
   {
      Contract.Requires(amount &gt;=0);

      Balance += amount;
   }

   <span class="op">public void</span> Withdraw(<span class="op">double</span> amount)
   {
      Contract.Requires(amount &gt; 0);
      Contract.Requires(amount &lt;= Balance);

      Balance -= amount;
   }

   <span class="op">public</span> Account Transfer()
   {
      Contract.Ensures(Balance == 0);
      Contract.Ensures(Contract.Result&lt;Account&gt;() != <span class="op">null</span>);

      Account newAccount = <span class="op">new</span> Account() {Balance = <span class="op">this</span>.Balance};
      Balance = 0;
      <span class="op">return</span> newAccount;
   }

   [ContractInvariantMethod]
   <span class="op">protected void</span> ValidAccount()
   {
      Contract.Invariant(Balance &gt;=0);
   }
}</pre>
<p>Как можно увидеть, контракт реализуется при помощи функций, что сразу вызывает вопрос, почему? Гораздо красивее была бы объявление контракта отдельно от кода, например с помощью  атрибутов. К сожалению, атрибуты, по утверждению разработчиков, не позволяют описать все сценарии использования контрактов. Была возможность передавать в атрибуты сложные выражения, но они не захотели дублировать функциональность синтаксического анализатора. Так же они не захотели добавлять эту функциональность напрямую в язык, так как при этом другие .NET-языки не смогли бы ею воспользоваться. Так что мы имеем набор из десятка функций и нескольких атрибутов, которые войдут в <em>mscorlib</em>.</p>
<h3>Code Contracts library</h3>
<p>.NET 4 пока что не вышел, но попробовать контрактное программирование можно уже сейчас, загрузив библиотеку Code Contracts для .NET 3.5 с сайта <a rel="nofollow" href="http://msdn.microsoft.com/en-ca/devlabs/dd491992.aspx">Dev Labs</a>. Библиотека доступна в двух вариантах: VSTS Edition для владельцев Visual Studio Team System, в которой доступны все возможности и ее применение разрешено в коммерческих целях, и Standard Edition для всех версий Visual Studio, за исключением Express Edition. Эта версия лицензируется для академических целей и не включает проверки контрактов во время компиляции.</p>
<p style="text-align: center;"><img src="http://lunarfrog.com/images/blog/ccoptions.png" alt="" /></p>
<p>При инсталляции, в систему добавляется библиотека Microsoft.Contracts, примеры и документация. Также, в Visual Studio инсталлятор добавляет в свойства проекта дополнительную страницу Code Contracts, на которой можно управлять поведением библиотеки. Для того, что бы начать работу с контрактами, в проект необходимо добавить ссылку на библиотеку <em>Microsoft.Contracts.dll</em>, расположенную в папке <em>%PROGRAMFILES%/Microsoft/Contracts/PublicAssemblies</em>.</p>
<p>Код, приведенный выше для примера, демонстрирует использование трех основных частей контракта: предусловий Contract.Requires в функциях Deposit и Withdraw, декларирующих, что они работают только с положительными суммами денег; постусловий Contract.Ensures в функции Transfer, которые заявляют, что в качестве результата функция должна вернуть новый счет и обнулить текущий; инварианта класса ValidAccount, утверждающего, что счет находиться в правильном состоянии, если его баланс больше или равен нулю.</p>
<p>Итак, контракт объявлен. Но что это нам дает? Что произойдет, если контракт будет нарушен, например, в случае такого вызова account.Deposit(-1000.0)? Это зависит от используемых настроек. Если включена статическая проверка контрактов, то уже на этапе компиляции будет выдано предупреждение о нарушении контракта. Если же включена только проверка контрактов во время выполнения, то, в простейшем случае, в момент вызова функции будет сгенерировано исключение ContractException. Если проверка отключена полностью, то никакой реакции не последует, так как в скомпилированном коде будут отсутствовать любые проверки.</p>
<ul class="arrows">
<li>На самом деле код не просто скомпилирован, но и пропущен через модуль ccrewrite.exe, который подвергает полученный в результате компиляции IL-код постобработке, в результате чего декларация контракта превращается в конкретные вызовы методов проверки.</li>
</ul>
<p>Дополнительно, библиотека позволяет достаточно гибко менять параметры runtime-проверки контрактов. Во-первых, можно задать какие именно части контракта необходимо проверять, например, только предусловия. И, во-вторых, можно перехватить событие Contract.ContractFailed  или задать свой класс, методы которого будут вызываться вместо генерации исключения. Таким образом, к примеру, можно автоматически протоколировать нарушения контракта перед завершением программы.</p>
<p>Далее коротко пройдемся по всем основным элементам контракта.</p>
<h3>Предусловия</h3>
<p>Декларируют условия, необходимые для работы метода, выражаются с помощью Contract.Requires() и обычно используются для проверки входящих параметров. Функция Requires()принимает в качестве параметра логическое выражение выражающее условие контракта.  Так же существует перегруженная функция, принимающая в качестве второго параметра строку – сообщение, используемое при нарушении условия.</p>
<pre class="code">Contract.Requires(amount &gt; 0, <span class="str">"Invalid amount"</span>);</pre>
<p>Как уже упоминалось выше, в зависимости от настроек текущей конфигурации в скомпилированном коде проверок контракта может и не быть. Однако, если вы хотите, что бы проверка предусловия осуществлялась всегда, вне зависимости от настроек, то можно использовать функцию Contract.RequiresAlways(), которая будет работать даже при отключеннии проверок в настройках проекта.</p>
<pre class="code">Contract.RequiresAlways(x != 0);</pre>
<p>Если вы добавляете поддержку контрактов в существующее приложение, то, возможно, у вас уже есть проверка входящих параметров функций. Если она выполнена в виде</p>
<pre class="code"><span class="op">if</span> (условие) <span class="op">throw new</span>...</pre>
<p>то, добавив вызов Contract.EndContractBlock() после этих проверок, вы превратите их в предусловия. Аналогичное действие окажет и вызов Contract.Requires(). На выражения накладываются следующие ограничения – они не должны выполнять ничего кроме генерации исключения, оператор else не поддерживается.</p>
<h3>Постусловия</h3>
<p>Постусловия декларируют состояние, достигнутое после завершения работы метода. Простой пример постусловия:</p>
<pre class="code">Contract.Ensures(Balance == 0);</pre>
<p>Постусловия, как и предусловия, объявляются в начале метода, однако в результате постобработки проверка условия будет осуществлена после выполнения всех инструкций метода. Это легко увидеть, запустив отладку метода содержащего постусловия – сначала отладчик пройдет по всем инструкциям, включая return и лишь затем перейдет к выполнению проверок.</p>
<p>Приведенный выше синтаксис работает в простейших случаях, для реализации более сложных сценариев используются дополнительные методы.</p>
<p>Так, для верификации возвращаемого функцией значения используется специальный метод Contract.Result&lt;T&gt;(), где T &#8211; это тип возвращаемого функцией значения.</p>
<pre class="code">Contract.Ensures( Contract.Result&lt;<span class="op">int</span>&gt;() &gt; 0 );</pre>
<p>Метод Contract.OldValue(e) позволяет получить значение переменной e до начала работы метода. Существует несколько ограничений на применение OldValue, главное из которых – переменная должна существовать перед началом выполнения инструкций метода и ее значение должно быть вычисляемым. В качестве таких переменных, например, могут выступать свойства класса или входящие переменные метода.</p>
<pre class="code">Contract.Ensures(Contract.OldValue(i) &lt; n);</pre>
<p>Для проверки в постусловиях значений out-переменных используется метод Contract.ValueAtReturn(out T t)</p>
<pre class="code"><span class="op">public void</span> TestOut (<span class="op">out int</span> a)
{
   Contract.Ensures(Contract.ValueAtReturn(<span class="op">out</span> a) == 8);
   a = 8;
}</pre>
<h3>Инварианты класса</h3>
<p>Инварианты класса относятся ко всему экземпляру класса и декларируют условия, при которых объект находиться в “хорошем” состоянии.</p>
<pre class="code">[ContractInvariantMethod]
<span class="op">protected void</span> ValidAccount()
{
   Contract.Invariant(Balance &gt;= 0);
}</pre>
<p>Объявления всех инвариантов помещаются в один метод класса, помеченный атрибутом ContractInvariantMethod. Этот метод не должен содержать никакого кода, кроме объявлений инвариантов и не может возвращать значения. Каждый инвариант задается вызовом метода Contract.Invariant(). Проверка инвариантов класса происходит в конце каждого public метода класса &#8211; если посмотреть IL-код программы, то можно увидеть, что в процессе постобработки в конец каждого такого метода добавляется вызов нашей функции, помеченной атрибутом ContractInvariantMethod.</p>
<p>Дополнительно, в любом месте программы можно использовать Contract.Assert() для проверки условия в этой точке.</p>
<pre class="code">Contract.Assert( _number &gt; 0 );</pre>
<p>В процессе выполнения программы, если выражение ложно, то  произойдет вызов Debug.Assert, в противном случае не последует никаких действий.</p>
<h3>Контракты для интерфейсов</h3>
<p>Описанные выше методы декларации контракта отлично работают в случае с конкретным классом. Однако что нам делать, если возникнет необходимость задать контракт для интерфейса? Ведь компилятор C# не позволит добавить для интерфейса тело функции с  вызовом методов Contract.Requires() или Contract.Ensures(). На помощь приходит вспомогательный класс и пара атрибутов – ContractClass и ContractClassFor.</p>
<pre class="code">[ContractClass(<span class="op">typeof</span>(SavingAccount))]
<span class="op">interface</span> IAccount
{
   <span class="op">int</span> Balance { <span class="op">get</span>; }
   <span class="op">void</span> Deposit(<span class="op">int</span> amount);
}

[ContractClassFor(<span class="op">typeof</span>(IAccount))]
<span class="op">class</span> SavingAccount : IAccount
{
   <span class="op">int</span> IAccount.Balance
   {
      <span class="op">get</span>
      {
         Contract.Ensures(Contract.Result&lt;<span class="op">int</span>&gt;() &gt;=0 );
         <span class="op">return default</span>(<span class="op">int</span>);
      }
   }
   <span class="op">void</span> IAccount.Deposit(<span class="op">int</span> amount)
   {
      Contract.Requires(amount &gt; 0);
   }
}</pre>
<p>Для интерфейса создается вспомогательный класс, реализующий его и декларирующий контракт. Для установления связи между классом и интерфейсом используются атрибуты. Точно таким же способом можно объявить контракт для абстрактного метода, создав вспомогательного наследника и реализовав метод.</p>
<p>Поскольку статья задумывалась как введение в библиотеку Code Contracts, то я не стал описывать некоторые нюансы ее использования и методы, используемые в специальных случаях – с ними вы можете познакомиться в достаточно подробном документе, идущем вместе с библиотекой. Так же, для начала, может быть интересным видео с одним из разработчиков библиотеки, доступное на сайте <a rel="nofollow" href="http://msdn.microsoft.com/en-ca/devlabs/dd491992.aspx">Dev Labs</a>.</p>
<div class="bottomcontainerBox" style="">
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Flunarfrog.com%2Fblog%2F2009%2F11%2F30%2F%25d0%25b1%25d0%25b8%25d0%25b1%25d0%25bb%25d0%25b8%25d0%25be%25d1%2582%25d0%25b5%25d0%25ba%25d0%25b0-code-contracts-%25d0%25ba%25d0%25be%25d0%25bd%25d1%2582%25d1%2580%25d0%25b0%25d0%25ba%25d1%2582%25d0%25bd%25d0%25be%25d0%25b5-%25d0%25bf%25d1%2580%25d0%25be%25d0%25b3%25d1%2580%25d0%25b0%25d0%25bc%25d0%25bc%25d0%25b8%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width=85px; height:21px;" allowTransparency="true"></iframe></div>
			<div style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://lunarfrog.com/blog/2009/11/30/%d0%b1%d0%b8%d0%b1%d0%bb%d0%b8%d0%be%d1%82%d0%b5%d0%ba%d0%b0-code-contracts-%d0%ba%d0%be%d0%bd%d1%82%d1%80%d0%b0%d0%ba%d1%82%d0%bd%d0%be%d0%b5-%d0%bf%d1%80%d0%be%d0%b3%d1%80%d0%b0%d0%bc%d0%bc%d0%b8/"></g:plusone>
			</div>
			<div style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://lunarfrog.com/blog/2009/11/30/%d0%b1%d0%b8%d0%b1%d0%bb%d0%b8%d0%be%d1%82%d0%b5%d0%ba%d0%b0-code-contracts-%d0%ba%d0%be%d0%bd%d1%82%d1%80%d0%b0%d0%ba%d1%82%d0%bd%d0%be%d0%b5-%d0%bf%d1%80%d0%be%d0%b3%d1%80%d0%b0%d0%bc%d0%bc%d0%b8/"  data-text="Библиотека Code Contracts: контрактное программирование под .NET" data-count="horizontal" data-via="taggedfrog">Tweet</a>
			</div><div style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://lunarfrog.com/blog/2009/11/30/%d0%b1%d0%b8%d0%b1%d0%bb%d0%b8%d0%be%d1%82%d0%b5%d0%ba%d0%b0-code-contracts-%d0%ba%d0%be%d0%bd%d1%82%d1%80%d0%b0%d0%ba%d1%82%d0%bd%d0%be%d0%b5-%d0%bf%d1%80%d0%be%d0%b3%d1%80%d0%b0%d0%bc%d0%bc%d0%b8/" data-counter="right"></script></div>			
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://lunarfrog.com/blog/2009/11/30/%d0%b1%d0%b8%d0%b1%d0%bb%d0%b8%d0%be%d1%82%d0%b5%d0%ba%d0%b0-code-contracts-%d0%ba%d0%be%d0%bd%d1%82%d1%80%d0%b0%d0%ba%d1%82%d0%bd%d0%be%d0%b5-%d0%bf%d1%80%d0%be%d0%b3%d1%80%d0%b0%d0%bc%d0%bc%d0%b8/"></script></div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div>]]></content:encoded>
			<wfw:commentRss>http://lunarfrog.com/blog/2009/11/30/%d0%b1%d0%b8%d0%b1%d0%bb%d0%b8%d0%be%d1%82%d0%b5%d0%ba%d0%b0-code-contracts-%d0%ba%d0%be%d0%bd%d1%82%d1%80%d0%b0%d0%ba%d1%82%d0%bd%d0%be%d0%b5-%d0%bf%d1%80%d0%be%d0%b3%d1%80%d0%b0%d0%bc%d0%bc%d0%b8/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

