codefoster | to inform and to inspire
Jeremy Foster
@codefoster

A Primer on LINQ and Lambda

by Jeremy Foster 1. May 2012 10:46

Introduction

I still remember the day well. I had heard a ton of buzz about LINQ statements and lambda expressions, so I knew they were pretty big deals, but I didn’t have the concept. I didn’t know why they were important or when. In short, I didn’t know what problem they solved.

I looked all over the internet for a good description of the why/when… for the problem statement… for the concept, but I didn’t really find it. I found enough information to extrapolate the concept in rather short order, but I’d like to write a primer on the composite topic of LINQ and lambdas because it’s what I would have like to have seen.

This is just a primer and not an exhaustive introduction. There’s plenty of information on the web and I’ll include some links to get you started digging further, but this is just a brief attempt to relay the concept and get you started.

Here goes.

LINQ

The problem statement

LINQ exists because we do a lot with lists of data in a huge variety of forms.

LINQ is essentially a collection of extension methods that act on lists. It’s that simple. These methods filter lists, sort lists, and in many other ways they manipulate the individual items in a list. The cool thing is that any list (any list that is IEnumerable technically) can be “LINQed”. Furthermore, the extension methods can be overloaded to work not only on local collections such as lists and arrays, but they can also act on an endless number of more conceptual collections. So anyone can create a LINQ provider and allow developers to interact with their collections through this common set of methods. The Wikipedia page on LINQ includes a good list of providers. Some I find interesting are: LINQ to Twitter, LINQ to Wikipedia, and LINQ to CSV.

The best place to go to learn about LINQ is 101 LINQ Samples. But know this… when they created LINQ, they created a whole new way of writing the code. It’s called the LINQ query syntax and it feels a little like you’re writing SQL. But everything you write in LINQ can either be written using this LINQ query syntax or it can be written using extension methods. The 101 LINQ Samples writes everything in LINQ query syntax, but I all but never use this syntax anymore. I strongly prefer the extension method syntax myself.

So these are equivalent statements that filter a list of states for the ones that start with the letter ‘a’:

LINQ Query Syntax:

var statesThatStartWithA = from s in States where s.Name.StartsWith('a');

LINQ Extension Method Syntax:

var statesThatStartWithA = States.Where(s => s.Name.StartsWith('a')); 

Lambda Expressions

The problem statement

Lambdas exist because delegates can be cumbersome.

Dynamic languages like JavaScript make handling and passing functions a beautiful thing. A function can be passed around just like a variable. The same can be done in C# using delegates, but it’s a pain in the butt. You have to declare the delegate and whoever uses it needs to have visibility to this definition.

Lambda expressions are simply anonymous functions. They’re just a really shorthand way of writing a function without even giving it a name.

Notice in the code above where we filter out the states that begin with ‘a’ using the extension method syntax that the Where method takes a single parameter and that parameter is a lambda expression…

s => s.Name.StartsWith('a')

This is awesome because functions are powerful. In this case we use s => which means that our function takes in a single parameter (which we know is going to be the type of whatever item types exists in our list… in this case States) and it returns a Boolean value of true if the state starts with an ‘a’. If we did this (which would be silly of course)…

var states = States.Where(s => true); 

…then we would get all states. They would not be filtered at all.

Notice also that our function doesn’t have any mustaches around it, doesn’t have a semicolon, and the “return” keyword is omitted. It doesn’t say s => { return s.Name.StartsWith(‘a’); } . This is another feature of lambda expressions. If you’re entire function is a single statement and evaluates to the return type that the lambda expression is expected to return, then the typical adornments can be omitted and it works. Know, however, that you are welcome to add the adornments and thus grant yourself the ability to get all sorts of fancy with your function. You can, for instance, do a few steps imperatively before you return a value. Let’s look at what that might look like although the following example is again rather silly except that it illustrates my point…

var statesThatStartWithA = States.Where(s => {
	char letter = 'a';
	bool result = s.Name.StartsWith(letter);
	return result;
});

Lambda expressions work great with LINQ statements, but their usefulness by no means ends there. Remember, it’s just a shorthand way of writing a function, so you will find them all over the place.

That probably plenty of depth for a primer, but dig into more depth in the links I have included below.

Resources

101 LINQ Samples
MSDN: Introduction to LINQ
Wikipedia article on LINQ

MSDN: Lambda Expressions (C# Programming Guide)
Wikipedia article on anonymous functions
Practical Introduction to Lambda Expressions

Tags:

C#

Get That WinRT Documentation Local

by Jeremy Foster 26. April 2012 09:05

If you haven’t seen the modified help system in Visual Studio 11 then prepare to be impressed. Now when you go to the Help menu, you can choose Add and Remove Local Help Content. Upon doing so, you’ll be presented with a very helpful dialog box.

From here it is very easy to figure out how to choose which categories of help content you want to be installed locally and where it will be installed from.

I just installed all of the WinRT and JavaScript help content so now I can read it disconnected. Woohoo.

image

Tags:

Visual Studio

Windows 8 "Rails" Panning Mode

by Jeremy Foster 25. April 2012 22:20

When you’re panning a page in Internet Explorer 10 Metro, you’ll feel it lock the panning direction on you at times. If you’re like me it won’t necessarily be intuitive and will take some getting used to. Here’s how that’s working…

It’s called “Rails” panning mode. If you grab the screen with your finger and drag far enough in the direction of one of the shaded areas below, the panning direction will be constrained to that direction. The reason is that usually if you scroll in the general direction of up, down, left, or right, what you want is to scroll exactly in that direction because you’re browsing content that’s laid out vertically or horizontally.Hh465310.ux_panning_rails(en-us,WIN.10).png

I didn’t like it at first because sometimes I scrolled down a little and then wanted to see what was off screen to the right and it wouldn’t scroll that direction. I don’t think it will take long to get into the habit of initiating my scroll diagonally if I might want that option, however, and I’ll have the added benefit of the rails functionality for when I truly am just wanting to go up and down.

Happy panning!

Tags:

Windows 8

Overview of Windows' New Architecture

by Jeremy Foster 25. April 2012 21:48

At the heart of Windows 8 development is WinRT. This is NOT Win32 and it’s not .NET. It’s a brand new set of APIs that’s designed for modern software development and designed for user experience with an asynchronous model that allows your app to remain fast and fluid.

The real joy is that you get to write code against this API in your language of choice. You can choose JavaScript, C#, Visual Basic, or C++. The code you author in your language of choice is projected into WinRT code and runs native on Windows. Additionally, you get all of the inherent benefits of your language. So for JavaScript, you still get to call all of the existing browser APIs. For the .NET languages, you get a tailored .NET profile with namespaces and classes that work much like you’ve come to expect. And with C++ you get to call C components and C/C++ libraries (again within a tailored subset of Win32).

All of this new functionality is available in addition to the ways you’ve always done things. It does not eliminate it. So you can still write web apps, .NET apps, and native apps against Win32 like you always have. That’s excellent.

In case it’s news to you, here’s an API overview of the Windows 8 Platform. You can find more information at buildwindows.com and dev.windows.com.

Tags:

Windows 8

Which Windows 8 Language Stack Should I Choose?

by Jeremy Foster 25. April 2012 10:30
Technorati Tags: ,,,

I had a conversation with an attendee at the recent Windows 8 developers event at LA Live on Monday that I want to put into words and share in case it is of benefit. The question was this:

I’m new to development and I’m jumping in to Windows 8 development. Which language stack should I choose – HTML/JavaScript or XAML/C#?

It’s a good question because there are a lot of contributing factors.

I’ll leave the other languages (Visual Basic, C++) out of the discussion for the most part since they were not part of the question.

Here are the factors I’d like to compare on:

  • viability of employment
  • scale
  • interoperability
  • developer joy

Finally, a direct comparison is difficult because the nature of each of these language stacks tends to push developers into application architectures. XAML/C# applications tend to enable a developer to create a lot of custom business logic inside the application itself, whereas HTML/JS applications tend to encourage a developer to push the business logic up to a separate service to be consumed in a JSON feed for instance.

Let’s go.

Viability of employment

First of all, I have to say this. Don’t jump into application development with high hopes of being employable but without any passion for the trade. It won’t work. I would love to play guitar, but I can’t. Why? Because I don’t love it enough. If I loved it enough I’d practice it every day and then I’d become really good. I guess my analogy breaks down there, because I wouldn’t necessarily be employable :) You really need to love software development and you need to do it every day. You need to read programming books in bed and you need to experience genuine, heart-felt aggravation when things aren’t working.

But it’s good to be employed, right?! Still, I don’t think viability of employment (now and in the future) is too much of a concern. Given the current developer and consumer investments in HTML and JavaScript as well as  XAML and C#, none of these languages are going to leave their developers on the street any day soon.

If, however, you want to be a very portable employee, you should choose HTML and JavaScript. I’m not talking geographically portable but technically portable – as in, you want to work in a variety of roles at a variety of companies doing a variety of things. The HTML and JavaScript languages are everywhere. We don’t just have browsers on our computers anymore. There are browsers in cars and kitchens and phones. So, every role in every company in every industry needs to know something of these technologies.

Still speaking technically, the employment options for a XAML/C# developer are going to be more narrowly defined.

Scale and maintainability

When I say scale, I'm talking about the ability for an application’s code base to go from small to huge. You might consider this dynamic if you suspect your application will be growing a lot - say going from 3 features to 30. In this case, your codebase needs to grow and your architecture needs to evolve.

On the UI side, I can’t see any advantages of either XAML or HTML in this area. Behind the scenes, however, C# has some huge advantages over JavaScript. I’ve seen C# codebases that are mind boggling and yet still quite easy for the developer to traverse and debug. Handling a huge JavaScript applications on the other hand is about like handling Jell-O - both are a little too dynamic. That’s not to say it can’t be done; I’d never make that claim.

Interoperability

How good are these language stacks at cross communicating with other applications? Both are very good. You might want to jump in here and tell me how much better JavaScript is because of it’s lightweight JSON objects, integration with the web applications, and the like. But C# can do all of that too. Any of the C# objects are one small serialization step away from becoming the same JSON object that a JavaScript app uses and likewise in the other direction. Just because your C# application is fat with business logic, doesn’t mean it can’t communicate lightly with the outside world.

Developer Joy

This is an important category in my opinion. You don’t technically  have to enjoy writing software to write a lot of good software, but it most certainly helps.

I find a lot of joy writing both C# and JavaScript. In C#, I enjoy the traversal of types, type hierarchy, and type conversion. I enjoy lambda statements a lot, and I really geek out on LINQ. In JavaScript, I enjoy JSON and dynamically creating, extending, and manipulating objects. I enjoy anonymous functions and passing them around willie nillie.

I think you have to run through some tutorials for each language and determine for yourself which one you might enjoy using more. The problem is that so much of my language enjoyment has come later when I’ve used a language for hundreds of hours and I’m starting to feel like I get it.

See if you can browse a bunch of JavaScript code and C# code and see if either feels more right to you. See if one of them comes more quickly to your intuition.

Conclusion

Overall, whatever language you choose for developing Windows 8 apps, you’re going to end up with the ability to create some awesome apps, you’re going to be employable, you’re going have fun doing it, and with the amazing opportunity you have to reach hundreds of millions of potential users, you are even likely to make some money!

Happy app development!

Tags:

Developer Community | Windows 8

Ban the #Region

by Jeremy Foster 24. April 2012 13:16

Just in case you didn’t know, you don’t need to use the #region designator any more to collapse code. When you use the #region indicator, you create a region for everyone you share your code with, and some people hate having regions in their files. I’m one of them.

If I’m looking at a code file that’s long enough to require regions, I’d rather not look at it at all. Even “in the real world,” files should contain a single class, classes should follow the single responsibility principle, and methods should be short. If your code doesn’t look like that and you use regions to attempt to make your code remotely readable, that’s sinful enough, but to force those regions onto your fellow developers is just downright morbid.

How do you get away from them you ask? Simple. You just highlight code that you want to group and hit CTRL + M, CTRL + H (or the alternative mouse longcut of going to Edit | Outlining | Hide Selection). The code collapses just like a regions, but here’s the kicker – it’s only hidden for you! The change is saved in your .suo solution file which is for you only (never check this into source control), and now you can go ahead and collapse what you will and leave your fellows free to work how they will.

There you have it.

Tags:

Visual Studio

Big Windows Developer Event in LA!

by Jeremy Foster 22. April 2012 10:48

If you are in the Los Angeles area Monday event or if you can get there, you should stop by the Nokia Theater Live next to the LA Convention Center and get a whirlwind tour of Windows 8 from a developers perspective!

Everything from breakfast to dinner will be information straight from Microsoft to you. Then, after dinner, you’ll be joining us for Coding with the Experts where you walk through an excellent series of tutorials to create a full-fledged Windows 8 app. You’re guaranteed to walk away with skills.

I personally will be presenting on the tooling you’ll use to create Windows 8 applications: Visual Studio 11 and Blend. I’ll also do a presentation on designing Windows 8 applications including a complete design scenario, so it will be theory and practice in one presentation.

Come introduce yourself to me when I’m not on stage. I’d love to meet you. See you there.

Go to http://bit.ly/Jjd9dato to get all the details. See you there!

Tags:

Windows 8 | Developer Community

Blend: Design, Execute, Interact

by Jeremy Foster 16. April 2012 10:24

This is likely apparent to anyone that has already ventured into Windows 8 development using Blend for Visual Studio 11, but if you haven’t ventured in yet for some reason… like say you’re busy actually getting work done! I know how that goes. I was recently in industry trying to meet deadlines and didn’t have much opportunity to look at new technology.

So allow me to quickly highlight an incredible feature in Windows 8 development – specifically in Blend for Visual Studio 11.

Why Use Blend?

First of all, why and when should you open Blend? For a long time, Blend was downright offensive to me as a developer. I was and still am a Visual Studio guy. I don’t want another IDE offering in parallel to confuse and divide me! But now I’ve accepted the two tools as very different and each very powerful in their own role.

Some people will almost always use Visual Studio. Remember that the Express version is completely free. How do you know if you’re one of these people? Simple. Look down. Are you wearing one of these t-shirts right now?

image

If so then chances are you’re a geek and Visual Studio may be your primary if not your exclusive tool.

Are you wearing something more like this?

image

If so then you may call Blend your home and ask a geekier friend to write the actual code for you. If you’re like me, you might wear many hats (and shirts) and be able to geek out in the code and the design tools.

Design, Execute, Interact

But right now I want to show you something that is exclusive to Blend. That is its ability to execute your application live as you design it and its ability to even give you interaction with the application and why you need that.

image

The figure above is what it looks like when you’re designing an application in Blend. The interesting tidbit of note is that those recipes you see in the design pallet are not declared in the HTML. They exist as JavaScript arrays in the data.js file and as images of food (yum) stored in the images folder.

Blend here is executing the application, running the JavaScript, and rendering the recipes accordingly on the screen. So just this is pretty awesome. Remember in Expression Blend days of old when we loaded sample data so we (designer role) could get an idea of what things looked like. Those are bygone days, my friend.

In this mode, we can actually grab one of the images (even though they’re being rendered live!) and resize it (see next figure) - effectively modifying the size of the image element in the item template utilized by the ListView control that forms this list.

image

But what about when you want to do some design on a different page. Say we want to resize the recipe image on its detail page as well. If we were actually executing this application, we would touch on the recipe to get to this page. But remember that we are actually executing this application. We just have to tell Blend that we want to interact with it. And to do that you hit the Interactive Mode icon (image) on the right side of the tab well. This hides all of Blend’s panes and puts you in a mode where input is passed on to the application (see next figure).

image

Now a click on a recipe takes you to the item’s detail page…

image

You can now click on the Interactive Mode icon again to turn it off…

image

…and now you’re ready to do some design on this page.

That’s all for now. Let the power and potential that is Blend sink deep. Now use it to create an awesome app.

Happy Blending!

Tags:

Windows 8

A Tour Through the Windows 8 Documentation

by Jeremy Foster 11. April 2012 12:29

Last night I did a presentation at a very active and exciting Seattle user group called vNext. The topic, of course, was Windows 8. If you read my blog, you know that that’s most of what I’m talking about these days. Instead of creating tangential content, relied on the excellent documentation that you can browse any time in the Windows Dev Center at dev.windows.com.

The Dev Center is an enormous place, but it’s well organized and I think you’ll find it’s not too difficult to find what you’re looking for. Still, I’m including my compiled outline below in case it helps you navigate the sea of information.

The hierarchy of this outline exactly reflects that of the Dev Center, so hopefully mapping the sections will be easy and intuitive.

Getting started

Making great apps

Visual Studio 11 Beta

Blend for Visual Studio 11 Beta

Download samples

JavaScript tutorial

JavaScript doc roadmap

Visual Studio templates

 Designing UX for apps

Design Principles

UX Patterns

Navigation design

Commanding design

Touch interaction design

Downloading design assets

Case studies

Website to Metro style app

Developing apps

Writing code for Metro style apps (JavaScript)

Coding basic apps

HTML, CSS, and JavaScript features and differences

HTML and DOM API changes list

Features and restrictions by context

Asynchronous programming

Asynchronous programming in JavaScript

Chaining promises in JavaScript

Creating a UI

Defining layout, navigation, and commands

Supporting navigation

Quickstart: Using single-page navigation

How to reference content

How to link to external web pages

How to create a mashup

Adding controls and content

Controls list

Animating your UI

Responding to user interaction

Touch input

Gestures, manipulations, and interactions

Quickstart: Identifying input devices

Working with data and files

Data binding

Quickstart: Binding data and styles to HTML elements

How to bind to a complex object

Managing app data

Accessing data and files

Transferring a file from a network resource

Sharing and exchanging data

Tags:

Windows 8

Creating an Observable Object in Windows 8 JavaScript

by Jeremy Foster 10. April 2012 15:05

Living in the JavaScript world for a while will help you to appreciate the offerings of C# for sure. Many concepts like classes, inheritance, observable collections, list extensions (LINQ) are  simply absent and so a creative alternative has been created either in WinJS or just in recommended practice.

One of these is in the area of data binding.

First of all, I recommend Steven Walther’s excellent article on Metro: Declarative Data Binding. He’s much more thorough than I intend to be here. I only want to relay my experience with following the instructions on dev.windows.com – specifically the article entitled How to bind a complex object, and following the sample project entitled Programmatic binding sample.

Here are the steps I took to get a very simple object to bind well.

  • Write a simple class
  • Add an _initObservable method
  • Mix it
  • Instantiate it
  • Bind the properties
  • Change a property to test

That’s it. I’ll elaborate a bit on each point.

Write a simple class

Here’s the rocket science class I wrote. It has a single property – name.

var Widget = WinJS.Class.define(
    function (name) {
        this.name = name;
    }
);

Add an _initObservable method

var Widget = WinJS.Class.define(
    function (name) {
        this._initObservable();
        this.name = name;
    }
);

This is necessary so that “the observablility implementation is completed properly”.

Mix it

WinJS.Class.mix(Widget,
    WinJS.Binding.mixin,
    WinJS.Binding.expandProperties(Widget)
);

This adds the necessary bindability to your custom class. If you only want a select few of your properties, you can specify a subset of properties in the parameter for the expandProperties method call. See the Programmatic binding sample to see what I mean.

Instantiate it

Now you’re ready to instantiate your object.

var widget = new Widget("Widget1");

Bind the properties

What you’re doing in the binding is specifying a function that you want to run whenever a property is changed.

widget.bind("name", function (newValue, oldValue) {
    var foo = document.querySelector("#foo");
    foo.innerText = newValue;
});

Change a property to test

Now, somewhere in your code, change value of that property like this…

widget.setProperty("name", "Hi, Mom!");

And there you have it. The simplest possible example I could come up with for data binding a complex object by turning it into the JavaScript version of an observable object.

Happy binding!

Tags:

Windows 8

Feed Subscribe