Microsoft SLPS Part 2
04 July 08 11:02 PM | adrian | with no comments

Yesterday evening, I've delivered a talk on protecting your code. Frequent readers would recognize that the first half of the talk was actually written in depth in the first SLPS post. It's not perfect, but I had fun. But definitely the best I did in English, so far.

So for you who didn't quite caught up with what I was talking (I know, I mumble here and there trying to buy some time :D), I'll explain in depth through this post.

First of all, I'm going to reemphasize my point of view; open source does not work, for business. It might be good for education, community, or charity, but not for business. You're trying to sell something you share, that's just doesn't make sense. This is why, there's an inherent requirement to protect your code.

When we're thinking about protection, we'll think: "It's compiled! They won't/don't/can't have the source code." Wrong.

If you're still on this mind set, then you should visit (or revisit) the first part of this post. There I demonstrate how easy it is to convert any compiled .NET assembly back to it's original source code. This actually made up the first of three parts of the talk. Compiling a small application and decompiling it using Microsoft and third party tools.

The next part is about basic protection. Microsoft have bundled Visual Studio with Dotfuscator Community Edition. It doesn't do much (even though the UI provided so many different features -- disabled), only some simple renaming. I've demonstrated how to use Dotfuscator.

This is the original code, which is 100% reproducible:

image

And after obfuscation using Dotfuscator Community Edition, it will become, even though it's 100% reproducible, but it's harder to understand:

image

Several important points on obfuscation:

  • The external interface to an obfuscated code will never be modified. This is to ensure that any code that depends on the interface will not break. Of course, this is basic logic.
  • Dotfuscator stripped all namespace and rename everything to single letter alphabets (sometimes numbers if it runs out of z's).
  • The obfuscation process happens after your code is done. Which means, it doesn't affect development, at all.
  • Obfuscation, given enough time and effort, eventually will be broken. It's still reverse engineering, but with added hurdles to slow down progress.

You've seen Dotfuscator in action, now you'll want more. Unfortunately, more means money! You can easily search for obfuscation products using Google Live Search, so finding one is not on the scope of this post. I don't have any product ready, so I just try to open one of the users of obfuscator.

The company is Intersoft, the product is a UI control library. I "volunteered" to crack open their authorization code. Since good product requires good adversaries, therefore I embark upon the journey of the dark.

Here's one piece of the code which I have successfully decompiled:

image

This is only one part of the code which is the constructor. As you can see the obfuscator actually renamed parts of the code with unidentified characters. It's not easy to distinguish one with another, and in come parts of the code, Reflector crashes when trying to decompile it.

Long story short, I've been able to crack half of it (only the runtime component) in 8 hours. After that I lost interest, since buying it will be cheaper than hacking it.

Several important points on (expensive) obfuscation:

  • The external interface is not change. Again, this is basic logic.
  • Obfuscation, given enough time and effort, eventually will be broken. But since the hurdles are higher, the economics become: which one is cheaper; to hack or to buy?
  • You get what you pay for. Expensive obfuscation will make your code less interesting to hack (except for hardcore hackers out there).

The third part of the talk is actually about Microsoft's product, Software Licensing and Protection Services, or in short SLPS. They have a product web site at root level (which means it's quite important) at www.microsoft.com/slps and if you have MSDN Subscription, you can get a free basic subscription to play with.

The difference between Microsoft and partner offerings is in the way the code protection does. While partners sell obfuscators, Microsoft sells encryptors. So your code is 100% not modified, but encrypted. This encrypted code will then run in a Secure Virtual Machine, or in short SVM. SVM itself runs on top of CLR (so it's still managed code). Moreover, Microsoft also offer activation services for your protected code. So when you pay for protection from Microsoft, they give you the ability to sell your software. Money out, money in.

Details will be in part three.

Share this post: | | | |
Why I'm Sticking with HP
07 June 08 12:26 PM | adrian | with no comments

Disclaimer: I am NOT a Hewlett-Packard employee or affiliate. I am just another very satisfied customer of it's products.

Back then in early 2007, I was just graduated and just got bonus from my first real job. Well, that was the time when I was in the market for a laptop. Actually, I've been thinking of getting one for some time, but time and money was not right.

I was browsing for some new ones, my criteria was simple: light and powerful, design is additional score. I was in between Sony VAIO or Macbook. To keep it short, the former holds non-official warranty (it's parallel imported) and the latter was Apple.

So my father took me to his usual used laptop store to take a look at the used ones. I was particularly sensitive to buying used electronic devices. They will never have enough MTBF to justify buying second hand. But that day was different, there's a 2 weeks old laptop on display, and it looks damn cool.

That laptop was then and is still my current laptop.

The HP Compaq nc2400 is a premium business class laptop, even though it's not powerful, it made up in weight, design, and warranty. The warranty was 3 years, international, parts and labor. Which means, if anything happen during the 3 years period, I will just need to deliver it to HP, and they will bring it back to me, up and running, with zero cost.

And yes, they did that.

The first occasion was power adapter problem. It was Indonesia Imagine Cup 2007 Software Design final. I was there as a guest to look at some of the interesting stuff made by our students. At the end of the event, suddenly my laptop is not charging anymore. I'm still thinking that the adapter had short circuit or overload, since the electricity in Indonesia is not that reliable. Nevertheless, I was back in Jakarta the next day, and brought the laptop and the adapter to the service center (which is just around 2 block from my previous company). In 3 days, they have returned my laptop, working exactly like new. They even cleaned up the laptop! Zero fee.

The second occasion was just last week. This time, the optical drive was not working properly (cannot burn, cannot read DVDs, etc.) and the mouse button was not responsive (probably due to some leftover Pringles inside). Nevertheless, I brought the laptop to the service center in Singapore. Within 3 days, they have delivered my laptop, working exactly like new. They also cleaned up the laptop. And again, zero fee.

These two occasion, puts HP in a very good position for my future buy. The other laptop brands I have experience with are Acer (lots of problem when worked overtime) and Toshiba (top of the line quality, but suffers from abysmal after sales support).

But, there is always a room for improvement. On both occasion, the queue is quite slow and long. On both occasion, I've to wait for around 45 minutes until I get to the support officer. Plus, they haven't released similar product to the one I'm using right now. They have one though, but the specification is a little outdated.

Share this post: | | | |
What is 933888?
07 May 08 10:53 PM | adrian | with no comments

This magic number seems to hold so many in so short form.

933888 is Microsoft Knowledge Base article for Zune update to version 2.5. Yes, it's here, and it shows that Microsoft listens to customer.

Big improvements for this version are:

  • Auto playlist is back! (previously removed from v1 to v2)
  • Gapless play is available (I haven't tried this one).
  • Video store, now I can watch movie without having to pirate it.

Notable is the social features. Too bad I live in the region where Zune is not out yet (that practically means anywhere but US and Canada), and I can't even upload my play records (since it only accepts North America IP addresses).

Features still on queue:

  • games, said CTP will be out this month
  • full five stars rating (previously removed from v1 to v2)

Update: I thought Zune Marketplace is out for updates/repairs, instead it was blocked. Long Zheng have the info on that and how to remove it here.

Update again: Now Zune Card is working! Jamie Thomson have the info on that and how to make it work here.

Share this post: | | | |
Filed under:
Microsoft SLPS (Part 1)
16 April 08 11:17 AM | adrian | 2 comment(s)

Decompiling means converting a program back to the original source code. Previously, decompilation is difficult because you need to understand assembly (which is the least human readable language). Assembly code is translated into machine language (readable by CPU) by the operating system. In .NET, this is not the case. Decompiling is easy.

.NET Compilation

Before we jump into how to decompile, we need to undestand compilation first. In .NET, compilation means converting from .NET language (Visual Basic or C#) to MSIL (Microsoft Intermediate Language).

image

DLL and EXE file you distribute will contain MSIL. When run, the .NET runtime will do another set of compilation before execution (that's why it's called Just-In-Time Compilation) to the platform's assembly language. The assembly language then sent to the platform's operating system.

This means, one set of DLL and EXE file can be run on multiple platform without changes, since translation to the platform's instructions are done after distribution or just before execution. The .NET runtime is also called virtual machine, since it acts as an intermediate machine.

The bad thing is, since the compilation does not generate assembly language, instead a standardized intermediate language, someone can easily take this and translate it back to the original source code with little difficulty.

.NET Decompiler

In fact, the .NET Software Development Kit includes a tool to help you open up the DLL and EXE file to retrieve the MSIL code. This tool is called ildasm.exe (IL De-Assembler). For example, we will decompile a simple Hello World application.

  1. Run ildasm tool. This tool is included with all Windows SDK distribution. You can run it from the Start Menu > Programs > Microsoft Windows SDK [version] > Tools > IL Disassembler.
  2. Once the window is opened, drag and drop the file you want to disassemble. You can use the attached HelloWorld.exe file or any .NET assembly.image
  3. To see the IL code, just double click on any method. For this demo, you can double click on Main to see how the console application retrieves the current user name.

    .method private hidebysig static void  Main(string[] args) cil managed
    {
      .entrypoint
      // Code size       29 (0x1d)
      .maxstack  8
      IL_0000:  nop
      IL_0001:  ldstr      "Hello {0}!"
      IL_0006:  call       string [mscorlib]System.Environment::get_UserName()
      IL_000b:  call       string [mscorlib]System.String::Format(string,
                                                                  object)
      IL_0010:  call       void [mscorlib]System.Console::WriteLine(string)
      IL_0015:  nop
      IL_0016:  call       string [mscorlib]System.Console::ReadLine()
      IL_001b:  pop
      IL_001c:  ret
    } // end of method Program::Main

  4. I won't dig in to the details of the IL, but suffice to say, you can see that the application calls System.Environment.get_UserName() method to retrieve the current user name. Easy enough.
  5. If you need a more developer-friendly code, you can download Reflector (at http://www.aisto.com/roeder/dotnet/). This tool will convert the IL code back to the language of your choice.

Why Do I Need to Worry?

So people can easily get back my source code. So what? Well, there are several reasons why source code is important.

  1. With source code, you can modify and recompile a modified code. This is easier than changing a compiled binary file. To overcome this, .NET have a feature called Code Access Security. With CAS, you can sign a compiled DLL or EXE with a private key. During execution, you can enforce that the DLL you create have the specific sign. Any tampered DLL will have a different sign.
  2. With source code, your intellectual property; like algorithm, process, or even secret, can be exposed. Imagine you have a product key generation algorithm. Anyone with access to your source code will be able to reverse engineer and generate a valid key for your product, without even paying. This is the part where Microsoft SLPS comes in.
     

What is Microsoft SLPS Then?

In short, Microsoft SLPS enables you to encrypt parts of your source code. The encrypted parts will not be able to be decompiled. Second part, Microsoft SLPS also enables product feature management. You may want to create three version of your product with different features (and price). You can easily do this with Microsoft SLPS.

I saved the discussion about how to use Microsoft SLPS in the next topic. For those eager to know may visit Microsoft SLPS web site at http://www.microsoft.com/slps. MSDN Subscribers can request for a limited account to try the service.

Share this post: | | | |
More and More Quality Readings!
12 April 08 11:56 PM | adrian | with no comments

I went to a computer book store today, and found lots of interesting books that we can only download back in Indonesia.

13042008

They are pictured sitting on top of my trusty laptop.

  • The Wisdom of Crowds, James Surowiecki
  • The Mythical Man-Month, Fred Brooks
  • Code Complete, Steve McConnell

I already went 2/3rd of Wisdom of Crowds, after that I'll re-re-read MMM (I went through it twice during my undergrad years - read on computer screen, bad for eyes).

I spent around $200 for all three. This should keep me reading for the next 2 or 3 months... :D

I also found more good books (which I can't buy yet, out of budget):

  • Design Patterns, GoF (this is definitely the next buy!)
  • Refactoring Databases, Scott Ambler

Another book is also coming from U.S. together with my new mouse, it's about the history of personal computer... Fire in The Valley by Paul Freiberger. This book have been turned into a movie titled Pirates of Silicon Valley. Can't wait to read this one.

Share this post: | | | |
I am Hiring
06 April 08 01:58 AM | adrian | with no comments

Yes, I am hiring...

I am looking for several freelancers for the following positions:

  1. Web Designer
  2. Application Developer
  3. Technical Writer

General requirements for all position:

  1. Reads, speaks, and writes English fluently. Do submit proof of English fluency (be it a TOEFL cert, IELTS cert, sample writings, or anything that shows off your English). I am very sensitive to bad English, if you can't read MSDN properly, you are not encouraged to apply.
  2. Have good access to Internet, preferably during meeting sessions (usually Saturday mornings). Anywhere, anytime access is even better. Work is exclusively online, from anywhere, anytime you like.
  3. Citizen of Indonesia. I want the work produced by an all-Indonesian team. Reason: http://wss-id.org/blogs/narenda/archive/2008/04/03/berbuat-sesuatu-demi-bangsa.aspx.

Specific requirements for Web Designer:

  1. I will use Microsoft Visual Studio 2008 and Microsoft Expression Design exclusively. Your Photoshop/Flash/Dreamweaver skills does not count.
  2. Have the ability to create XHTML 1.0-compliant page. If you don’t know XHTML, you are not encouraged to apply.
  3. Have the ability to use CSS 2.1 effectively. If you don’t know CSS, you are not encouraged to apply.
  4. Be able to create a Web 2.0-style design. Do submit proof of your past designs / design concepts.

Specific requirements for Application Developer:

  1. I will use Microsoft Visual Studio 2008 and C# exclusively. Express editions does not count (since we are going to use Team Explorer add in).
  2. Have the ability to write unit test. If you don’t know what unit test is, you are not encouraged to apply.
  3. Have the ability to write code that conform with a written coding guidelines. If you don’t know what coding guidelines are, you are not encouraged to apply.
  4. Be able to write working code to satisfy application requirements. Do submit proof of your past code.

Specific requirements for Technical Writer:

  1. I will use Microsoft Visual Studio 2008 and Microsoft Word 2007 exclusively.
  2. Have the ability to understand a code and write documentation for it. If you can’t do either or both, you are not encouraged to apply.
  3. Be able to write technical document for public consumption (both techie guys and business users). Do submit proof of your past writings.

I will personally test all applicant which passes the written requirements (unlike some lazy HR guy who just skips through applicants who does not have a famous university degree, for example). Accepted applicants are expected to do 5 hour work week, with payment billable by hours worked. Do submit your expected hourly rate.

Accepted applicants will work on an open source product.

Send your application to me, e-mail address below.

--

Adrian Godong
adrian.godong@gmail.com
Microsoft MVP
https://mvp.support.microsoft.com/profile/adrian

Share this post: | | | |
Filed under: ,
Windows 7 Private Alpha
01 April 08 09:30 AM | adrian | 10 comment(s)

I just got the latest bits of the next Windows this morning. I've been playing with it on a Virtual PC on my trusty 10-core laptop.

Here's a little bit of review of what I have found:

You now have access to truly everywhere computing. Microsoft has finally created a product that's true to my vision of future computing. No longer are you tied to a specific computer to do your entire computing task. With Windows 7, all computing is in the clouds (a.k.a. Internet)! Amazon have jump started this trend with Amazon S3 (storage in the clouds) and Amazon EC2 (computing in the clouds). Now Microsoft pushes these two together to build a truly virtual private desktop to users.

How do they achieve this? Well, the OS is built on top of proprietary communication protocol (I don't think this is part of WCF released earlier with .NET Framework 3.5). All processing and storage is done via the network to Microsoft centralized server farm. Local resources are shared via Hyper-V technology to the farm, so everyone gets maximum available performance, limited only by the network bandwidth.

Installation is a breeze, or should I say, installation is instant. Basically it will install every time you boot your computer. The boot up time itself is very fast, since the OS only needs to initialize audio, video, and network devices. Once all three drivers are up, you will see the now-familiar Windows Vista startup animation. They’re still using it to save resources. If you see this animation, you’ll know that audio and video drivers are loaded and running properly.

Next up is network log in. All the functionality is delivered via network. Processing, storage, even logging in is handled via network. You might think Windows 7 will work like Internet browser and Google applications. Well, Microsoft took one step further. By implementing their proprietary communication protocol, you don’t need a browser anymore. Your OS is your “browser”. In this preview version, the Vista taskbar is still there. But if you click the Start orb, what you will get is the list of application available on the cloud. Any computer you use will always have the same application/settings/layout, since all of them are stored in the Internet.

How about USB accessories? If you recall, Windows Server 2008 and Windows Vista SP1 with the latest Remote Desktop version have the ability to forward a USB device to terminal server. In other words, you can do Remote Desktop from your laptop at work to your home server, plug your Zune, and sync the Zune as if it is plugged to your home server. Windows 7 took this approach, so you can plug your USB device from any computer in the world, and it just works! No driver installation is required (after the first one, of course), since the USB port is forwarded. No one can beat this, even Macs!

For applications, Windows 7 preview have very simple applications available; Notepad, calculator, and FreeCell to show off the system’s capabilities to date.

Notepad is just your standard notepad. And since it is based on the existing code, the “bush hid the fact” Unicode trick is still there. Improvement to it is web-based dictionary, spell check, and grammar. These feature use to be available on Word, but since the Web 2.0 era, several web sites provide the service for free. So why not leverage them and put it to Notepad? Dictionary is from Wiktionary, spell check is from SpellCheck.net, and grammar is from proprietary Microsoft service (based on Word).

Calculator is also your standard calculator. Although now it does provide a Web 2.0 finish, there’s a new option of “post to community”, just like the one in Visual Studio. It’s not working yet right now, but I’m envisioning something like community-based home-work discussion portal that revolves around Calculator.exe. Cool.

FreeCell is now multiplayer-only. Since you will need to go online to access it, why not implement a transparent multiplayer lobby? You will have the same problem set, and compete with others to solve it. You now have three empty cells, and four empty shared cells between other three players.

OK, my laptop configuration is a 10-core processor with 10 GB of RAM. If everything runs on the network, then what would my top-of-the-line hardware will be used for? Well, Microsoft knows this, and they are surely tapping it up. While all the operations are being done on the server, what you don’t know is, they forced you to donate your computing powers for public use. So when you’re playing Starcraft 2, one of your units could’ve been rendered on your rival’s processor! This grid computation is derived from Hyper-V technology, again from Windows Server 2008. Microsoft promises to tweak this technology to improve load balancing with peer to peer communication. Since this is a preview version with very few users, my CPU never hit 10% on idle. Memory usage is even lower than Vista, clocking only 50Mb on idle.

I will also hear IT Administrators complain. If everything is stored on Microsoft servers, then how do they manage data security, policy, etc? Well fear not, Microsoft will launch the server part of Windows 7 to corporate enterprises. This server will enable you to act like Microsoft servers. In fact, during log in, you will be able to choose which server you want to connect. You can optionally sync these servers to achieve the same look and fell between accounts on different servers.

Unfortunately under NDA, no pictures/video/screen shot will be available for public consumption. Can’t wait for the public beta!

Share this post: | | | |
Filed under:
Beta Version of Wi-Fi
14 March 08 09:44 PM | adrian | with no comments

I came across an interesting "fact" in the Heroes Happen Here comic strip. A radio is called a beta version of wi-fi, not exactly true, but kind of reminding me over how simple does the past usually is.

Get the comic here.

Share this post: | | | |
Filed under:
IE8B1
06 March 08 04:03 PM | adrian | 1 comment(s)
Post testing from Internet Explorer 8 Beta 1. Acid 2 Test successfull. Download from Microsoft here.
Share this post: | | | |
Filed under:
What is Zune + Heroes?
01 March 08 11:03 PM | adrian | 1 comment(s)

Microsoft made another marketing move for Zune again! The popular series Heroes is releasing the first soundtrack album soon. In preparation for that, Microsoft and NBC will host 5 music videos (taken from the soundtrack) and mix-it with Heroes clips.

The videos will be released as movie podcast here (don't forget you have to install Zune software first, free). Enjoy!

So Zune + Heroes = happy smiley faces on me.

Share this post: | | | |
Filed under:
What's a Facade, Anyway?
24 February 08 11:14 PM | adrian | 3 comment(s)

Some years ago, Norman wished that we conduct a tech talk with a real architect to get the real feel of what an architect does. Well, we never did that, but there's something (actually, a lot) you can learn from Singaporean architecture related to software engineering.

Right now I'm talking about a facade. I'm sure you all have heard or used this pattern. I've heard this once, and then again recently. Both are bad design, IMO. In both design, a business facade is merely a middleman between web service and O/RM. The facade was doing nothing other than being another layer of indirection (which is bad, if done overly). Imagine something like this:

Bad BF

Bad BF 2 

Object has a collection of ObjectB which needs to be populated on load (eager-loading). Every time an Object is retrieved from the web service, the client will need to call the second web service (that retrieves the collection of ObjectB). All calls made by the web service could've gone directly to O/RM, but in this case, we add another layer between them. We don't need it.

So what's a facade, anyway?

An example of a very distinctive facade is an old cinema redeveloped just downtown Singapore.

The Cathay

This is The Cathay. You can find the history of the building on Wikipedia, this is not a history blog.

Back to the topic, you can see the brown, art-deco style part on the center, this is called the facade of the building. It's the front face of the building, covering the massive construction behind it. The idea of a facade is an indirection so that you don't need to deal with the complexity of logic. Security check on the facade doors, for example, will almost screen all visitor to the building.

Taking the analogy to software engineering, a facade should hide the complexity of the logic, too. Fixing the diagram above, it should look like this:

Good BF

Now, the client will only need to call one web service to retrieve Object and all related ObjectB. The facade becomes a composition orchestrator. The facade have the knowledge of what objects required when retrieving another object, the facade have the knowledge of how to retrieve it, too. A facade can call more than one O/RM function, can include logic, but should not call another facade function.

Now that you know have learnt a good facade by example of a physical building architecture, I invite you to start using this analogy when creating a facade. Please save us, developers, from the need of writing a useless middleman code. Thank you.

Share this post: | | | |
Chinese New Year == Reunion Time
09 February 08 10:18 PM | adrian | 1 comment(s)

Chinese people said that new year is the best time for reunion with families and old friends. While I've went back home earlier this week for that, but today something unexpected happened.

Our friend, IT Pro Evangelist (still in 'ay-dash' haha) is touring the Merlion Park, Singapore, with his fiancee, and I happen to be on the same spot at the same time!

Imagine my surprise of finding these two lovers holding hands just beside the water-spitting lion head statue. We chatted for several minutes, then went our own ways.

He is considering a position in Singapore, for a certain company we both know. Best of luck for you!

Share this post: | | | |
Windows Vista SP1 is RTM
05 February 08 09:38 AM | adrian | 2 comment(s)

The wait is over, Windows Vista Service Pack 1 is RTM. Unfortunately though, we won't be able to receive it just yet.

Windows Update download will begin mid-March.

Automatic Update will begin mid-April.

Share this post: | | | |
Third Birthday
21 December 07 09:00 AM | adrian | 5 comment(s)

OK, this date a year ago was the second birthday. This date two years ago, was the first birthday. This date, three years ago, I've started to blog here.

It has been a quick three years! The first post on this third year was about .NET compiler sizes. Now that .NET 3.5 is out, I have recheck the compiler size, and right now csc.exe have grown to 1,545,720 bytes! (some DLLs are gone, so likely they merge everything into single .exe file)

My favorite post is definitely April 1st post. Nobody beats 19 cores CPU + 10Gb of RAM on a laptop, yet. The biggest post (in terms of view and comments) was Windows Vista giveaway. Maybe I should give some VS2008 away later! :D

Happy holidays from rainy Singapore!

Share this post: | | | |
Filed under:
New Language Features
13 December 07 08:14 AM | adrian | 1 comment(s)

So earlier this afternoon I delivered a talk about new language features in .NET 3.5 for Singapore audiences. I admit it's not the best talk I've ever done, even worse, it's not even good.

For you guys who didn't grab the concept or wanted to know more, below is the long explanation about how things should've gone through...

Slide3

First of all, I've created a small console application, to display the result of the code. I can type all code but no result, that's uninteresting. So for the talk, I've created a search application. I have not emphasized this basic functionality of the application during the talk. A search application is the easiest form of querying a collection of data, so it should be very natural.

Slide4

Up next is the "source query" we are going to use throughout the talk. Previously the talk was designed for this query to be put at the final conclusion, where all of the features combined. This time, I tried a different way.

Slide5

The "source query" is then translated to "ordinary function calls".

Note to self: the appearance of Lambda expression there is quite confusing. I should use anonymous method or standard delegate next time (to ease the transition from 2.0).

To make sure that both syntax behave exactly the same, we're going to switch to demo mode to see it in action.

Here's the code for "source query":

return
    from cookie in christmasCookies
    where cookie.Name.Contains(lookup)
    select cookie;

And here's the code for "ordinary function calls":

return
    christmasCookies
    .Where(cookie => cookie.Contains(lookup))
    .Select(cookie => cookie);

If you run it, both will return same result. I can open it using Reflector to see similar code for both function.

Now that you know the syntax equivalence of the "source query", we can move on to discuss each language features that is used to make LINQ actually works...

Slide6

The first and most visible is Extension Method. The methods called in the "ordinary function calls" are one-to-one replacement with LINQ keywords; where for .Where(), select for .Select(), etc.

Extension method enables you to add method to an existing class without limitation of the class' inheritance modifier. You can add method to an abstract, sealed, normal, or even interface.

To illustrate the usage, I've created a simple extension method for speech synthesis. It also outlines the ease of use of .NET TTS engine.

Here's the code:

static class SpeakExtensions
{
    public static void Speak(this string str)
    {
        System.Speech.Synthesis.SpeechSynthesizer synth = new System.Speech.Synthesis.SpeechSynthesizer();
        synth.Speak(str);
    }
}

Now you can make any string to .Speak() by calling the extension method. Take note that you are not subclassing or recompiling the System.String class.

Advanced note: under the hood, extension method uses a concept of static class/method to do it's magic (that's why it has to be declared inside a static class). Static class and static method are basically available to be called from any part of the code (provided you referenced them). Now if one of this method takes an instance of an object and do something to it, you can achieve the extension method behavior. But, using this path will make your code very messy (lots of static calls). Extension method hides (not removes) all the mess under a very elegant syntax.

Slide7

Next huge part is Lambda Expression. This part is almost one-to-one replacement with "source query", because this part encapsulates the logic of the query. On the slide we have two logic, the first one is selection logic, and the second one is output logic.

Lambda expression relieves you from having to define the parameter types and the rigid structure of delegate instantiation. It is actually 100% exchangeable with anonymous delegate or standard delegate.

To illustrate this, I have created a code of how lambda have evolved from delegates.

Here is the "standard delegate way":

foreach (int i in wholeNumbers.FindAll(EvenNumber))
    Console.WriteLine(i.ToString());

...

private static bool EvenNumber(int input)
{
    return (input % 2 == 0) ? true : false;
}

Note that you need to define the named delegates first before you can use them in the .FindAll function.

And here's the "anonymous delegate way":

foreach (int i in wholeNumbers.FindAll(delegate(int input) { return (input % 2 == 0) ? true : false;}))
    Console.WriteLine(i.ToString());

Note that you still need to pass in parameter types (v2.0 is already smart enough to infer the output parameter type).'

And here's the newly invented lambda expression:

foreach (int i in wholeNumbers.FindAll(input => (input % 2 == 0) ? true : false))
    Console.WriteLine(i.ToString());

Note that there are no delegate declaration or parameter type setting.

Slide8 Slide9

Then come the shortcut trio; Object Initializer, Collection Initializer, and Auto-Implemented Property. All three can be easily recognized as syntactic sugar (well, almost all of the new features are syntactic sugar -- it runs on top of v2.0 CLR!).

These features simplify object declaration and instantiation. The first two are easy to understand, auto-implemented property also very simple.

Note to self: I should've written a small program on the fly for the demo. No need to prepare anything. Create classes with auto-prop, and then instantiate it using both initializer, and then output the result to screen.

Slide9

Then come the confusing part, Anonymous Types. It's easy to use this in query, but it's not easy to create a real-world application for this.

Anonymous types enables you to have a strong typed class/type, without the need to declare any of the property, or even better, without the need to declare it.

The question I have not been able to answer is, in real world, when do you need to use anonymous types. In a real world scenario where all business entities are perfectly defined, I don't see any usage of anonymous types. Note that, this feature can be great if you're prototyping some application or creating some object on the fly (and still keep the strong type).

Opening the DLL using Reflector is one way to make sure that the classes are generated on compile-time rather than run-time (thus, keeping the strong typing).

Note to self: think hard on creating a good scenario for this feature demo.

Slide11

The final one is Type Inference. I predict that this will be the mostly used feature since it is both convenient and safe to use.

Type inference relieves developer from the need to specify a type to a field on declaration. The type is inferred from the first assignment. The field is neither variant (can be of any type) nor System.Object (which will need boxing-unboxing process when used).

To illustrate this, I create a simple code below:

var inferredField = 1;
inferredField = "One";

You will not be able to compile the above code since the compiler will infer and declare the field type to System.Int32 (the first assignment). If you're trying to assign a string literal to an integer field, you will get compiler error.

Slide12

But wait, there's another feature? Yes, and it is called XML Literal. Should the previous speaker (name hidden) does not spoil this, it would be the big closure of the day. (hey, no offense man, we didn't sync up on this one :D)

Note: I didn't even bother to put anyting in the slide because of the suspense it creates.

XML Literal enables Visual Basic developer (yes, you read that right -- this is a VB-specific feature!) to copy and paste an XML file into the code as an XML (not string). Not also that, you can also output an XML using this feature. So you can write XML inside your VB code using some XML Literal, some LINQ to XML, and some plain old function call. It sounds mixed up, but it does the job. (And that is what VB does -- the job.)

To illustrate the usage, I created an XML reader in place of the collection initializer:

Dim xmlCookies = _
<ChristmasCookies>
    <Cookies>
        <Id>88653C79-2F49-40fd-9BBD-38EE0B5C69CA</Id>
        <Name>Chocolate Mint Cookies</Name>
...

Return _
  From cookie In xmlCookies...<Cookies> _
  Select New With { _
    .Id = New Guid(cookie.<Id>.Value), _
    .Name = cookie.<Name>.Value
  }

Neat!

Slide13

In Summary, here we have the list of new features I have explained. Just in case someone missed the name of the feature.

Note to self: should tell a little summary about each feature (forgot to do this earlier).

And comes the standard blurb slide. Shameless self-promotion and contact methods.

Done!

(P.S.: In case you didn't notice, you can click on each slide picture to get a bigger view of it)

Share this post: | | | |
More Posts Next page »