Recent posts about LINQ and related topics by ThinqLinq

New Paper.li for Reactive Extensions

Paper.li is a site that makes it easy to aggregate blog posts, twitter streams, Google+, Facebook, etc into a magazine format for easy reading. There are virtual papers on almost any topic you could imagine. While I’ve seen messages that some of my tweets and links have been featured, I didn’t recall seeing any on the Reactive Extensions (until Now).

I took the liberty of creating a Paper.li specifically for tracking Reactive Extensions news and announcements. Feel free to follow it by clicking on the widget below. Currently I have it scheduled to only publish once a week, but could make it more frequent if necessary. Also, if you can think of a filter I should add or post I should feature, let me know and I’ll see what I can do.

Posted on - Comment
Categories: Rx - RxJs -

Beware of Async Sub or Void

At my VS Live last week, I gave a survey of Asynchronous programming from .Net 1 through .Net 4.5. As part of the presentation, I showed off this simple example of doing Async starting with a synchronous example. Here’s the beginning example:

Sub Main() DoWorkAsync() Debug.WriteLine("All Done")

Console.ReadLine() End Sub Sub DoWorkAsync() PrintIt() Debug.WriteLine("Done Async") End Sub Public Sub PrintIt() Dim text = "Hello World" Task.Delay(2000) Debug.WriteLine(text) End Sub

Before continuing on, try to figure out what you would see in the output window. For those impatient, here’s the output:

Hello World
Done Async
All Done

However, if you try this code, you will notice that the output is all produced prior to the expected 2 second delay (from the Task.Delay). Why is the delay ignored, because the TPL schedules the delay operation on a different thread than the main UI one and then lets the rest of the code operate on the main thread. We can force the delay to pause by changing the PrintIt method as follows:

    Public Sub PrintIt()
        Dim text = "Hello World"
        Task.Delay(2000).Wait()
        Debug.WriteLine(text)
    End Sub

Now, we do delay for the 2 seconds as expected, but we loose any asynchronous behavior that we expected. As a result, we should use the new Async/Await keywords to make our PrintIt method async:

    Public Async Sub PrintIt()
        Dim text = "Hello World"
        Await Task.Delay(2000)
        Debug.WriteLine(text)
    End Sub

Now, if we check our output, we’ll see the following results:

Done Async
All Done
(2 second pause)
Hello World

Notice here that the Done Async and All Done messages appear before Hello World.  Why? Because when the line with the Await is encountered, control is passed back to the calling method (DoWorkAsync) and schedules the continuation of the await operation on the thread context of the Task.Delay operation. This is just one of the problems with the “Async Sub” or in C#, “async void” patterns. They are acceptable for fire and forget operations, but can cause issues if you want to rely on structured exception handling, resource disposal, and a number of other useful constructs, you shouldn’t use Async Sub. For more information, see Lucian Wischik’s Async Patterns article or any of a number of excellent articles by Stephen Toub.

So, how do we call the PrintIt operation asynchronously and ensure that it completes prior to continuing the “Done Async”  operation? We need to change the signature of the PrintIt method to return a Task rather than returning nothing (void). We then need to move the await up the stack to also Await PrintIt and mark DoWorkAsync as Asynchronous.

    Sub Main()
        DoWorkAsync()
        Debug.WriteLine("All Done")
        Console.ReadLine()
    End Sub

    Async Sub DoWorkAsync()
        Await PrintIt()
        Debug.WriteLine("Done Async")
    End Sub

    Public Async Function PrintIt() As Task
        Dim text = "Hello World"
        Await Task.Delay(2000)
        Debug.WriteLine(text)
    End Function

Now when we run our program, we see the following output:

All Done
Hello World
Done Async

Notice here that the “All Done” message appears before the 2 second delay, but Hello World and Done Async come out in the expected order showing how the DoWorkAsync operation was indeed run asynchronously from the rest of the app. If you want to see the internals of how the compiler interprets the Async and Await keywords, see my earlier post on using ILSpy with Async.

Also, if you are interested in using Async with Asp.Net or WCF, make sure to check out the Async session from Asp.Net Conf 2012 which details some of the potential issues you should consider there.

Posted on - Comment
Categories: VB Dev Center - VB -

CSS Disambiguation with WinJS and SPA

Recently, I’ve been working to build with some HTML/JS applications for Windows 8. While I could have built them using XAML/VB-C#, I decided to push myself out of my comfort zone to see what I could do with my web experience in these new Windows Store Apps. In addition, I have a number of customers who are looking to minimize code re-writing by leveraging their existing web assets for these native applications, so I figured I might as well dig into them a bit.

I’m used to the standard page per request model and AJAX based models, but the Windows-8 implementation follows more along the lines of the Single Page Application (SPA) model. As a result, some things become easier (like state management across pages) while others become more tricky (make sure to avoid the global namespace as more JavaScript will stay alive in your apps now).

One of the first Issues I came up against was an issue when navigating between pages and finding that styles that are being applied in child pages are sticking when navigating back to the parent page. I’m sure I’m not alone as this Stack Overflow post indicates.This wouldn’t be an issue in a standard web implementation because the page would be re-loaded along with only the styles that page requested. However, in the Windows Store App model, each page that is loaded will bring it’s associated css and js into scope the first time the page is loaded and be retained as we navigate to other pages. Let’s take a look at an example app to see how this works.

Let’s start by creating a new JavaScript app using the Navigation App template. This will create a solution framework with a default.html page that loads a home.html page into a div called “contenthost”

image

To keep this sample as simple as possible, I’m just going to add one more page to the default template. To do this, create a new folder in the pages folder in the Solution Explorer. I’ll call this folder Detail. In the Detail folder, add a new Page using the Page Control template and call it DetailPage.html.

image

The Page Control template will generate three files in our folder – DetailPage.html, DetailPage.js and DetailPage.css. This allows us to follow a good coding pattern to keep our concerns separated between layout semantics (html), logic (js), and presentation (css). We’re not going to modify the html of this page, instead we’ll just tweak the css to apply a bit of styling to our h1 tag to set the font to Comic Sans MS. Note, I don’t recommend making this particular change in your apps. This change is just for demonstration purposes! Open the DetailPage.css and add the following to it:

h1{
    font-family:'Comic Sans MS', cursive;
}

 

With that change, we now need to give the user the ability to navigate from the home page to our new page. In the home.html page, let’s add the highlighted line giving the user an anchor tag to click:

        <section aria-label="Main content" role="main">
            <p>Content goes here.</p>
            <a id="detailButton" href="#">View Detail</a>
        </section>

Finally, let’s add a click handler for the “button” in the home.js file:

  ready: function (element, options) {
      element.querySelector("#detailButton").addEventListener('click',
           function () { WinJS.Navigation.navigate('/pages/Detail/DetailPage.html') });
  }

Now that we're done, we can navigate to our page to view our handy work. Hit F5 to run the app to see your impressive L337 skillz.

image

Next, navigate to the detail screen by clicking your link.

image

Notice here, because we used the WinJS.Navigation.navigate method to move to this page rather than just setting the href on the anchor tag, we magically have the default back button to get back to the home page. Try clicking it now.

image

Compare the first screen shot with this one. Do you notice anything unusual? The page title is now the wrong font. If we look at the Solution Explorer while debugging, the situation starts to make sense. Notice here that the DetailPage.js is still loaded even though we have navigated back to the home page.

image

As I stated earlier, in WinJS applications, the js and css files are loaded when they are first used and retained in memory rather than being refetched for each page request as is done in web pages. Since the styles are applied in the order that they are fetched, the last version of the font that applied to the h1 is the one that came from DetailPage.css. We can’t just try to set the style explicitly again in the home.css, because it was already previously loaded, so it won’t be re-loaded again.

In this case, if we want to globally modify the style, we should make then change in the default.css located in the css folder of our project. If we want to modify the style only for the lifetime of our individual detail page, we need to preface the style with a page class that is specific to our page. Looking at our DetailPage.html, we can see that the page template wizard generated the necessary class for us already.

<body>
    <div class="DetailPage fragment">
        <header aria-label="Header content" role="banner">
            <button class="win-backbutton" aria-label="Back" disabled type="button"></button>
            <h1 class="titlearea win-type-ellipsis">
                <span class="pagetitle">Welcome to DetailPage</span>
            </h1>
        </header>
        <section aria-label="Main content" role="main">
            <p>Content goes here.</p>
        </section>
    </div>
</body>

Notice that the main div uses the “DetailPage fragment” class. With this we can preface the h1 style in the DetailPage.css file with the .DetailPage class selector to indicate that the style should only be applied to this page:

.DetailPage h1 {     font-family:'Comic Sans MS', cursive;
}

If we run the application again, we should see that when we navigate back to the home page, the font is (thankfully) no longer Comic Sans MS, but has reverted to the oh so much more wonderful Windows 8 default of Segoe UI. If you don’t’ believe me and want to try this out for yourself, feel free to type the code in above, or just download the project and try it yourself. I know, I could have told you about the download link in the beginning, but where’s the fun in that?

Have you run into this issue and found alternative solutions, I’d love to know what you thinq.

Posted on - Comment
Categories:

Blog evolution

Five years ago, I started this blog as a site written in LINQ dedicated to talking about LINQ. In the years that have followed, I’ve expanded the discussions to include a number of LINQ and language design related topics, including Entity Framework, Reactive Extensions, and other items. Over-all, I’ve tried to limit the scope of the topics to LINQ related issues.

Although I still love LINQ and thinq it is a great technology, I’ve been increasingly working with other technologies and as a result, I have shied away from posting about them here for the fear of alienating my LINQ loving fans. Now that LINQ has been around for over half a decade, I suppose it is time to allow the topics on this site evolve as well and start discussing some of the newer things that I’m encountering in the various technologies that I’m working with to spread the love (or love-hate as the case is from time to time) of that technology with the rest of you.

My hope is that you can continue to grow with me and continue to find value in the posts that will come. Of course, I’ll continue to post about LINQ related items as I find the inspiration and time. If you find yourself turned off by the non-LINQ related posts, let me know and I can consider moving the blog off onto another domain. I'm always open to knowing what you thinq.

Posted on - Comment
Categories:

Unit testing rules of thumb

Earlier this week, Uncle Bob stirred up the TDD hornet nest again trying to wade the fine line between RAD and pure TDD with excessive use of IOC’s. In one of the many responses to the twitter debate, Jimmy Bogard responded that you should use testing methodologies, “When it provides value … it depends.”  Since I am speaking about Unit Testing in SharePoint at the upcoming VS Live events, I figured I should put in my two cents as well.

VSL13_Badge_See125x125VSLCH13_Badge_See125x125

In general, I tend to agree with Jimmy’s pragmatic approach. I’m not a test first zealot by any means, and don’t think that trying to achieve 100% code coverage is a panacea. Indeed, even if you do have 100% code coverage, there can be significant business rules that you may not be testing that you should have tests for. Also, your code may well have exception checking, input validation, data binding, etc. code that spending time testing can only decrease your overall ROI.

When designing systems, I tend to use the following rules of thumb to guide me in when to write coded tests for my solutions. This list is likely not inclusive and as always, to every rule there is an exception.

If it’s a core piece of business logic, it should have a test.

When building systems, there will be a number of cases where business rules assert that under certain situations something specific should happen. In those cases, I recommend writing a unit test. The test should be named appropriate to the business defined rule. For example, if the user should be notified when customer’s age a value drops below an acceptable minimum, I would name the test something along the lines of Customer_InvalidWhenAgeBelow18. This way we document the system requirements through the tests and have a quick way of validating our logic directly with the stakeholders to make sure our tests are asserting the correct things. Once we are done, we can give the test report to the customer to show them that all of their assertions are coming up true before handing off the code.

If you hit F5 to debug an issue more than 5 times, it would have been quicker to write an automated test for it.

On most systems that I work with, the act of debugging an issue can be quite time consuming. Just navigating the system to the point where you want to test often involves a number of steps, including logging into the system, creating a new record, setting the test values, trying to submit the values and checking the results. Often, if you took the time to write up a testing harness for these situations, you can bypass many of the manual steps and just test the logic that you need in isolation. Additionally, if you take the appropriate time upfront to set some test objects (fakes or mocks), then they can be reused for similar tests in the future – further reducing your future testing development time and effort.

If there’s a complex calculation that you are automating, include tests for it.

Even the most thorough coder can make simple math errors when coding calculations. Flipping a “+/-“ check or evaluating a complex logical truth table can be a brain twisting task at times. A simple error can ripple through the system causing unexpected errors. In many cases when automating calculations, you know up-front what some of the expected input and output values are. Write specific tests for them up-front and you will be well rewarded down the road. Better yet, write one test and provide a list (in Excel/Xml/etc.) with the valid inputs and outputs and then use a data driven test approach to evaluate the various permutations of the values.

If there is a user detected bug in logic, write a test before fixing the bug.

All too often, I find my developers trying to debug an issue and thinking they’ve found the solution only to realize that they just located a different bug and never actually fixed the true defect. When writing tests, you should aim to write them so that they fail first and only pass once you’ve corrected the underlying defect.  I’ve also seen tests that appear to have passed even when the test failed, but the author of the test never knew it because the test was always passing (in most cases, they were swallowing test failure exceptions). By writing your test to fail first and then fixing the implementation, you are assured that your fix solves the problem at hand, and have a built-in regression test for future changes.

Often, when trying to get teams to start using a testing approach, I have to work to convince them that the tests are worth the time and effort. Typically, I find resistance particularly from teams that follow the just “get ‘er done” approach. In the consulting world, we often feel the pressure of producing the requested system at the expense of tests which are typically not included as a payable deliverable. However by building up a testing suite, we typically find the value when a test locates a regression defect prior to shipping the product which would have had a cost if it shipped with the defect. Following this more pragmatic approach and remembering these rules of thumb can provide a sense of safety in refactoring and increase your agility and velocity over time when maintaining systems.

Do you have additional rules of thumb that help to guide you? Let me know what you Thinq.

Posted on - Comment
Categories:
 Next