<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>.NET and me</title>
	
	<link>http://blog.vuscode.com</link>
	<description>Coding dreams since 1998!</description>
	<lastBuildDate>Thu, 18 Oct 2012 23:14:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/vuscode" /><feedburner:info uri="vuscode" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><geo:lat>50.05</geo:lat><geo:long>14.25</geo:long><feedburner:emailServiceId>vuscode</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>Awaitable task progress reporting</title>
		<link>http://feedproxy.google.com/~r/vuscode/~3/YSrFdJQkOsw/awaitable-task-progress-reporting.aspx</link>
		<comments>http://blog.vuscode.com/malovicn/archive/2012/09/21/awaitable-task-progress-reporting.aspx#comments</comments>
		<pubDate>Fri, 21 Sep 2012 22:40:07 +0000</pubDate>
		<dc:creator>administrator</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Async]]></category>

		<guid isPermaLink="false">http://blog.vuscode.com/?p=2546</guid>
		<description><![CDATA[<p>In my previous Task.WhileAll post I had a very fishy piece of code in sample where I put a Thread to sleep in order to give enough time for async composition to complete so the test could pass. Well, every time I use a Thread.Sleep anywhere I know it is a bad thing so I've [...]</p><p>The post <a href="http://blog.vuscode.com/malovicn/archive/2012/09/21/awaitable-task-progress-reporting.aspx">Awaitable task progress reporting</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>In my <a title="Task.WhileAll" href="http://blog.vuscode.com/malovicn/archive/2012/09/20/task-whileall.aspx" target="_blank">previous Task.WhileAll post</a> I had a very fishy piece of code in sample where I put a Thread to sleep in order to give enough time for async composition to complete so the test could pass.</p>
<p>Well, every time I use a Thread.Sleep anywhere I know it is a bad thing so I've decided to get rid of it.</p>
<h2>IProgressAsync&lt;T&gt;</h2>
<p>The problem is related to the fact that <a href="http://msdn.microsoft.com/en-us/library/hh138298.aspx" target="_blank">IProgress&lt;T&gt;</a> interface defines a void handler which can't be awaited and thus it ruins composition.</p>
<p>That's why I decided to define my own "true async" version of the interface which looks has the same report method but returning a Task I can await.</p>
<pre class="brush: csharp; title;">    
namespace WhileAllTests
{
    using System.Threading.Tasks;

    public interface IProgressAsync&lt;in T&gt;
    {
        Task ReportAsync(T value);
    }
}</pre>
<p>Having a async version of reporting is VERY useful when the subscriber itself is awaiting further calls. I could get that with async void but using async void IMHO always turns to be bad solution so I choose to use the Task returning signature even I need a custom made interface for that.</p>
<p>And here's the implementation</p>
<pre class="brush: csharp; title;">    
    using System;
    using System.Threading.Tasks;

    public class ProgressAsync&lt;T&gt; : IProgressAsync&lt;T&gt;
    {
        private readonly Func&lt;T, Task&gt; handler;

        public ProgressAsync(Func&lt;T, Task&gt; handler)
        {
            this.handler = handler;
        }

        public async Task ReportAsync(T value)
        {
            await this.handler.Invoke(value);
        }
    }</pre>
<p>No magic here:</p>
<ul>
<li>Instead of Action&lt;T&gt; my ctor accepts the Func&lt;T, Task&gt; so I can await it</li>
<li>ReportAsync awaits in async manner the provided Task  enabling composition</li>
</ul>
<p>Now having this in place I can update my task extension method to compose reporting method invocation</p>
<pre class="brush: csharp; title;">public static async Task&lt;IList&gt; WhileAll(this IList&lt;Task&gt; tasks, IProgressAsync progress)
        {
            var result = new List(tasks.Count);
            var remainingTasks = new List&lt;Task&gt;(tasks);
            while (remainingTasks.Count &gt; 0)
            {
                await Task.WhenAny(tasks);
                var stillRemainingTasks = new List&lt;Task&gt;(remainingTasks.Count - 1);
                for (int i = 0; i &lt; remainingTasks.Count; i++)
                {
                    if (remainingTasks[i].IsCompleted)
                    {
                        result.Add(remainingTasks[i].Result);
                        await progress.ReportAsync(remainingTasks[i].Result);
                    }
                    else
                    {
                        stillRemainingTasks.Add(remainingTasks[i]);
                    }
                }

                remainingTasks = stillRemainingTasks;
            }

            return result;
        }</pre>
<p>With all this in place I can remove thread sleep from my unit tests and have it more useful</p>
<p>&nbsp;</p>
<pre class="brush: csharp; title;">[TestClass]
public class UnitTest1 {

Listresult = new List();

[TestMethod]
    [TestClass]
    public class UnitTest1 {

        List&lt;int&gt; result = new List&lt;int&gt;();

        [TestMethod]
        public async Task TestMethod1() {

            var task1 = Task.Run(() =&gt; 101);
            var task2 = Task.Run(() =&gt; 102);
            var tasks = new List&lt;Task&lt;int&gt;&gt;() { task1, task2 };

            var listener = new ProgressAsync&lt;int&gt;(this.OnProgressAsync);
            var actual = await tasks.WhileAll(listener);

            Assert.AreEqual(2, this.result.Count);
            Assert.IsTrue(this.result.Contains(101));
            Assert.IsTrue(this.result.Contains(102));

            Assert.AreEqual(2, actual.Count);
            Assert.IsTrue(actual.Contains(101));
            Assert.IsTrue(actual.Contains(102));
        }

       private async Task OnProgressAsync(int arg) { result.Add(arg); }
    }</pre>
<p>There you go, updated code of Task.WhileAll can be found <a title="sample code" href="http://sdrv.ms/SaoyV2" target="_blank">here</a></p>
<p>The post <a href="http://blog.vuscode.com/malovicn/archive/2012/09/21/awaitable-task-progress-reporting.aspx">Awaitable task progress reporting</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/vuscode?a=YSrFdJQkOsw:r3Z-CJwufKk:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=YSrFdJQkOsw:r3Z-CJwufKk:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=YSrFdJQkOsw:r3Z-CJwufKk:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/vuscode?i=YSrFdJQkOsw:r3Z-CJwufKk:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/vuscode/~4/YSrFdJQkOsw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vuscode.com/malovicn/archive/2012/09/21/awaitable-task-progress-reporting.aspx/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2012/09/21/awaitable-task-progress-reporting.aspx</feedburner:origLink></item>
		<item>
		<title>Task.WhileAll</title>
		<link>http://feedproxy.google.com/~r/vuscode/~3/ySElFwhGhTs/task-whileall.aspx</link>
		<comments>http://blog.vuscode.com/malovicn/archive/2012/09/20/task-whileall.aspx#comments</comments>
		<pubDate>Thu, 20 Sep 2012 22:31:25 +0000</pubDate>
		<dc:creator>administrator</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Async]]></category>

		<guid isPermaLink="false">http://blog.vuscode.com/?p=2542</guid>
		<description><![CDATA[<p>When Task.WhenAll met the Task.WhenAny… There are two methods which can be used for awaiting an array of tasks in non blocking manner: Task.WhenAll and Task.WhenAny. It is quite obvious how they work: WhenAll completes when every task is completed, WhenAny when any of the task is completed. I needed today something which is a [...]</p><p>The post <a href="http://blog.vuscode.com/malovicn/archive/2012/09/20/task-whileall.aspx">Task.WhileAll</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p>]]></description>
				<content:encoded><![CDATA[<h1>When Task.WhenAll met the Task.WhenAny…</h1>
<p>There are two methods which can be used for awaiting an array of tasks in non blocking manner: <a title="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.whenall.aspx" href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.whenall.aspx" target="_blank">Task.WhenAll</a> and <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.whenany.aspx" target="_blank">Task.WhenAny</a>.</p>
<p>It is quite obvious how they work: </p>
<ul>
<li>WhenAll completes when every task is completed, </li>
<li>WhenAny when any of the task is completed. </li>
</ul>
<p>I needed today something which is a mix of those two and I’ve came up with something which completes when all is awaited but also provides hook for me to respond on awaits of individual tasks.</p>
<p>I’ve called my little extension: <strong>Task.WhileAll.</strong></p>
<h2>Extension method</h2>
<p>Here's the complete implementation</p>
<pre class="brush: csharp; title;">    
public static class TaskExtensions 
{
	public static async Task&lt;IList&lt;T&gt;&gt; WhileAll&lt;T&gt;(this IList&lt;Task&lt;T&gt;&gt; tasks, IProgress&lt;T&gt; progress) 
	{
		var result = new List&lt;T&gt;(tasks.Count);
		var done = new List&lt;Task&lt;T&gt;&gt;(tasks);
		while(done.Count &gt; 0) 
		{
			await Task.WhenAny(tasks);
			var spinning = new List&lt;Task&lt;T&gt;&gt;(done.Count - 1);
			for(int i = 0; i &lt; done.Count; i++) 
			{
				if(done[i].IsCompleted) 
				{
					result.Add(done[i].Result);
					progress.Report(done[i].Result);
				} else {
					spinning.Add(done[i]);
				}
			}

			done = spinning;
		}

		return result;
	}
}</pre>
<p>&#160;</p>
<p>The code is quire simple:</p>
<ul>
<li>it is an async extension method extending the IList&lt;Task&lt;T&gt;&gt; </li>
<li>method returns on completition IList&lt;T&gt; (result of awaited tass) </li>
<li>Method accepts <a href="http://msdn.microsoft.com/en-us/library/hh138298.aspx" target="_blank">IProgress&lt;T&gt;</a> interface publishing information about the tasks who had just completed to the interested subscribers </li>
<li>Inside of the method body we have a loop which is active as long there are tasks with IsCompleted==false. </li>
<li>The loop has a “sleep” line where I use await Task.WhenAny to asynchronuslly wait for any task to complete </li>
</ul>
<h2>Unit test</h2>
<p>Here’s a simple unit test ilustrating the usage of the extension method</p>
<pre class="brush: csharp; title;">  
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class UnitTest1 {
        [TestMethod]
        public async Task TestMethod1() {

            var task1 = Task.Run(() =&gt; 101);
            var task2 = Task.Run(() =&gt; 102);
            var tasks = new List&lt;Task&lt;int&gt;&gt;() { task1, task2 };


            List&lt;int&gt; result = new List&lt;int&gt;();
            var listener = new Progress&lt;int&gt;(
                taskResult =&gt; {
                    result.Add(taskResult);
                });

            var actual = await tasks.WhileAll(listener);
            Thread.Sleep(50); // wait a bit for progress reports to complete

            Assert.AreEqual(2, result.Count);
            Assert.IsTrue(result.Contains(101));
            Assert.IsTrue(result.Contains(102));

            Assert.AreEqual(2, actual.Count);
            Assert.IsTrue(actual.Contains(101));
            Assert.IsTrue(actual.Contains(102));
        }
    }</pre>
<p>Again, nothing complicated :</p>
<ul>
<li>I create an array of two dumb tasks </li>
<li>I define the listner which takes the task result and (for the unit test needs) adds it to the collection of results </li>
<li>I await the extension methods on task array with provided listner </li>
<li>Wait for 50 ms so the progress report would have time to finish (code is async after all) </li>
<li>Check that both tasks were reported to subscriber </li>
<li>Check that both tasks are returned as result. </li>
</ul>
<h2>Conclussion</h2>
<p>That’s it. Dead simple code which I use A LOT to increase CPU utilization of my web crawlers.</p>
<p>Source code of the extension method and unit test can be found <a href="http://sdrv.ms/SaoyV2" target="_blank">here</a>. </p>
<p>The post <a href="http://blog.vuscode.com/malovicn/archive/2012/09/20/task-whileall.aspx">Task.WhileAll</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/vuscode?a=ySElFwhGhTs:vjPA2KWbLf8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=ySElFwhGhTs:vjPA2KWbLf8:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=ySElFwhGhTs:vjPA2KWbLf8:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/vuscode?i=ySElFwhGhTs:vjPA2KWbLf8:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/vuscode/~4/ySElFwhGhTs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vuscode.com/malovicn/archive/2012/09/20/task-whileall.aspx/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2012/09/20/task-whileall.aspx</feedburner:origLink></item>
		<item>
		<title>Hacking the KendoUI grid</title>
		<link>http://feedproxy.google.com/~r/vuscode/~3/zolACbw90IA/hacking-the-kendoui-grid.aspx</link>
		<comments>http://blog.vuscode.com/malovicn/archive/2012/06/14/hacking-the-kendoui-grid.aspx#comments</comments>
		<pubDate>Wed, 13 Jun 2012 23:08:01 +0000</pubDate>
		<dc:creator>administrator</dc:creator>
				<category><![CDATA[MVC]]></category>
		<category><![CDATA[KendoUI]]></category>

		<guid isPermaLink="false">http://blog.vuscode.com/?p=2548</guid>
		<description><![CDATA[<p>Here’s the thing: I love KendoUI grid! It allows a server side desktop guy like me getting really nice results.In case you don’t have a clue what I am talking about go and look at their demo page for what KendoUI can do. The only problem I have with KendoUI is that is “client side” [...]</p><p>The post <a href="http://blog.vuscode.com/malovicn/archive/2012/06/14/hacking-the-kendoui-grid.aspx">Hacking the KendoUI grid</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>Here’s the thing: <strong>I love <a href="http://demos.kendoui.com/web/grid/index.html" target="_blank">KendoUI grid</a></strong>!</p>
<p>It allows a server side desktop guy like me getting really nice results.In case you don’t have a clue what I am talking about go and look at their demo page for what KendoUI can do.</p>
<p>The only problem I have with KendoUI is that is “client side” UI technology which is I am sure the way to go in 2012 and perfect for many folks but I personally prefer doing my things as much I can in C# and use jscript when I have to.</p>
<p><strong><span style="color: #ff0000;">Source code of today’s blog post can be found </span></strong><a href="http://sdrv.ms/LKQHib" target="_blank"><strong><span style="color: #ff0000;">here</span></strong></a></p>
<h2>What is the problem?</h2>
<p>Imagine a use case where you have a page where you enter a salary document which has a heading with  a date and number and a list of employees getting paid in that month.</p>
<p>Something like this</p>
<pre class="brush: csharp; title;">    
     public class CartHeaderModel
    {
        public string Number { get; set; }
        public DateTime Date { get; set; }

        public IList Items { get; set; }
    }

    public class CartItemModel
    {
        public string FullName { get; set; }

        public decimal NetAmount { get; set; }
        public decimal GrossAmount { get; set; }
    }</pre>
<h2>Client side story</h2>
<p>To enable entering of this data using MVC, one might create a page with two text boxes and a  grid for showing and entering the employee data. (Similar example to this is cart and cart items and other master details LOB scenarios).</p>
<p>Something like this</p>
<pre class="brush: html; title;">    
&lt;body&gt;
        
	@model KendoPractice.Models.CartHeaderModel
        
	@using (Html.BeginForm((string)ViewBag.FormAction, "Home"))
        
	{
            
		&lt;fieldset id="employee-new"&gt;
&lt;legend&gt;Podaci obračuna&lt;/legend&gt;</pre>
<p>&lt;div&gt;<br />
@Html.LabelFor(m =&gt; m.Number)<br />
@Html.TextBoxFor(m =&gt; m.Number)<br />
@Html.ValidationMessageFor(m =&gt; m.Number)<br />
&lt;/div&gt;<br />
&lt;div&gt;<br />
@Html.LabelFor(m =&gt; m.Date)<br />
@Html.TextBoxFor(m =&gt; m.Date)<br />
@Html.ValidationMessageFor(m =&gt; m.Date)<br />
&lt;/div&gt;<br />
&lt;div id="grid"&gt;&lt;/div&gt;</p>
<p>&lt;input type="hidden" id="items" name="items" /&gt;<br />
&lt;input type="submit" value="Snimi podatke" /&gt;</p>
<p>&lt;/fieldset&gt;<br />
}<br />
&lt;/body&gt;</p>
<p>Few things are going on here:</p>
<ul>
<li>There’s a form having two text boxes for header information</li>
<li>A grid is represented with just a empty div element with id=”grid”</li>
<li>There is one hidden input field with name “items” which would be used to post client grid state to server.</li>
</ul>
<p>This is not supposed to be a post about Kendo (I am planning to do a few How-To later but not now) so here’s a very short explanation on how grid gets hooked up – it is quite simple.</p>
<pre class="brush: js; title;">            $("#grid").kendoGrid({
                dataSource: salaryDataSource,
                editable: { mode: "incell" },
                columns: [
                    { title: "Employee name", field: "FullName", width: 90, validation: { required: true } },
                    { title: "Net wage", field: "NetAmount", width: 90, validation: { required: true } },
                    { title: "Gross wage", field: "GrossAmount", width: 90, validation: { required: true } },
                ],
            });</pre>
<p>As you can see, jquery selector gets a pointer on div with id grid and then wraps it with a .kendoGrid() having a few properties set up so the column headers etc. would be set. The data comes from a object called <strong>salaryDataSource</strong> which looks like this</p>
<pre class="brush: js; title;">	 
	var itemsData = @Html.Raw(ViewData["gridInitContext"]);
	var salaryDataSource = new kendo.data.DataSource({
                data: itemsData,

                change: function (e) {
                    var datas = salaryDataSource.data();
                    var result = "[";
                    var separator = "";
                    for (var i = 0; i &lt; datas.length; i++) {
                        result += separator + JSON.stringify(datas[i]);
                        separator = ",";
                    }
                    result += "]";
                    $("#items").val(result);
                }
            });</pre>
<p>&nbsp;</p>
<p>Few interesting things here:</p>
<ul>
<li>DataSource is hooked to a variable called itemsData which content is injected from server using the ViewData[“gridInitContext”]</li>
<li>Every time data source is changed, all of the bounded items are concatenated to a JSON array and value of a hidden field with an id <strong>items </strong>is set to that JSOn value.</li>
</ul>
<p>To summarize the client side story:</p>
<ul>
<li>KendoUI wraps the div and provides a rich grid UI functionality without any ajax calls</li>
<li>Initial data context of the grid is injected in a form of JSON collection from server using a ViewData[“gridInitContext”]</li>
<li>Every time bounded data of data source change the value of the hidden input field is getting updated to its JSON representation and on page post that value gets posted.</li>
</ul>
<h2>Server side story</h2>
<p>Having in mind just summarized things, we are going to quickly check the Home controller now</p>
<pre class="brush: csharp; title;">    
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            //  in real world this comes from a repository etc - blog post only code
            var model = new CartHeaderModel()
            {
                Number = "12345",
                Date = DateTime.Now,
                Items = new List()
                {
                    new CartItemModel { FullName = "John Doe", GrossAmount = 123, NetAmount = 456},
                    new CartItemModel { FullName = "Jane Doe", GrossAmount = 555, NetAmount = 666},
                }
            };

            // pass to view JSON reprensentation of init context of the grid
            ViewData["gridInitContext"] = JsonConvert.SerializeObject(model.Items);

            return View(model);
        }

        [HttpPost]
        public ActionResult Index(string items, CartHeaderModel cartHeaderModel)
        {
            cartHeaderModel.Items = Newtonsoft.Json.JsonConvert.DeserializeObject&gt;(items);

            // now with complete model we proceed as there was no kendo at all.
            return View();
        }
    }</pre>
<p>Few interesting moments:</p>
<ul>
<li>Index get action serialize to json items collection and store to view data so KendoUI can initialize grid  from it.</li>
<li>Post action gets two params where the items one contains JSON reprensentation of the client state which gets deserialized and the model is being completed.</li>
</ul>
<p><a href="http://vuscode.cloudapp.net/wp-content/uploads/2012/06/image.png"><img style="display: inline;" title="image" src="http://vuscode.cloudapp.net/wp-content/uploads/2012/06/image_thumb.png" alt="image" width="640" height="106" /></a></p>
<h2>What is the point of all this?</h2>
<p>It is quite simple:</p>
<ul>
<li>Have a server side code as ignorant as possible about the KendoUI.</li>
<li>Enable KendoUI to work in its full coolness.</li>
</ul>
<p>In other words, I wanted KendoUI to be a toppling on my MVC cake, and not the part of the cake itself.</p>
<p>Samples on kendoui.com site are always showing the use case when you define CRUD controller just to feed the grid which IMHO breaks the MVC because half of your model gets to the server item by item using ajax calls, and half of it gets after page post.</p>
<p>I don’t know if this would be useful to anyone, but I wanted to share it with the community just in case there is someone out there.</p>
<p>The post <a href="http://blog.vuscode.com/malovicn/archive/2012/06/14/hacking-the-kendoui-grid.aspx">Hacking the KendoUI grid</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/vuscode?a=zolACbw90IA:v-6RKNLTqlI:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=zolACbw90IA:v-6RKNLTqlI:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=zolACbw90IA:v-6RKNLTqlI:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/vuscode?i=zolACbw90IA:v-6RKNLTqlI:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/vuscode/~4/zolACbw90IA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vuscode.com/malovicn/archive/2012/06/14/hacking-the-kendoui-grid.aspx/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2012/06/14/hacking-the-kendoui-grid.aspx</feedburner:origLink></item>
		<item>
		<title>One BIG problem with Azure Tables</title>
		<link>http://feedproxy.google.com/~r/vuscode/~3/fhjx0XjVXdw/one-big-problem-with-azure-tables.aspx</link>
		<comments>http://blog.vuscode.com/malovicn/archive/2012/04/14/one-big-problem-with-azure-tables.aspx#comments</comments>
		<pubDate>Sat, 14 Apr 2012 18:12:59 +0000</pubDate>
		<dc:creator>administrator</dc:creator>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Gotchas]]></category>
		<category><![CDATA[Storage]]></category>
		<category><![CDATA[Tables]]></category>

		<guid isPermaLink="false">http://blog.vuscode.com/?p=2539</guid>
		<description><![CDATA[<p>Migrating SQL Azure to Azure Tables - GUID gotcha Windows Azure rocks! I am so impressed with the power it gives me with the price I can afford that I started porting the codebase I work on at home in my spare time. So far, I’ve connected my clients to Azure Service Bus Topics (works [...]</p><p>The post <a href="http://blog.vuscode.com/malovicn/archive/2012/04/14/one-big-problem-with-azure-tables.aspx">One BIG problem with Azure Tables</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p>]]></description>
				<content:encoded><![CDATA[<h2>Migrating SQL Azure to Azure Tables - GUID gotcha</h2>
<p>Windows Azure rocks! I am so impressed with the power it gives me with the price I can afford that I started porting the codebase I work on at home in my spare time.</p>
<p>So far, I’ve connected my clients to Azure Service Bus Topics (works great), created my own custom app SkyDrive using Azure Blob storage (works great) and today I tried to port my SQL Server databases to Azure Table Storage.</p>
<h2>3 main reasons when to pick Azure Tables – fulfilled</h2>
<p>The reason why I decided to port my data is that in a way I was using already my SQL Server DB as it is table:</p>
<ul>
<li>My primary key of the table is sequential Guid (in order to <a href="http://www.informit.com/articles/article.aspx?p=25862" target="_blank">remove performance issue caused by normal guid PKs</a>)<br />
<strong>RowKey checked</strong></li>
<li>In some of the tables I have a column OwnerID which I already use to horizontally partition my data –<br />
<strong>PartitionKey checked</strong></li>
<li>I do all of the joins etc.  on client side and perform only two select queries: SelectByPK and SelectNewerPKs.This second select gets from client input parameter anchor identity value and returns all of the rows whose RowKey is greater then a given value. I use it to get the change set / data deltas which I need to sync from server to client DB in order to update client DB with the new data existing in the cloud.( get me all of the rows which PK is greater then the given value)</li>
</ul>
<p>No need to bother you with more details regarding my database, II guess it is clear just based on these 3 things how good match my DB structure is for moving to Azure Tables.</p>
<h2>Why Azure tables?</h2>
<p>Quite simple: price and scalability.</p>
<p>SQL Azure is very affordable (especially after the last price cut) so in order to get 5 Gb DB you pay only 25 USD/month which is really nothing. Still, if your app architecture doesn’t use SQL server relational capabilities and relies primarily on clients and “PK selects”  (as mine does) then Azure tables can be used and the price for 5 Gb storage is <strong>0.625 USD/month. </strong>Let me repeat that one more time: less then one USD per month would cost me 5 Gb Table storage space. <strong>Completely and utterly insanely awesome!</strong></p>
<p>Scalability is the same story as with the price. While SQL Azure is making big steps to enable sharding scenarios with <a title="Sql Azure Federations" href="http://channel9.msdn.com/Shows/Cloud+Cover/Episode-69-SQL-Azure-Federations-with-George-Huey" target="_blank">SQL Azure Federations</a>, tables are having partitioning built in from “day 1” as a fundamental design principle and allows scaling datasets which size measures in TBs. <strong>Awesome!</strong></p>
<h2>So what is the problem then with Azure Tables?</h2>
<p>Problem is that Azure Tables uses Comparer&lt;Guid&gt; (.NET approach) and not  the Comparer&lt;SqlGuid&gt; (SqlServer and SqlCompact approach).</p>
<p>In other words</p>
<blockquote>
<p style="text-align: center;"><strong><em>"SQL Server and Azure Tables are sorting rows differentlly </em></strong></p>
<p style="text-align: center;"><strong><em>when RowKey is unique idenitifier (GUID) </em></strong></p>
<p style="text-align: center;"><strong><em>which leads to the row shuffling"</em></strong></p>
</blockquote>
<p>&nbsp;</p>
<p>Let me explain it in one simple example….</p>
<p>Let say we have next dummy table in SQL Server database</p>
<p><a href="http://blog.vuscode.com/wp-content/uploads/2012/04/image.png"><img style="display: inline;" title="image" src="http://blog.vuscode.com/wp-content/uploads/2012/04/image_thumb.png" alt="image" width="354" height="135" /></a></p>
<p>And let say this table has two rows:</p>
<ol>
<li><strong>ID</strong>: 7240963F-D384-4D78-BADF-A03300F678CC, <strong>Name</strong>:  First</li>
<li><strong>ID</strong>: 15DF6719-9671-43D3-BAFA-A03300F678CD, <strong>Name</strong>:  Second</li>
</ol>
<p>If I would execute next query on Sql Server and Sql Compact (databases I support on local client boxes</p>
<p><strong>SELECT * FROM GuidTest ORDER BY ID</strong></p>
<p>I get (not surprising) next results</p>
<p><a href="http://blog.vuscode.com/wp-content/uploads/2012/04/image1.png"><img style="display: inline;" title="image" src="http://blog.vuscode.com/wp-content/uploads/2012/04/image_thumb1.png" alt="image" width="333" height="91" /></a></p>
<p>Now, I insert the same data to Azure Table (using <a title="http://azurestorageexplorer.codeplex.com/" href="http://azurestorageexplorer.codeplex.com/" target="_blank">Neudisk Azure Storage Explorer</a> is one easy way to do that) and run the same query I get opposite results where row second in sql server is first in Azure table storage.</p>
<p><a href="http://blog.vuscode.com/wp-content/uploads/2012/04/image2.png"><img style="display: inline;" title="image" src="http://blog.vuscode.com/wp-content/uploads/2012/04/image_thumb2.png" alt="image" width="754" height="330" /></a></p>
<h2>Why it happens?</h2>
<p>.NET and Sql Server are having comparing guid values differently – here’s a simple illustration</p>
<pre class="brush: csharp; title;">using System;
using System.Data.SqlTypes;
namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            // .NET guid
            Guid first = Guid.Parse("7240963F-D384-4D78-BADF-A03300F678CC");
            Guid second = Guid.Parse("15DF6719-9671-43D3-BAFA-A03300F678CD");

            // .SQL server guid
            SqlGuid firstSql = new SqlGuid(first);
            SqlGuid secondSql = new SqlGuid(second);

            Console.WriteLine(".NET compare:" + first.CompareTo(second));
            Console.WriteLine("SQL compare:" + firstSql.CompareTo(secondSql));

            Console.ReadKey();
        }
    }
}</pre>
<p>And here’s the result illustrating the difference between .NET and Sql Server.</p>
<p><a href="http://blog.vuscode.com/wp-content/uploads/2012/04/image3.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://blog.vuscode.com/wp-content/uploads/2012/04/image_thumb3.png" alt="image" width="240" height="79" border="0" /></a></p>
<h2>What now?</h2>
<p>In my case, I am probably going to drop Azure Tables and use SQL Azure because I have a single code shared between the cloud and clients where it does the <strong>SelectNewer </strong>on SQL clients so the different results would break the cloud data sync code I have.</p>
<p>The other option I consider is to have a custom code for Azure Tables maybe utilizing the mandatory timestamp values but it is probably going to end as too complicated.</p>
<p>Real bummer Azure team choose a different path to follow then the SQL Server one - It was too god to be true</p>
<p>The post <a href="http://blog.vuscode.com/malovicn/archive/2012/04/14/one-big-problem-with-azure-tables.aspx">One BIG problem with Azure Tables</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/vuscode?a=fhjx0XjVXdw:omjPNAWUg8Q:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=fhjx0XjVXdw:omjPNAWUg8Q:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=fhjx0XjVXdw:omjPNAWUg8Q:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/vuscode?i=fhjx0XjVXdw:omjPNAWUg8Q:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/vuscode/~4/fhjx0XjVXdw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vuscode.com/malovicn/archive/2012/04/14/one-big-problem-with-azure-tables.aspx/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2012/04/14/one-big-problem-with-azure-tables.aspx</feedburner:origLink></item>
		<item>
		<title>What is new in WCF in .NET 4.5 – Task and async</title>
		<link>http://feedproxy.google.com/~r/vuscode/~3/o69fUmj668Q/what-is-new-in-wcf-in-net-4-5-taskt-and-async.aspx</link>
		<comments>http://blog.vuscode.com/malovicn/archive/2012/01/21/what-is-new-in-wcf-in-net-4-5-taskt-and-async.aspx#comments</comments>
		<pubDate>Sat, 21 Jan 2012 09:55:09 +0000</pubDate>
		<dc:creator>administrator</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.vuscode.com/?p=2522</guid>
		<description><![CDATA[<p>.NET 4.5 WCF – unit testable out of the box As I mentioned already in How to get testable WCF code in simplest way? problem with abstracting WCF services occur due to the fact that the service contract is by definition not containing the async members defined and every solution I’ve seen enabling asynchronous calls [...]</p><p>The post <a href="http://blog.vuscode.com/malovicn/archive/2012/01/21/what-is-new-in-wcf-in-net-4-5-taskt-and-async.aspx">What is new in WCF in .NET 4.5 – Task<T> and async</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p>]]></description>
				<content:encoded><![CDATA[<h1></h1>
<h1>.NET 4.5 WCF – unit testable out of the box</h1>
<p>As I mentioned already in <a title="http://blog.vuscode.com/malovicn/archive/2010/11/25/naked-mvvm-simplest-way-to-do-wcf-code.aspx" href="http://blog.vuscode.com/malovicn/archive/2010/11/25/naked-mvvm-simplest-way-to-do-wcf-code.aspx">How to get testable WCF code in simplest way?</a> problem with abstracting WCF services occur due to the fact that the service contract is by definition not containing the async members defined and every solution I’ve seen enabling asynchronous calls to a WCF service adds a certain level of complexity to the code base so therefore I have chosen to use service generated proxy enhanced with some T4 magic creating appropriate interfaces.</p>
<p>I am happy to report that is not true any more and that</p>
<blockquote><p><strong>WCF in .NET 4.5 enables VERY easy asynchronous service calls in a testable manner out of the box.</strong></p></blockquote>
<p>Here’s a <a href="http://bit.ly/WcfTask" target="_blank"><span style="color: #ff0000;"><strong>source code</strong></span></a> of the simplest illustration of what is the point. Usual constraints: works-for-me and take-it-as-an-idea-only.</p>
<p><em>In case all this <strong>async</strong>, <strong>Task&lt;T&gt;</strong> C# 5.0 things are new for you I suggest checking out some of presentations from </em><a href="http://bit.ly/TPLStack" target="_blank"><em>my TPL delicious stack</em></a><em> (especially “Future Directions For C#…” one there)</em></p>
<h2>Server side code</h2>
<p>Let’s stick to the simplest possible sample of a vanilla WCF service having a single operation returning a server time</p>
<pre class="brush: csharp; title:;">using System;
using System.ServiceModel;
using System.Threading.Tasks;

namespace WcfService1
{
    [ServiceContract]
    public interface ITestService
    {
        [OperationContract]
        Task&lt;DateTime&gt; GetServerTimeAsync();
    }
}</pre>
<p>As you can notice there are two interesting moments in the contact definition:</p>
<ul>
<li>Returning type is not DateTime - it is Task&lt;DateTime&gt;</li>
<li>The name of the operation ends with <strong>Async </strong>which is a naming convention for marking new C# 5.0 async methods</li>
</ul>
<p>Implementation of the service contract is equally trivial:</p>
<pre class="brush: csharp; title:;">using System;
using System.Threading.Tasks;

namespace WcfService1
{
    public class TestService : ITestService
    {
        public async Task&lt;DateTime&gt; GetServerTimeAsync()
        {
            return DateTime.Now;
        }
    }
}</pre>
<p>Implementation has three key moments:</p>
<ul>
<li>Method name ends with Async</li>
<li>It returns Task&lt;DateTime&gt;</li>
<li>method has a <strong>async </strong>keyword which allows me to write a simple method body like I would do it normally and return a simple date time and completely forget about Task&lt;T&gt;</li>
</ul>
<p>In other words, thanks to C# 5.0 all I have to do is to replace DateTime with async task&lt;DateTime&gt; and everything else stays the same – AWESOME!.</p>
<h2>Client side code</h2>
<p>I am going to add to the solution simple console application and create a trivial service client file</p>
<pre class="brush: csharp; title:;">using System;
using System.ServiceModel;
using System.Threading.Tasks;
using WcfService1;

namespace ConsoleApplication1
{
    public class TestServiceClient : ClientBase&lt;ITestService&gt;, ITestService
    {
        public Task&lt;DateTime&gt; GetServerTimeAsync()
        {
            return Channel.GetServerTimeAsync();
        }
    }
}</pre>
<p>No magic here: using <a href="http://wcfguidanceforwpf.codeplex.com/releases/view/28192" target="_blank">shared service library</a> I get the service contract on client and use it in combination with ClientBase&lt;T&gt; to create a simple class wrapper implementing via delegation service contract.</p>
<p>Now the class which simulates the one performing a wcf service call in its implementation</p>
<pre class="brush: csharp; title:;">using System;
using System.Threading.Tasks;
using WcfService1;

namespace ConsoleApplication1
{
    public class ServerTimeReader
    {
        private readonly ITestService testService;

        public ServerTimeReader(ITestService testService)
        {
            this.testService = testService;
        }

        public async Task&lt;DateTime&gt; GetTimeAsync()
        {
            return await this.testService.GetServerTimeAsync();
        }
    }
}</pre>
<p>The ServerTimeReader has a ITestService based dependency injected through its constructor. It has a method called GetTimeAsync which <strong><em>awaits </em></strong>the async wcf service call to be finished. All the mumbo jumbo of AMP, events etc. in a single keyword – brilliant.</p>
<p>Now when we have a class invoking a WCF call let’s ramp up IoC container and make a async call to server using the code we wrote so far.</p>
<pre class="brush: csharp; title:;">using System;
using Microsoft.Practices.Unity;
using WcfService1;

namespace ConsoleApplication1
{
    class Program
    {
        private static UnityContainer container;

        static void Main(string[] args)
        {
            container = new UnityContainer();
            container.RegisterType&lt;ITestService, TestService&gt;();

            ReadTime();

            Console.ReadLine();
        }

        private static async void ReadTime()
        {
            var serverTimeReader = container.Resolve&lt;ServerTimeReader&gt;();
            var serverTime = await serverTimeReader.GetTimeAsync();

            Console.WriteLine("Server time:" + serverTime);
        }
    }
}</pre>
<p>It's a console app so the entry point is static Main method which creates a new instance of IoC container (Unity in this sample) and adds to the IoC container mapping of the server side service contract with the service client I wrote</p>
<p>Then client calls a ReadTime method which uses IoC container to resolve ServerTimeReader instance injecting to it during that resolution a service client instance. Then the code awaits the GetTimeAsync method which awaits the service client call which results with a asynchronous call to a server being made and awaited on client.</p>
<p>Once the server returns the result to client the client shows it in console – that’s it.</p>
<p><a href="http://blog.vuscode.com/wp-content/uploads/2012/01/image3.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="image" src="http://blog.vuscode.com/wp-content/uploads/2012/01/image_thumb2.png" alt="image" width="567" height="85" border="0" /></a></p>
<h2>Conclusion</h2>
<p>The simplicity of the code performing fully async call to a WCF service is so brilliant that I am not going to write unit test here for the GetTimeAsync method because it should be quite obvious how to do that. The code is almost the same as it would be if it was written for sync WCF calls and to learn just how to tacklethe TPL/async specific things check out <a href="https://twitter.com/#!/roboblob/status/159771516056244227" target="_blank">this stack overflow page</a> recommended by my friend <a href="blog.roboblob.com" target="_blank">Slobodan Pavkov</a></p>
<p>That’s it folks – hope this will be useful to someone!</p>
<p>The post <a href="http://blog.vuscode.com/malovicn/archive/2012/01/21/what-is-new-in-wcf-in-net-4-5-taskt-and-async.aspx">What is new in WCF in .NET 4.5 – Task<T> and async</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/vuscode?a=o69fUmj668Q:H8HaD3jsUtY:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=o69fUmj668Q:H8HaD3jsUtY:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=o69fUmj668Q:H8HaD3jsUtY:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/vuscode?i=o69fUmj668Q:H8HaD3jsUtY:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/vuscode/~4/o69fUmj668Q" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vuscode.com/malovicn/archive/2012/01/21/what-is-new-in-wcf-in-net-4-5-taskt-and-async.aspx/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2012/01/21/what-is-new-in-wcf-in-net-4-5-taskt-and-async.aspx</feedburner:origLink></item>
		<item>
		<title>Silverlight Data Pager, fake ItemsCount and stored procedures</title>
		<link>http://feedproxy.google.com/~r/vuscode/~3/ewvhwixpcG8/silverlight-data-pager-fake-itemscount-and-stored-procedures.aspx</link>
		<comments>http://blog.vuscode.com/malovicn/archive/2012/01/10/silverlight-data-pager-fake-itemscount-and-stored-procedures.aspx#comments</comments>
		<pubDate>Tue, 10 Jan 2012 19:00:11 +0000</pubDate>
		<dc:creator>administrator</dc:creator>
				<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://blog.vuscode.com/?p=2511</guid>
		<description><![CDATA[<p>Silverlight data pager control in real world What is the better thing one could wish to blog about after a year of blog silence then about something as simple as it gets: How to use Silverlight DataPager control with server side paging? There’s a swarm of blog posts showing how to do that but each [...]</p><p>The post <a href="http://blog.vuscode.com/malovicn/archive/2012/01/10/silverlight-data-pager-fake-itemscount-and-stored-procedures.aspx">Silverlight Data Pager, fake ItemsCount and stored procedures</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p>]]></description>
				<content:encoded><![CDATA[<h1>Silverlight data pager control in real world</h1>
<p><a href="http://blog.vuscode.com/wp-content/uploads/2012/01/image1.png"><img style="margin: 8px; display: inline; float: right;" title="image" src="http://blog.vuscode.com/wp-content/uploads/2012/01/image_thumb.png" alt="image" width="197" height="320" align="right" /></a>What is the better thing one could wish to blog about after a year of blog silence then about something as simple as it gets: <strong>How to use Silverlight DataPager control with server side paging</strong>?</p>
<p>There’s a swarm of blog posts showing how to do that but each one of them I saw does that with WCF data services, using DataService&lt;T&gt; and  entity framework which is really great way to do it except it violates one of the holiest of all enterprise software laws</p>
<blockquote>
<p align="center"><em><strong><span style="font-size: medium;">Thou should obey and use always only and only<br />
stored procedures when accessing the database.</span></strong></em></p>
</blockquote>
<p>Well, as simple as it looks I couldn’t google it with Bing so here’s a blog post showing how to do such a dumb thing. It’s a solution which “works-for-me” but it does feel hacky so take it with a grain of salt and please take it just as an illustration of the idea.</p>
<p><span style="color: #ff0000;"><strong>Source code with the sample used in this post can be downloaded from </strong><a href="http://bit.ly/DataPagerEx" target="_blank"><strong>here</strong></a></span></p>
<h2>What is exactly the problem?</h2>
<p>The problem is that in a given database I can have million rows which I don’t want to download all to client so I ‘m using DataPager control to get page by page of result.</p>
<p>If I would be allowed to use WCF DataService (ex. RIA service) the solution would be quite trivial: my WCF service would expose IQueryable&lt;User&gt;, SL client would use a Linq statement which would transfer over the wire to the server, on the server would be translated to entity framework ORM call and the data flows back in a second.</p>
<p>Unfortunately, I am not allowed to use ORMs so the dynamic SQL based solutions are out of the question.</p>
<h2>The solution</h2>
<p>Solution used in this blog post is a vanilla Silverlight project with one web project containing:</p>
<ul>
<li>a WCF service called UsersService which gets from Silverlight client desired page index and page size and calls the stored procedure using DAL.</li>
<li>A User DTO class which only has 3 properties: Id, Name and Birthdate</li>
<li>UserDAL class which imitates the DAL code simulating the DB with 200 rows in a table and stored procedure which gets result page for given parameters</li>
</ul>
<p>Here's that dummy DAL code</p>
<pre class="brush: csharp; title:;">namespace SilverlightApplication1.Web.Model
{
    public class UserDAL
    {
        private static readonly IList&lt;User&gt; _users = new List&lt;User&gt;();

        static UserDAL()
        {
            for (int i = 0; i &lt; 200; i++)
            {
                _users.Add(new User { Id = i, Name = "User " + i, BirthDate = DateTime.Now.AddDays(-i) });
            }
        }

        public static IList&lt;User&gt; InvokeStoreProcedure(int pageIndex, int pageSize, out int totalCount)
        {
            totalCount = _users.Count;
            int startIndex = pageIndex * pageSize;
            return _users.Skip(startIndex).Take(pageSize).ToList();
        }
    }
}</pre>
<p>On Silverlight project client side we are having:</p>
<ul>
<li>a UserService wcf service proxy</li>
<li>MainPage.xaml containing in markup data grid and data pager</li>
<li>MainPageViewModel class which is view model of the main page</li>
</ul>
<p>Here’s the view xaml which data binds the DataGrid and DataPager to some <strong>Users</strong> collection property:</p>
<pre class="brush: xml; title:;">&lt;UserControl x:Class="SilverlightApplication1.MainPage"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
             Height="600"
             Width="800"&gt;
    &lt;Grid x:Name="LayoutRoot"&gt;
        &lt;Grid.RowDefinitions&gt;
            &lt;RowDefinition Height="*" /&gt;
            &lt;RowDefinition Height="Auto" /&gt;
        &lt;/Grid.RowDefinitions&gt;
        &lt;sdk:DataGrid ItemsSource="{Binding Path=Users, Mode=TwoWay}"
                      AutoGenerateColumns="True" /&gt;
        &lt;sdk:DataPager Grid.Row="1"
                       Source="{Binding Path=Users}" /&gt;

    &lt;/Grid&gt;
&lt;/UserControl&gt;</pre>
<p>&nbsp;</p>
<p>The code behind that xaml only wires up the view model and view:</p>
<pre class="brush: csharp; title:;">namespace SilverlightApplication1
{
    public partial class MainPage
    {
        public MainPage()
        {
            InitializeComponent();

            Loaded += (sender, args) =&gt;
                          {
                              ViewModel = new MainPageViewModel();
                          };
        }

        public MainPageViewModel ViewModel
        {
            get { return (MainPageViewModel) DataContext; }
            set { DataContext = value; }
        }
    }
}</pre>
<p>And here's the view model class:</p>
<pre class="brush: csharp; title:;">using System.ComponentModel;

namespace SilverlightApplication1
{
    public class MainPageViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public MainPageViewModel()
        {
            Users = new UserPagedCollectionView() { PageIndex = 0, PageSize = 25 };
            Users.Init();
        }

        private UserPagedCollectionView users;
        public UserPagedCollectionView Users
        {
            get { return this.users; }
            set { this.users = value; OnPropertyChanged("Users"); }
        }

        public void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}</pre>
<p>No magic happening in a constructor of a view model :</p>
<ul>
<li>sets a view model <strong>Users </strong>property to a instance of <strong>UserPagedCollectionView </strong></li>
<li>invokes the User.Init();</li>
</ul>
<h2>Secret sauce</h2>
<p>Obviously the only thing left not shown is the <strong>UserPagedCollectionView</strong> instance where the magic happens. The class  itself is a bit longer to be pasted so here are just the juicy stuff</p>
<pre class="brush: csharp; title:;">using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using SilverlightApplication1.UsersServiceProxy;

namespace SilverlightApplication1
{
    ///
<summary> /// Endless paged collection view for testing purposes. /// </summary>

    public class UserPagedCollectionView : IEnumerable, IPagedCollectionView,
                                           INotifyPropertyChanged, INotifyCollectionChanged
    {
        private bool isPageChanging;

        private int pageSize;

        private readonly UsersServiceClient proxy;
        readonly Dictionary&lt;int, User&gt; users = new Dictionary&lt;int, User&gt;();

        private int GetPageCount()
        {
            var result = ItemCount / pageSize;
            if (result * pageSize &lt; ItemCount)
            {
                result++;
            }

            return result;
        }

        public UserPagedCollectionView()
        {
            proxy = new UsersServiceClient();
            proxy.GetResultsCompleted += (sender, ea) = &gt;
                                             {
                                                 ItemCount = ea.Result.TotalCount;
                                                 int position = ea.Result.StartIndex;
                                                 foreach (var user in ea.Result.Items)
                                                 {
                                                    if (!users.ContainsKey(position))
                                                    {
                                                        users.Add(position, user);
                                                    }
                                                    position++;
                                                 }
                                                 OnCollectionChanged();
                                             };

            PageChanged += (sender, ea) =&gt; Init();
        }

        public void Init()
        {
           proxy.GetResultsAsync(PageIndex, pageSize);
        }

        public IEnumerator GetEnumerator()
        {
            var startIndex = PageIndex * pageSize + 1;
            var endIndex = startIndex + pageSize;

            var result = new List&lt;User&gt;();

            for (int i = startIndex; i &lt; endIndex; i++)
            {
                if (users.ContainsKey(i))
                {
                    result.Add(users[i]);
                }
            }

            return result.GetEnumerator();
        }
    }
}</pre>
<p>Major points:</p>
<ul>
<li>The class implements the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.ipagedcollectionview(v=VS.95).aspx" target="_blank">IPagedCollectionView</a></li>
<li>It has the Init() method which just calls the service on the server and gets the page of data for a page index and page size with values from a DataPager.</li>
<li>it has a dictionary&lt;int, user&gt; field users which is caching the user data retrieved from server where the key is position.</li>
<li>It has a method GetPageCount() which returns the total number of the pages<br />
(regardless of the number of items data pager  is bind to)</li>
<li>In its constructor it is constructing an instance of the WCF service proxy and it subscribes to the GetResultsCompleted event where it takes the service results (total number of items, current page index and page users and store it all as data pager context) and raise an CollectionChanged event informing the UI that it needs to refresh</li>
<li>Every time a PageChanged event is invoked (clicking one of the arrows, entering the page number etc.) it invokes the Init method  which again makes the call to the server getting the data for the new page.</li>
</ul>
<h2>Result</h2>
<p>That’s it – on initial page load only 25 rows are retrieved but the page count is set to 8 (as 8 x 25 = 200) – exactly what I needed. Clicking the next page gets again from server only the next 25 rows etc. There are no requirements regarding using the ORM and the page data is retrieved using the SP (mocked in this post with a simple in memory method).</p>
<p>Can it be better? Sure, add sorting in game, preemptive loading of the future pages, do not hit the server if you already have the data etc. As I said this is not a production code just an illustration of how I solve a problem I couldn’t find a solution on the net so I hope it will save some time someone in the future – that’s all.</p>
<p><a href="http://blog.vuscode.com/wp-content/uploads/2012/01/image2.png"><img style="display: inline;" title="image" src="http://blog.vuscode.com/wp-content/uploads/2012/01/image_thumb1.png" alt="image" width="713" height="607" /></a></p>
<p>The post <a href="http://blog.vuscode.com/malovicn/archive/2012/01/10/silverlight-data-pager-fake-itemscount-and-stored-procedures.aspx">Silverlight Data Pager, fake ItemsCount and stored procedures</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/vuscode?a=ewvhwixpcG8:WZFVSKjF5Jc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=ewvhwixpcG8:WZFVSKjF5Jc:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=ewvhwixpcG8:WZFVSKjF5Jc:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/vuscode?i=ewvhwixpcG8:WZFVSKjF5Jc:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/vuscode/~4/ewvhwixpcG8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vuscode.com/malovicn/archive/2012/01/10/silverlight-data-pager-fake-itemscount-and-stored-procedures.aspx/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2012/01/10/silverlight-data-pager-fake-itemscount-and-stored-procedures.aspx</feedburner:origLink></item>
		<item>
		<title>Naked MVVM – simplest way to do WCF code</title>
		<link>http://feedproxy.google.com/~r/vuscode/~3/Hn8Jl4furME/naked-mvvm-simplest-way-to-do-wcf-code.aspx</link>
		<comments>http://blog.vuscode.com/malovicn/archive/2010/11/25/naked-mvvm-simplest-way-to-do-wcf-code.aspx#comments</comments>
		<pubDate>Thu, 25 Nov 2010 01:11:33 +0000</pubDate>
		<dc:creator>administrator</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://</guid>
		<description><![CDATA[<p>How to get testable WCF code in simplest way? What is the problem? We all know that creating an instance of service proxy inside of the view model makes writing tests for the view model very hard because during the unit test run we don’t have usually the web service on the other side or [...]</p><p>The post <a href="http://blog.vuscode.com/malovicn/archive/2010/11/25/naked-mvvm-simplest-way-to-do-wcf-code.aspx">Naked MVVM – simplest way to do WCF code</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p>]]></description>
				<content:encoded><![CDATA[<h1>How to get testable WCF code in simplest way?</h1>
<h2>What is the problem?</h2>
<p>We all know that creating an instance of service proxy inside of the view model makes writing tests for the view model very hard because during the unit test run we don’t have usually the web service on the other side or even if we do it slows down web tests.</p>
<p>You know how they say</p>
<blockquote><p><em>“Unit test is the test which runs without any problem with network cable unplugged”</em></p></blockquote>
<p>Like the previous post about <a href="http://blog.vuscode.com/malovicn/archive/2010/11/07/naked-mvvm-simplest-possible-mvvm-approach.aspx" target="_blank">simplest possible way to do MVVM</a>, the solution for this problem was covered in so many blog posts that even I am personally aware of a couple of cool and ‘frameworkish’ ways to solve it: use WCF behaviors, <a href="http://wcfguidanceforwpf.codeplex.com/releases/view/28192#DownloadId=70421" target="_blank" rel="nofollow">create your own ChannelFactory&lt;T&gt;</a> with either <a href="http://kozmic.pl/archive/2009/08/09/making-asynchronous-wcf-calls-without-svcutil.aspx" target="_blank" rel="nofollow">sync call in separate thread</a> <a href="http://blog.roboblob.com/2010/04/11/unit-testable-wcf-web-services-in-mvvm-and-silverlight-4/" target="_blank" rel="nofollow">or IAsyncResult based approach</a> and (my personal favorite) <a href="http://wcfproxygenerator.codeplex.com/" target="_blank">hack the Visual Studio proxy generator</a>. I’m sure there are at least 24 more solutions to do this <img class="wlEmoticon wlEmoticon-smile" style="border-style: none;" src="http://blog.vuscode.com/blogs/blogs/malovicn/wlEmoticon-smile_261876A6.png" alt="Smeško" /></p>
<p>Still, there are two main problems with all the approaches I saw which belong to one of the next two groups:</p>
<ol>
<li>They deal purely with async based scenarios.<br />
If I have a service with a method GetForecast(DateTime date), I don’t want to maintain another interface just to get a way to make async call.</li>
<li>They are rocket science type of solutions<br />
We are all geeks and like nice and shiny toys, but what about regular folks like me and a lot of the readers? Is there a really simple way to do this for “us others”?</li>
</ol>
<p>Luckily, I think I found one which is definitely not the coolest one and 100% can be enhanced etc, but it is the one which proved to me in my day to day WPF/SL coding to be the easiest one “to grok and use”.</p>
<h2>Conceptual solution</h2>
<p><a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_7E05C786.png"><img title="image" style="display: inline; float: right;" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_683BDF29.png" alt="image" width="177" height="240" align="right" /></a>The solution follows next design goals:</p>
<ul>
<li>doesn’t require any typing</li>
<li>it is using Visual Studio proxy generated with “Add service..”  menu action</li>
<li>it is using the well documented MethodAsync() invoker, MethodCompleted event subscriber pattern</li>
<li>it is using T4 to auto generate code which enhances the VS generated service proxy</li>
<li>every service proxy file follows naming convention of ending with word “Proxy”</li>
</ul>
<p>A year ago, I have blogged in great detail about the <a href="http://blog.vuscode.com/malovicn/archive/2009/11/01/design-for-testability-wcf-proxies.aspx" target="_blank">unfortunate fact of ServiceClient generated in service proxy  not implementing an IServiceClient interface</a>. In case you want to understand what my solution do under the hood go read that blog post now and then continue reading this one. In case “you don’t care how it works as long it is working” here’s a very short summary for you:</p>
<p>ServiceClient generated by proxy generator is marked as partial class.That allows me to create another partial class with same name and namespace outside of proxy which only purpose is to hook the IServiceClient interface I generated manually based on the ServiceClient itself.</p>
<p>In the original blog post I do it manually which ended as a <a href="http://en.wiktionary.org/wiki/pain_in_the_ass" target="_blank" rel="nofollow">PITA</a> due to the fact that every change of service contract one has to keep updated the interface. As a result of noticing that I waste a lot of time on that, I spent 20 minutes and created a simple T4 class  which does that automatically for me.</p>
<p><span style="color: #ff0000; font-size: medium;"><strong>You can download the source code of end solution </strong></span><a href="http://cid-e8cc105df7380bc5.office.live.com/self.aspx/Blog.vuscode.com/MVVMWCF.zip"><span style="color: #ff0000; font-size: medium;"><strong>here</strong></span></a><span style="color: #ff0000; font-size: medium;"><strong>.</strong></span></p>
<h2>Before</h2>
<p>Project structure is very trivial. It is vanilla Silverlight project which has a TimerService WCF service doing just this</p>
<pre class="brush: csharp; title:;">using System;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace NakedMVVM.Web
{
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class TimerService
    {
        [OperationContract]
        public string GetTime()
        {
            return "Yes it works on " + DateTime.Now;
        }
    }
}</pre>
<p>Once we add a service proxy to NMVVM_WCF project (<strong>NOTE </strong>that proxy name ends with Proxy)</p>
<p><a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_26C12CD0.png"><img title="image" style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_40B4ECF2.png" alt="image" width="597" height="484" border="0" /></a></p>
<p>We can happily write now our <em>demoware</em> code “…</p>
<pre class="brush: csharp; title:;">namespace NMVVM_WCF
{
    using System.ComponentModel;
    using System.Runtime.Serialization;

    using NMVVM_WCF.TimerServiceProxy;

    public class MainPageViewModel : INotifyPropertyChanged
    {
        public MainPageViewModel()
        {

            TimerServiceClient client = new TimerServiceClient();
            client.GetTimeCompleted += OnGetTimeCompleted;
            client.GetTimeAsync();
        }

        private void OnGetTimeCompleted(object sender, GetTimeCompletedEventArgs e)
        {
            Message = e.Result;
        }

        [DataMember]
        private string message;

        public string Message
        {
            get
            {
                return this.message;
            }
            set
            {
                if (this.message == value)
                {
                    return;
                }
                this.message = value;
                this.OnPropertyChanged("Message");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}</pre>
<p>Nothing wrong with this code per se, just it makes unit testing of the view model much harder task then it should be…</p>
<h2>After</h2>
<p>To fix this problem, let’s do next 2 steps:</p>
<ul>
<li>download the T4 template file (no need to look in what it contains at all) <a title="T4 template" href="http://bit.ly/t4wcf" target="_blank" rel="nofollow">from here</a><strong><span style="color: #ff0000;"> </span></strong>.</li>
<li>add the file to the root folder of NMVVM_WCF project using VS IDE “Add existing item”</li>
</ul>
<p>As a result of this activities t4 template was executed and a file with ClientEnhancer was auto-generated with next content</p>
<pre class="brush: csharp; title:;">	namespace NMVVM_WCF.TimerServiceProxy
	{
		public partial interface ITimerServiceClient
		{
			#region Events
			event System.EventHandler GetTimeCompleted;
			event System.EventHandler OpenCompleted;
			event System.EventHandler CloseCompleted;
			#endregion Events

			#region Methods
			 void GetTimeAsync();
			 void GetTimeAsync(object userState);
			 void OpenAsync();
			 void OpenAsync(object userState);
			 void CloseAsync();
			 void CloseAsync(object userState);
			#endregion Methods
		}

		public partial class TimerServiceClient  : ITimerServiceClient
		{
		}
	}</pre>
<p>As you can guess, that's complete code I was coding by hand and keep it updated manually with service contract changes. Having this in place it is quite easy to change ViewModel to accept the IServiceClient as a constructor parameter</p>
<pre class="brush: csharp; title:;">        public MainPageViewModel(ITimerServiceClient client)
        {
            client.GetTimeCompleted += OnGetTimeCompleted;
            client.GetTimeAsync();
        }

        private void OnGetTimeCompleted(object sender, GetTimeCompletedEventArgs e)
        {
            Message = e.Result;
        }</pre>
<p>The only thing left is to update the MainPage.xaml.cs file</p>
<pre class="brush: csharp; title:;">namespace NMVVM_WCF
{
    using NMVVM_WCF.TimerServiceProxy;

    public partial class MainPage
    {
        public MainPage()
        {
            InitializeComponent();
            DataContext = new MainPageViewModel(new TimerServiceClient());
        }
    }
}</pre>
<p>And that’s it – application works like it was and we have a highly testable view model using only service client interface which is easy to stub/mock.</p>
<p>Having a hard time figuring out path from “before” to “after”? Here’s a short video showing step by step things just described</p>
<div class="wlWriterEditableSmartContent" style="margin: 0px auto; padding: 0px; width: 587px; float: none; display: block;" id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:402f14bb-9ced-4e4f-b619-afeb99842d64">
<div><a href="http://www.youtube.com/watch?v=g2qoQ_LVUJw&amp;feature=youtube_gdata_player" target="_new"><img style="border-style: none;" src="http://blog.vuscode.com/blogs/blogs/malovicn/video3c8774ace813_5C88AA1B.jpg" alt="" /></a></div>
</div>
<p><span style="color: #ff0000; font-size: medium;"><strong>You can download the source code of end solution </strong></span><a href="http://cid-e8cc105df7380bc5.office.live.com/self.aspx/Blog.vuscode.com/MVVMWCF.zip"><span style="color: #ff0000; font-size: medium;"><strong>here</strong></span></a><span style="color: #ff0000; font-size: medium;"><strong>.</strong></span></p>
<h2>Aftermath</h2>
<p>My own version of this T4 template, beside the T4 template code used in this blog post is also auto filling IoC container with mappings to all of service clients and its interfaces generated by template. That auto generation combined with auto MVVM wire up I described in first post allow me to have this “TDD enabling of WCF service proxies” fully automated.</p>
<p>I decided not to put that additional template code so it won’t bloat the post with IoC containers etc, but it is VERY easy to modify and customize the T4 template – even if you never did it spend 20 minutes looking at .tt file I shared for this post and I guarantee you – you’ll get it.</p>
<p>The only downside of this approach is that you have to manually drop the T4 template file to every project with service proxies which in my case is not the problem at all – I add it once and after that it keeps things in sync on its own.</p>
<p>I am really not sure why Microsoft is not doing this in the default proxy generation process – it is not breaking anything or damaging backward compatibility and it enables easy testing. I was experimenting <a href="http://wcfproxygenerator.codeplex.com/" target="_blank">modifying the Visual Studio proxy generator</a> myself, but I decided to abandon it (even it was working at the end) due to required registry modifications etc. In my opinion, dropping one file in project without any other requirements to make it testable is more transparent then other approaches and everyone could do this.</p>
<p>What do you think about it? Is it simple enough?</p>
<p>The post <a href="http://blog.vuscode.com/malovicn/archive/2010/11/25/naked-mvvm-simplest-way-to-do-wcf-code.aspx">Naked MVVM – simplest way to do WCF code</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/vuscode?a=Hn8Jl4furME:0byejiOgoIk:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=Hn8Jl4furME:0byejiOgoIk:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=Hn8Jl4furME:0byejiOgoIk:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/vuscode?i=Hn8Jl4furME:0byejiOgoIk:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/vuscode/~4/Hn8Jl4furME" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vuscode.com/malovicn/archive/2010/11/25/naked-mvvm-simplest-way-to-do-wcf-code.aspx/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2010/11/25/naked-mvvm-simplest-way-to-do-wcf-code.aspx</feedburner:origLink></item>
		<item>
		<title>Naked MVVM–simplest possible MVVM approach</title>
		<link>http://feedproxy.google.com/~r/vuscode/~3/Edk5urA46Qk/naked-mvvm-simplest-possible-mvvm-approach.aspx</link>
		<comments>http://blog.vuscode.com/malovicn/archive/2010/11/07/naked-mvvm-simplest-possible-mvvm-approach.aspx#comments</comments>
		<pubDate>Sun, 07 Nov 2010 11:54:00 +0000</pubDate>
		<dc:creator>administrator</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://</guid>
		<description><![CDATA[<p>How to do MVVM in simplest possible way? Yes, I am aware that there are at least 50 “How to do MVVM” blog posts and well known frameworks: prism, MVVM Light, Caliburn etc. Still, my friend Slobodan Pavkov convinced me to write a post and explain the approach I am personally using in my code, [...]</p><p>The post <a href="http://blog.vuscode.com/malovicn/archive/2010/11/07/naked-mvvm-simplest-possible-mvvm-approach.aspx">Naked MVVM–simplest possible MVVM approach</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p>]]></description>
				<content:encoded><![CDATA[<div>
<h1>How to do MVVM in simplest possible way?</h1>
<div>Yes, I am aware that there are at least 50 “How to do MVVM” blog posts and well known frameworks: <a title="Prism" rel="nofollow" href="http://compositewpf.codeplex.com/" target="_blank">prism</a>, <a title="MVVM LIght toolkit" rel="nofollow" href="http://mvvmlight.codeplex.com/" target="_blank">MVVM Light</a>, <a title="Caliburn micro" rel="nofollow" href="http://caliburnmicro.codeplex.com/" target="_blank">Caliburn</a> etc. Still, my friend <a title="Slobodan Pavkov" href="http://blog.roboblob.com/" target="_blank">Slobodan Pavkov</a> convinced me to write a post and explain the approach I am personally using in my code, because (as he believes) it is so simple that it can be useful to someone -  so here I am - writing it down.</div>
<div>Idea is so simple that I guess it is very possible someone already blogged about it and if so please let me know so I could link that blog post here. I presume you know what MVVM already is – if not go read some of the hundreds blog posts about that and once you get it come back. My sample is done in WPF (as that is <a href="http://blog.vuscode.com/malovicn/archive/2010/06/02/5-reasons-why-silverlight-sucks-in-lob-compared-to-wpf.aspx" target="_blank">my LOB platform of choice</a>) but it works without any changes in Silverlight too.</div>
<div>As all MVVM framework I had to pick a name reflecting the spirit of my “framework” and I ended with “Naked MVVM” because it reflects <strong>design principles</strong> I respect:</div>
<ol>
<li>
<div>No base classes of any kind required for framework</div>
</li>
<li>
<div>No interfaces of any kind required for framework</div>
</li>
<li>
<div>No attributes of any kind required for framework</div>
</li>
<li>
<div>View first – Blend friendly &amp; simple composition</div>
</li>
<li>
<div>IoC enabled</div>
</li>
<li>
<div>Works out of box as much as possible</div>
</li>
</ol>
<h2>Basic ideas behind “Naked MVVM”</h2>
<h3>Scenario</h3>
<div>Simple MVVM framework requires simple possible problem: show in MVVM way a text box showing current date. That’s it – let’s roll.</div>
<h2><span style="color: #ff0000; font-size: medium;">You can download the source code of end solution </span><a title="source code" rel="nofollow" href="http://cid-e8cc105df7380bc5.office.live.com/self.aspx/Blog.vuscode.com/YAMVVM.zip" target="_blank"><span style="color: #ff0000; font-size: medium;">here</span></a><span style="color: #ff0000; font-size: medium;">.</span></h2>
<h2>No base classes, interfaces and attribute</h2>
<div>Usual implementations of MMVM I’ve seen usually have ViewModel&lt;TView&gt; base class and/or some form of IView view abstraction etc.</div>
<div>Here’s how View looks like in my approach</div>
<pre class="brush: csharp; title:;">namespace NakedMVVM
{
    public partial class MainWindowView
    {
        public MainWindowView()
        {
            InitializeComponent();
        }
    }
}</pre>
<div>And here is the view model containing all of the necessary requirements from my Naked MVVM framework</div>
<pre class="brush: csharp; title:;">namespace NakedMVVM
{
    public class MainWindowViewModel
    {
    }
}</pre>
<div>As you can tell from the code above, there are <strong>ZERO </strong>requirements from view and view model.</div>
<h2>Wiring up the view and the view model</h2>
<div>s you already know, the whole MVVM pattern is based on the idea that view data binds to a view model which then talks to a model.</div>
<div><a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_1E79185F.png"><img style="display: inline;" title="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_5FC41AF8.png" alt="image" width="640" height="84" /></a></div>
<div>A lot of samples I’ve seen, define some form of view abstraction which should enable view model to communicate with view on framework level.</div>
<div>All of those samples ignore one simple but VERY IMPORTANT fact – there is such abstraction already baked in .NET – <a rel="nofollow" href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.aspx" target="_blank"><strong>FrameworkElement</strong></a>. Every view (user control, window etc.) inherits from the FrameworkElement and can be casted to it. The reason why I picked it up is that the framework element has a DataContext member (to bad it is not defined in some interface so I could replace FrameworkElement with it). Setting a user control data context to some value results with all of the controls in that window/user control being bounded to the same value.</div>
<div>To codify that thought...</div>
<pre class="brush: csharp; title:;">namespace NakedMVVM
{
    using System.Windows;

    public class MainWindowViewModel
    {
        public MainWindowViewModel(FrameworkElement frameworkElement)
        {
            frameworkElement.DataContext = this;
        }
    }
}</pre>
<div>The problem here is how an IoC container (one of the requirements above is to use IoC) can resolve this generic FrameworkElement constructor parameter? That question is exactly the reason why we have all of the IView and IView&lt;T&gt; in the MVVM blog posts. To me that well documented approach is an overkill because we create entities just to hold our infrastructure. Much better approach could be to resolve a framework element from a IoC container using a well known key. There are many way how to do that but let here illustrate it in the simplest to digest form using the ServiceLocator.</div>
<pre class="brush: csharp; title:;">namespace NakedMVVM
{
    using System.Windows;

    using Framework;

    public class MainWindowViewModel
    {
        public MainWindowViewModel()
        {
            var frameworkElement = ServiceLocator.IoC.Resolve("MainView");
            frameworkElement.DataContext = this;
        }
    }
}</pre>
<div>As you can see here, view model becomes a data context of a view without any artificial code artifacts created to enable that. If I wouldn’t have to respect my <strong>design principle #1 </strong>“No base classes of any kind required” I could extract this class to base view model class and have it applicable on all view models.</div>
<pre class="brush: csharp; title:;">namespace NakedMVVM
{
    using System.Windows;
    using Framework;

    public class MainWindowViewModel : ViewModel
    {
    }

    public abstract class ViewModel
    {
        public ViewModel()
        {
            var frameworkElement = ServiceLocator.IoC.Resolve(this.GetType().Name.Replace("Model",""));
            frameworkElement.DataContext = this;
        }
    }
}</pre>
<div>Too bad I am not allowed to do that so I am again deleting all of the changes in this ViewModel and restore it back to be an empty class with no base class and no wire-up code in it. To see what I do in my code you would have to be patient for a little bit more because I need to explain first may way of …</div>
<h2>Filling the IoC container</h2>
<div>In most MVVM samples, there is a bootstrapper class where developer enlist all of the IoC mappings. In this example it could be something like this</div>
<pre class="brush: csharp; title:;">using System.Windows;

namespace NakedMVVM
{
    using Framework;

    public partial class App : Application
    {

        public App()
        {
            ServiceLocator.IoC.RegisterType&lt;FrameworkElement,MainWindowView&gt;("MainWindowView");
        }
    }
}</pre>
<div><a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_45EFE4C9.png"><img style="float: right; display: inline;" title="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_5A090152.png" alt="image" width="240" height="216" align="right" /></a>Just by looking at this single line of code, it <strong>becomes obvious</strong> that:</div>
<ul>
<li>I have to do the same thing for every user control/window I have</li>
<li>I map always framework element to a user control/windows</li>
<li>The key I use to store it in IoC is the same as the name of user control/window</li>
</ul>
<div>Every WPF/SL developer I know (including me) when doing MVVM follows the next naming convention:</div>
<ul>
<li>every user control is suffixed with “View” and</li>
<li>every view model of a control is suffixed with “ViewModel”</li>
</ul>
<div>In concrete case of the sample used in this blog post, user control is named <strong>MainWindowView </strong>and her view model class <strong>MainWindowViewModel</strong></div>
<div>If we combine the 3 obvious facts given above with the naming convention we could easily come to the same idea as I did:</div>
<blockquote>
<div>“Iterate all of the types in current assembly. Each one of them which name ends with “View” map as framework element using the full type name as a key. Each one of them which name ends with a “ViewModel” map as object with a full type name as a key.”</div>
</blockquote>
<div>Translating that thought into a C# code class IoCBuilder in this sample was created containing this</div>
<pre class="brush: csharp; title:;">namespace Framework
{
    using System;
    using System.Reflection;
    using System.Windows;
    using System.Windows.Controls;

    public static class IoCBuilder
    {
        public static void CollectViewAndViewModelMappings()
        {
            foreach (var type in Assembly.GetCallingAssembly().GetTypes())
            {
                var typeIsUserControl = type.BaseType == typeof(UserControl);
                if (typeIsUserControl)
                {
                    var typeIsView = type.Name.EndsWith("View", StringComparison.InvariantCultureIgnoreCase);
                    if (typeIsView)
                    {
                        ServiceLocator.IoC.RegisterType(typeof(FrameworkElement), type, type.FullName);
                    }
                }
                else
                {
                    var typeIsViewModel = type.Name.EndsWith("ViewModel", StringComparison.InvariantCultureIgnoreCase);
                    if (typeIsViewModel)
                    {
                        ServiceLocator.IoC.RegisterType(typeof(object), type, type.FullName);
                    }
                }
            }
        }
    }
}</pre>
<div>Now when we have this code in place, we can replace the explicit mappings from our bootstrapper class to a framework call</div>
<pre class="brush: csharp; title:;">namespace YAMVVM
{
    using System.Windows;
    using Framework;

    public partial class App : Application
    {
        public App()
        {
            IoCBuilder.CollectViewAndViewModelMappings();
        }
    }
}</pre>
<div>Major upside of this approach (at least for me) is that respects design principle #6 and allows me to just add a view and a view model without thinking about IoC mappings etc.</div>
<h2>My way of wiring up view and view model</h2>
<div>Having in mind the content of IoC container and design principle #4 (Blendable framework) after a lot of experimenting I’ve realized that the behavior is the most suitable way of doing the wire up.</div>
<div>The behavior itself is quite trivial and it it reflecting the same approach as shown above in explicit wire up sample code.</div>
<pre class="brush: csharp; title:;">namespace Framework.Behaviors
{
    using System.Windows;
    using System.Windows.Interactivity;
    using Framework;

    public class AutoWireUpViewModelBehavior : Behavior&lt;UIElement&gt;
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            var view = (FrameworkElement)this.AssociatedObject;
            var viewModelName = string.Format("{0}Model", view.GetType().FullName);
            var viewModel = ServiceLocator.IoC.Resolve&lt;object&gt;(viewModelName);
            view.DataContext = viewModel;
        }
    }
}</pre>
<div>Code is quite simple: pointer to a user control is being passed to a behavior. Following the naming convention explained above, I add the “Model”to the name of the view so I would get the specific view model key which I use to resolve view model from a container. Once resolved view model, I set to a DataContext of a user control being passed to a behavior. Same approach as the one in explicit sample, just encapsulated in the behavior.</div>
<div>Now when there is a framework level behavior, only thing a designer has to do to wire up a view and view model (I emphasize here again that both of them are following the #1-#3 principles and not having any base class, interface etc) is to fire up a blend and just drag&amp;drop the AutoWireUp behavior to a control.</div>
<div><a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_0ABC08FE.png"><img style="display: inline;" title="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_3B6F10A9.png" alt="image" width="164" height="240" /></a><a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_6ECAD405.png"><img style="margin: 0px 0px 0px 10px; display: inline;" title="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_152CB751.png" alt="image" width="240" height="148" /></a></div>
<div>Off course, for us developers executing next R# snippet and resolving namespaces is maybe more suitable solution</div>
<pre class="brush: xml; title:;">    &lt;i:Interaction.Behaviors&gt;
        &lt;Framework:AutoWireUpViewModelBehavior /&gt;
    &lt;/i:Interaction.Behaviors&gt;</pre>
<div>Regardless of which way you would prefer, the end goal is achieved: view and view model are wired up on a unobtrusive way removing the need for infrastructure bloat used usually to enable that.</div>
<h2>Putting it to work</h2>
<div>If we run our sample, everything will work just fine (even with view and view model being completely empty) except we won’t see the current date on the screen so we can’t know for sure if it work or not, aren’t we?</div>
<div>Let modify the view to its final state</div>
<pre class="brush: xml; title:;">&lt;Window x:Class="NakedMVVM.MainWindowView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:Framework="clr-namespace:Framework.Behaviors;assembly=Framework"
        xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"&gt;
    &lt;i:Interaction.Behaviors&gt;
        &lt;Framework:AutoWireUpViewModelBehavior /&gt;
    &lt;/i:Interaction.Behaviors&gt;
    &lt;Grid&gt;
        &lt;TextBlock Text="{Binding HeadingCaption}" /&gt;
    &lt;/Grid&gt;
&lt;/Window&gt;</pre>
<div>and the view model</div>
<pre class="brush: csharp; title:;">namespace NakedMVVM
{
    using System;
    using System.ComponentModel;

    public class MainWindowViewModel : INotifyPropertyChanged
    {
        public MainWindowViewModel()
        {
            HeadingCaption = "Yes it works on " + DateTime.UtcNow;
        }

        private string headingCaption;

        public string HeadingCaption
        {
            get { return this.headingCaption; }
            set
            {
                this.headingCaption = value;
                this.OnPropertyChanged("HeadingCaption");
            }
        }

        #region The usual INPC implementation
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion    }
    }
}</pre>
<div>Run the app</div>
<div><a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_6666FEAE.png"><img style="border-width: 0px; padding-top: 0px; padding-right: 0px; padding-left: 0px; display: inline; background-image: none;" title="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_3E544F8F.png" border="0" alt="image" width="436" height="98" /></a></div>
<div>See, it works <img class="wlEmoticon wlEmoticon-smile" src="http://blog.vuscode.com/blogs/blogs/malovicn/wlEmoticon-smile_442EF328.png" alt="Smeško" /></div>
<div><span style="color: #ff0000; font-size: medium;">You can download the source code of end solution </span><a title="source code" rel="nofollow" href="http://cid-e8cc105df7380bc5.office.live.com/self.aspx/Blog.vuscode.com/YAMVVM.zip" target="_blank"><span style="color: #ff0000; font-size: medium;">here</span></a><span style="color: #ff0000; font-size: medium;">.</span></div>
<div>What do you think? Have you seen this approach in whole somewhere? Does it makes sense to you or it look to you just-another-fluffy-pattern-thing?</div>
<div>Looking forward to hear your thoughts on my approach!</div>
</div>
<p>The post <a href="http://blog.vuscode.com/malovicn/archive/2010/11/07/naked-mvvm-simplest-possible-mvvm-approach.aspx">Naked MVVM–simplest possible MVVM approach</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/vuscode?a=Edk5urA46Qk:0byejiOgoIk:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=Edk5urA46Qk:0byejiOgoIk:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=Edk5urA46Qk:0byejiOgoIk:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/vuscode?i=Edk5urA46Qk:0byejiOgoIk:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/vuscode/~4/Edk5urA46Qk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vuscode.com/malovicn/archive/2010/11/07/naked-mvvm-simplest-possible-mvvm-approach.aspx/feed</wfw:commentRss>
		<slash:comments>23</slash:comments>
		<feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2010/11/07/naked-mvvm-simplest-possible-mvvm-approach.aspx</feedburner:origLink></item>
		<item>
		<title>Windows LiveID – Microsoft red headed stepchild?</title>
		<link>http://feedproxy.google.com/~r/vuscode/~3/w04Sg-5N3GI/windows-liveid-microsoft-red-headed-stepchild.aspx</link>
		<comments>http://blog.vuscode.com/malovicn/archive/2010/06/26/windows-liveid-microsoft-red-headed-stepchild.aspx#comments</comments>
		<pubDate>Sat, 26 Jun 2010 11:46:00 +0000</pubDate>
		<dc:creator>administrator</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Smart Client]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://</guid>
		<description><![CDATA[<p>I personally believe Microsoft is missing (if not already missed) the opportunity to monetize serious potential of Windows LiveID. For years already, there are more then half a billion user accounts (which surpasses current number of Facebook accounts) which Microsoft could’ve use to create serious advertisement revenue the same way Facebook is doing now. The [...]</p><p>The post <a href="http://blog.vuscode.com/malovicn/archive/2010/06/26/windows-liveid-microsoft-red-headed-stepchild.aspx">Windows LiveID – Microsoft red headed stepchild?</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>I personally believe Microsoft is missing (if not already missed) the opportunity to monetize serious potential of Windows LiveID. </p>
<p>For years already, there are more then half a billion user accounts (which surpasses current number of Facebook accounts) which Microsoft could’ve use to create serious advertisement revenue the same way Facebook is doing now. The value proposition for users is the fact that they don’t have to remember “yet another user name and password” which is a definite win – at least for me. For identity holder (Microsoft/Facebook), getting information on activities user makes across the web is clearly a win from marketing and advertisement perspective. It is such an obvious case of win-win scenario, that I don’t want to spend any more words on selling it to you, dear reader.</p>
<p>Microsoft (as with many other cool things – Ajax etc) pioneered the Sing sign-on concept more then a decade ago but didn’t do much with it allowing to OpenID, OAuth, Facebook Connect etc to emerge as industry standards. </p>
<p>The reason behind LiveID failure to reach world domination in identity space is related to the poor developer story which prevented wider adoption of the LiveID as “the one online identity”./ Having in mind we are speaking about the Microsoft&#160; as developer oriented company I find that to be quite hilarious in one hand and a proof of lack of Microsoft strategic vision in this area. In other words, I believe no one cared(s) in Microsoft so much about getting the benefits from Windows LiveID as some startup might try to (<em>who said Facebook Connect?</em>).</p>
<h2>Why Microsoft failed to dominate with Windows LiveID</h2>
<p>Here are couple of reasons why I think thinks are like they are right now…</p>
<p>Year 2003, Microsoft attempts rolling out LiveID (at that time called Passport) to couple of big companies (<a href="http://en.wikipedia.org/wiki/Windows_Live_ID" target="_blank">including eBay and Monster</a>) which dies in 2004. Whatever the reasons were, loosing two of such a big adopters in 2004 is (IMHO) VERY stupid because if it did happen I bet we would be all using LiveID across the web right now “with not much of an alternative”. </p>
<p>Year 2006, MS <a href="http://blog.beuchelt.org/2006/06/16/STS+For+PassportWindows+Live+ID.aspx" target="_blank">had a STS</a> running on <a href="http://sts.labs.live.com">http://sts.labs.live.com</a>. I can not imagine a reason why would something like that die but there’s no such thing today.     <br />Having an STS (web service auth token issuer) is all I would personally care about in order to adopt LiveID in my apps.</p>
<p>On Mix 2008, they announced Windows LiveID SDK <u><strong>CTP</strong></u> which was up until yesterday the only way of integrating Windows LiveID with client apps and sites. They have also announced on the same mix that <a href="http://blogs.msdn.com/b/mvplead/archive/2009/04/28/windows-live-id-becomes-an-openid-provider.aspx" target="_blank">LiveID would become OpenID provider</a>, but that <a href="http://winliveid.spaces.live.com/blog/cns!AEE1BB0D86E23AAC!1791.entry" target="_blank">didn’t long last too</a>. </p>
<p>Beside this efforts, Microsoft was trying also to pitch LiveID in parallel using its own strongest weapon: Windows. </p>
<p>Microsoft's <a href="http://en.wikipedia.org/wiki/Windows_XP">Windows XP</a> has an option to link a Windows user account with a Windows Live ID (appearing with its former names), logging users into Windows Live ID whenever they log into Windows. To me that sounds very nice (I’ve already auth myself logging on my PC and established a trust relationship which for most of the web sites out there should be sufficient). The only problems with this is that is almost unknown feature. I did a smoke test asking 10 people I know which use Windows Live Messenger on day to day basis if they use it – none of them even knew about it. I don’t even have clear understanding how this thing gets installed other then guessing it gets bundled in Live essentials installer .</p>
<p>Then, there is CardSpace which is industry correct and secure way of handling our online identity information. All great, except for the fact that it is quite a mystery “how to use it” <img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://blog.vuscode.com/blogs/blogs/malovicn/wlEmoticonsmile_15CD3BE0.png" />. In 2007, there was a beta of&#160; <a href="http://winliveid.spaces.live.com/blog/cns!AEE1BB0D86E23AAC!931.entry?sa=426162015" target="_blank">CardSpace LiveID integration</a> but after that nothing happens.CardSpace being a part of most of Windows apps is such a untapped potential that it is hart for me to believe that no one is trying to utilize it more seriously.</p>
<h2>Couple of things I hope Microsoft will do with LiveID in the future</h2>
<p>Microsoft still has some chance to emerge as one of the leaders in identity space but to do that they might consider doing some of the next things: </p>
<ul>
<li><strong>promote “LiveID” to become a 1st grade citizen in Windows.        <br /></strong>      <br />Ask for LiveID to be entered during the windows installation process (most of us have it anyhow). Windows Live service would then (during the install process itself) issue Card Space managed card for a user. Right from the moment system would be installed, that card should be used on every LiveID site.       <br />Even better put that card on my Live SkyDrive so it could roam with me while I work on different computers. If not possible to be built in Windows (ether Win7 SP1 or Win8), can we at least consider building it in Internet Explorer 9?      </p>
<p>I know this could be probably breaking some monopoly law, but lets face it – MS didn’t become what it is playing fair but playing bold.       <br />Apple integrating MobileMe and Chrome integrating google bookmarks and Flash are doing exactly that.       </li>
<li><strong>Use LiveID on <u>ALL</u> of the Microsoft sites. No excuses. Period.         <br /></strong>Just check out <a href="http://windowsteamblog.com/windows_live/b/developer/archive/2010/06/25/messenger-connect-making-your-data-more-portable-while-retaining-control-over-its-use.aspx" target="_blank">last post on windowsteamblog.com</a> which (ironic isn’t it) introduces newest LiveID “Messenger Connect” API.       <br />To post a comment you need to Sign In       <br /><img style="border-right-width: 0px; margin: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_1ED9C761.png" width="244" height="31" />       <br />but that is not using the LiveID&#160; <img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://blog.vuscode.com/blogs/blogs/malovicn/wlEmoticonsmile_15CD3BE0.png" />       <br /><a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_7A4839DC.png"><img style="border-right-width: 0px; margin: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_6B315B02.png" width="208" height="244" /></a>
<p>If you don’t trust in it, why should we?       </li>
<li><strong>Spread it across the web similar to Facebook ‘Like’ button (‘Post with Messenger’)&#160; <br /></strong>Here’s a sample of how Bing can be used to collect ‘Likes’ by adding a ‘Post With Messenger button’ which would send it to people on messenger contact list andor Facebook, MySpace etc… Even this would end with forwarding it to Facebook as ‘Like’ there is still value in collecting those data associated with LiveID…       <br /><strong>       <br /><img src="http://i.msdn.microsoft.com/ff796187.branding3(en-us,MSDN.10).png" /></strong></li>
</ul>
<blockquote><p>Do the same with as much as possible social networking sites.     <br />Aggregate the data and share it with us developers so we can personalize better our content (not only ads)..</p>
</blockquote>
<ul>
<li><strong>Stay away from hustling users as much as you can        <br /></strong>Force me to log in only once in 24 hour or more.&#160; I ‘m sure this goes against best security practices etc. but for most web sites it really doesn’t matter. Otherwise you shift from &quot;login screen” to “nag screen“       </li>
<li><strong>Support other browsers the same you do with IE.        <br /></strong>What’s the story with the FireFox and Windows Live? One of my <a href="http://blog.roboblob.com/" target="_blank">friends</a>, decided to use DropBox instead of LiveMesh (even offered 250% more storage space) just because he hates LiveID. Reason: he uses Firefox and it looks like that “Remember me”check box on Firefox has slight dementia so the login screen is quite annoying <img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://blog.vuscode.com/blogs/blogs/malovicn/wlEmoticonsmile_15CD3BE0.png" />&#160; </li>
<li><strong>Support other security protocols       <br /></strong>LiveID as OpenID provider, OAuth etc… The more adapters the merrier.</li>
</ul>
<h2><strong>Last but not the least - respect us developers </strong></h2>
<p> <strong></strong>
<p><strong></strong>I got personally interested in this topic because I choose <a href="http://blog.vuscode.com/malovicn/archive/2010/06/02/5-reasons-why-silverlight-sucks-in-lob-compared-to-wpf.aspx" target="_blank">WPF for my LOB application</a> I am playing lately and I decided to use LiveID for authentication (everyone I know has one – regardless how they use it). </p>
<p>My preferred approach to building this app is S+S (which I am not sure if is still official MS way to go) where a desktop client application gets powered by services from the web/cloud getting with this approach best of both worlds: best user experience on windows machines + data in the cloud.</p>
<p>I was so naïve when I decided to try tout LiveID to expect to find some LiveID STS web service to which I would pass user name + password + ApplicationID and get back in response membership token. Naïve because I didn’t even consider the possibility that such thing doesn’t exist which ended as a true case.I really don’t understand why there is no such offering by Microsoft as we speak.   <br />&#160; <br />The second in favor solution is “acceptable” experience Microsoft has in its own Live Essential suite tools.Here’s a sample of how to do it.    </p>
<p><a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_3C6BA260.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_65B2C491.png" width="604" height="517" /></a></p>
<p>As you can see it is a simple client app window which I am not sure what it does on “Sign in” but whatever it does (POST or web service) I am ok with using it too.</p>
<p>What I don’t want: </p>
<ul>
<li>login control being a web browser control showing the special windows live login html page</li>
<li>generic control where I can not change the text (my app + folks not speaking English)</li>
</ul>
<p>Reasons why I don’t accept those two things are I guess exactly the same as the one Microsoft came up with&#160; when deciding not to use it in their own products.</p>
<p><em><strong>If Microsoft expects me to use LiveID in my WPF apps they have to provide me a way to get the same user experience they have in dealing with the same problem.</strong></em></p>
<p>Yesterday Microsoft released new <a href="http://msdn.microsoft.com/en-us/library/ff749458.aspx" target="_blank">Messenger Connect SDK</a> which contains a sample WPF application and WPF template which is encouraging. In order to run the sample, one need to register application with windows live which right now is done through connect where you fill the request form and someone sometime would consider it. </p>
<p>Based on a quick glance over the sample there are no obvious ”skinning” capabilities – no control just a direct call to some function. The only thing I could do while waiting (hopefully) to get an LiveID was to run the sample as it is out of the b ox and this is the result I got “HTML in a box” – not very encouraging.</p>
<p><a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_27E394E0.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_3DEA0072.png" width="244" height="230" /></a>    </p>
<p>I’ll wait for the application key before I make a final call but so far it doesn’t look like Microsoft cares about WPF + LiveID integration experience..</p>
<p>Keeping fingers crossed but not holding my breath …</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:2c097ec5-9ea9-4855-8491-dbede07709cc" class="wlWriterEditableSmartContent">del.icio.us Tags: <a href="http://del.icio.us/popular/LiveID" rel="tag">LiveID</a>,<a href="http://del.icio.us/popular/WPF" rel="tag">WPF</a></div>
<p>The post <a href="http://blog.vuscode.com/malovicn/archive/2010/06/26/windows-liveid-microsoft-red-headed-stepchild.aspx">Windows LiveID – Microsoft red headed stepchild?</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/vuscode?a=w04Sg-5N3GI:0byejiOgoIk:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=w04Sg-5N3GI:0byejiOgoIk:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=w04Sg-5N3GI:0byejiOgoIk:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/vuscode?i=w04Sg-5N3GI:0byejiOgoIk:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/vuscode/~4/w04Sg-5N3GI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vuscode.com/malovicn/archive/2010/06/26/windows-liveid-microsoft-red-headed-stepchild.aspx/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2010/06/26/windows-liveid-microsoft-red-headed-stepchild.aspx</feedburner:origLink></item>
		<item>
		<title>What is wrong with Cosmopolitan theme</title>
		<link>http://feedproxy.google.com/~r/vuscode/~3/wjna359QGzI/what-is-wrong-with-cosmopolitan-theme.aspx</link>
		<comments>http://blog.vuscode.com/malovicn/archive/2010/06/15/what-is-wrong-with-cosmopolitan-theme.aspx#comments</comments>
		<pubDate>Tue, 15 Jun 2010 11:02:31 +0000</pubDate>
		<dc:creator>administrator</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://</guid>
		<description><![CDATA[<p>I am HUGHE fan of Metro design paradigm, so I was more then excited to check out Silverlight business application theme pack&#160; containing the Metro theme template (“Cosmopolitan”) which was released officially couple of days ago. I am not designer but still wanted to share with community my initial impression and that is: WTF. Here [...]</p><p>The post <a href="http://blog.vuscode.com/malovicn/archive/2010/06/15/what-is-wrong-with-cosmopolitan-theme.aspx">What is wrong with Cosmopolitan theme</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>I am HUGHE fan of Metro design paradigm, so I was more then excited to check out Silverlight business application theme pack&#160; containing the Metro theme template (“Cosmopolitan”) which <a title="http://blogs.msdn.com/b/deepm/archive/2010/06/13/theme-pack-for-silverlight-business-application-released.aspx" href="http://blogs.msdn.com/b/deepm/archive/2010/06/13/theme-pack-for-silverlight-business-application-released.aspx" target="_blank">was released officially couple of days ago</a>. </p>
<p>I am not designer but still wanted to share with community my initial impression and that is: <strong>WTF</strong>.</p>
<p>Here is picture illustrating why..</p>
<p><a href="http://blog.vuscode.com/blogs/blogs/malovicn/UIWaste_635A81A0.jpg"><img style="display: inline" title="UIWaste" alt="UIWaste" src="http://blog.vuscode.com/blogs/blogs/malovicn/UIWaste_thumb_7A1C59DA.jpg" width="640" height="423" /></a> </p>
<p>Considering the fact that we are speaking here about the web site, the fact that there’s 300 pixel of wasted vertical space (~220 in OOB scenarios) is insane. Think about how usable this site would be used in typical netbook/laptop/slate (any smaller height wide screen).</p>
<p>What they should do is simply copy paste Zune minimalist approach which preserves the UI waste and maximize the central part of the screen showing content.</p>
<p><img src="http://media.papiri.rs/2010/06/Zune.jpg" /> </p>
<p>I am aware that this is template which can be customized etc, but we all know that in a lot of cases it won’t be customized at all and we might end with a bunch of web sites using “Metro theme” (especially once WP7 would be released) which would contribute to Silverlight reputation in a bad way,</p>
<p>In other words, while I really appreciate templates provided to us, I think Microsoft creative ninjas (or someone from the community)&#160; should do a couple more iterations on Cosmopolitan template and make it more usable by default and then we would customize it with 2nd level menu etc.</p>
<p>The post <a href="http://blog.vuscode.com/malovicn/archive/2010/06/15/what-is-wrong-with-cosmopolitan-theme.aspx">What is wrong with Cosmopolitan theme</a> appeared first on <a href="http://blog.vuscode.com">.NET and me</a>.</p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/vuscode?a=wjna359QGzI:0byejiOgoIk:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=wjna359QGzI:0byejiOgoIk:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/vuscode?a=wjna359QGzI:0byejiOgoIk:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/vuscode?i=wjna359QGzI:0byejiOgoIk:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/vuscode/~4/wjna359QGzI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vuscode.com/malovicn/archive/2010/06/15/what-is-wrong-with-cosmopolitan-theme.aspx/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2010/06/15/what-is-wrong-with-cosmopolitan-theme.aspx</feedburner:origLink></item>
	</channel>
</rss>
