Friday, September 26, 2008

Hi! I'm sorry for the long absent of this series continuation. Before this, I have provided you a quick glimpse about concepts behind .NET type system. Now, I'll bring you the previous local variable type inference, method extension, and query comprehension (query syntax) in a "walkthrough" style of LINQ.

The journey to get there, the LINQ in C# 3.0 and VB.NET 9.0 is quite a long and full of what-the-heck-of-these roads.

LINQ actually contains:

Local variable type inference

Extension methods

Query comprehension

Some cool functional programming constructs, the Lambda expressions and closure

A cool subset of "dynamic" programming feature, expression tree

I don't know whether this fact is good or bad, but C# 3.0 and VB 9.0 have this interesting fact: these guys know how to "steal" the good things from outside of the realm of imperative programming and incorporating them into the language, without ever changing the CLR of .NET 2.0!

Quick overview of functional programming

What is functional programming? According to many sources, including Eric Meijer of Microsoft, functional programming is programming with functions, in terms of mathematical functions.

What is a function in a math term, really?

A function is, a computational operation that can have input and return an output.

A simple example of this, a simple x multiply by 2 function that has parameter "x" and returns a result:

f(x) = x *2

This function means do operation multiplication by 2 with parameter x, then return y as the result. These parameter and result should be typed, since it has to be meaningful type.

Sometimes, the f(x) is transferred to another symbol such as y:

y = f(x) = x * 2

This y, is simply a variable.

Again, y and x should be given a type, or simply put, a strongly typed. There were numerous debates about this, since dynamically typed languages such as Javascript and Ruby have these function notation but they are dynamically typed, not strongly typed.

And it read: "f is a function of x to y that has operation of x times 2", but the expression below.

This notation is so close with Lambda calculus notation which forms the base of the Lambda expression in C# 3.0 and VB 9.0:

in C# 3.0:

y = f(x) => x * 2

in VB 9.0:

Dim y = Function(x) x * 2

Now, enter the world of functional programming. Functional programming is simply translating those notation into programming languages that functional such as Haskell, Scheme, and F#. Yes, we now have functional programming notation in C# and VB, but it has no type declaration. Why? Because the type of the return value and the parameter are inferred. The compiler simply translate the return type into the right hand expression.

This is why this is called type inference. The best part of this, type inference not just give you less noise about giving type declarations, but it makes your code less bloated, and then further expands into expressions and later into expression trees.

Functional programming often discusses about avoiding global states and effects. What are states and effects, really?

States mean that the value of variables. and global states mean that these variables have values in context of global (public static in C#) that in functional programming tries to avoid. Why? Because variables when they're treated as globals, they will affect the whole function execution. These give the notions of side effects, such as the current time and date of system.

What the hell is this? Then why do I have to take care this?

Well, functional programming can’t really have the freedom of mutable and immutable states, and then effects or in term of functional programming, side effects.

Let’s say if I have:

f(x) = x * 2

If I have set the x parameter by 3, then I’ll get 6, since 3 *2 = 6. This function is a real function, since I gave 3 and I will always get 6 as a result. Every time I call this function, I will get the same result and it modifies nothing else.

That’s why this simple function is defined as a pure function, a function that has no side effect because it has no other modified result.

What if I have this:

f(x) = DateTime.Now.Second

Can you guarantee that you’ll always have the same result?

Then this function is not pure, and it can’t give the same result every time I call it. Why do I care about this? Because it’s simply this notion that functional programming always care about the states and effects, and it’s contrary with imperative programming that always embrace states and effects.

Then, what about states?

Imperative programming has a degree of freedom to deal with mutable states, in a simple term is simply a mutable object, the one we often use in C++, C#, VB, and Java. But in functional programming, a mutable object and immutable object are treated carefully.

The function above is a sample of changing global state. DateTime.Now is a public static definition, and any functions that evaluate this will also modify the value, since it gives you current date and time, and of course current date and time is always changing.

DateTime is not just one effect. In a real situation, these are effects:

Input Output (I/O), such as writing to and reading from files and console.

System state, such as date, time, and handles and other operation that depends on these such as randomize. And this is simply an I/O effects too.

Exceptions (since it halts and changes the execution)

Some of you may ask, if I can’t have these, then my program is somehow disabled. Since you can’t do anything exciting with your program. And then it’s not fun anymore since you can’t compete with imperative programming.

But functional programming handles these restrictions using monads and giving the notion of explicit declaration of effects throughout its codes.

Sadly enough, many experts out there embracing pure functional programming and tries to remove side effects completely. The best approach is taking the extreme of purity into a less pure by allowing side effects but you have to declare it explicitly. As Eric Meijer from Microsoft call this, a honest function.

So, instead of writing this function in C#:

int GetCurrentSecond()

you should state that this function is a side effect of I/O that also give you integer:

IO<int> GetCurrentSecond()

This is quite simple, isn’t it? :)

But in C# and VB, you don’t have the notion of declaring that this function may gives exception. You don’t have explicit notion such as “throws” in Java.

Sunday, August 10, 2008

Yes, Silvelight 2 hasn't been released yet, and it's currently in Beta 2.

If you have Firefox 2 (at least 2.0.0.7), Silverlight 1 or 2 runs peacefully and quite the same with Silverlight 1/2 on IE. But on Firefox 3, Silverlight runs but does not run!

Why? This definitely happens to be a bug in Silverlight.js, the script that's needed to prepare <OBJECT> for your Silverlight app. The bug is called "race condition". Initially, Microsoft had announced that this bug is on Firefox 3, but this time they have admitted it's a bug in Silverlight.js via blog entry of Nigel Parker in MSDN:

What this means is that the forthcoming Firefox 3 release will break some Silverlight 1.0 installation experiences on web sites that use the original Silverlight 1.0 SDK Silverlight.js detection file.

The Silverlight 2 SDK has an updated Silverlight.js file that not only solves this problem for all versions of Silverlight but also eliminates browser restart that was previously needed for new installs.

Thumbs up for Microsoft! But, I think this updates needs to be synchronized in all sites, especially on Microsoft's heavy multimedia developer and it-pro community sites such as Channel 9, Channel 8, On10, TechEdge. And if you read the above 2nd paragraph, they had blamed Firefox and they have quickly clarified it.

If you want to get the latest script updates, you can visit the MSDN Code on the above link.

Seeing that that blog entry was quite a long time, "Tuesday, June 17, 2008", when can I see my streaming video on these heavy Silverlight sites (including Channel 9) on Firefox 3, hey Microsoft?

Monday, June 9, 2008

First, I admit that I have very long silence after my last January 2008 entry. I've been busy doing my software development projects and balancing between my family leave.

Before I continue about the next series on LINQ, I want to clarify type system in .NET 2.0, 3.0 and 3.5.

There are these jargon/buzzword or programming language term in .NET and others:

Statically typed

Strongly typed

Implicitly typed

Dynamically typed

First of all, type system in CLR 2.0, the CLR that's first been brought by .NET 2.0, and has been available since .NET 1.0, is statically typed.

Statically typed means once you define a type of a field or a variable, it can't be changed afterwards. This is heavily related to a strongly typed concept.

An easy example is how the variables, properties, fields in .NET are declared. It's always mention the type declaration first, and then the Type will be "forever" glued to the object it declared.

Simply put, if you have variable:

TableLayoutPanel tablePane = newTableLayoutPanel();

The tablepane has typed TableLayoutPanel, and the type can't be changed later in runtime. Only then can be upcasted to a higher level object (derived object).

Strongly typed means statically typed variable that has more specific type assigned to it, instead of just Object type. The use of Object type is often not recommended, since it can mean any types.

Strongly typed has many uses and can be easily understood in using collections. Generic collections are very good samples of strongly typed concept.

For example, instead of defining this:

ArrayList arrayint = newArrayList();

It's more strongly typed to use this:

List<int> listint = newList<int>();

Why? ArrayList contains a list of objects. This means a bad practice, since you can just add any kind of types into an ArrayList. List<T> (generic List) is better, since the member of List is a typed T, just like the example above.

Strongly typed are also more efficient in performance, since it requires less casting.

Now, what is implicitly typed? Sadly enough, there are less conversation about this concept. But deep inside CLR 2.0, there is one good sample, array. An array, as documented in MSDN, is derived from IEnumerable, IList, ICloneable, and ICollection.

"In the .NET Framework version 2.0, the Array class implements the System.Collections.Generic.IList<T>, System.Collections.Generic.ICollection<T>, and System.Collections.Generic.IEnumerable<T> generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools. As a result, the generic interfaces do not appear in the declaration syntax for the Array class, and there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException. "

See? This is, by any means, is implicitly typed. Therefore, if you have:

String[] is simply an implicit type of Array<String>

Int32[] is simply an implicit type of Array<Int32>

What about dynamically typed? Dynamically typed is easy, it's simply an object that can have any type, or an object where its type can be changed dynamically at runtime. You can spot this in a JScript or JavaScript language. It's also heavily used in Python, Ruby, and others.

Now, I'll bring you more heavy use, samples, and best practices of these conceptual terms in my next installments of quick thoughts series. :)

Thursday, January 24, 2008

Ahh... I enjoy the comments on my other previous post, part three of my quick thoughts. I hope it really open the minds of Indonesian software developers about .NET progress and its current/latest features.

"Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type."

Yes, you can add methods to existing types. But this addition has its own requirements, not just simple "add".

Take look at this sample code in C# (from MSDN):

///<summary>/// Extension methods must be inside of a public static class///</summary>publicstaticclassStringExtension1 {// This is the extension method.// The first parameter takes the "this" modifier// and specifies the type for which the method is defined.publicstaticint WordCount(thisString str) {return str.Split(newchar[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length; } }

classProgram {staticvoid Main(string[] args) {string s = "The quick brown fox jumped over the lazy dog.";// Call the method as if it were an // instance method on the type. Note that the first// parameter is not specified by the calling code.int i = s.WordCount();Console.WriteLine("Word count of s is {0}", i);Console.ReadLine(); } }

As you can see, String has additional method, WordCount(). It returns number of words in a hard coded sentence as a value of String s. There's no magic here, only the compiler can decide at runtime where to look for this method, after searching through static classes. The static classes doesn't have to be in the same namespace as your code. After it find the method, it translates into an execution of the static method of StringExtension1 class at runtime.

Still, the conclusion is, this is a proof that there's no change in CLR since CLR in .NET 2.0. A language features? No. It's more correct if you simply say it as a compiler feature. Why? Since it's more emphasized in compilation time.

The requirement of extension methods are (also as step by step guide, taken from MSDN):

Define a static class to contain the extension method.

The class must be visible to client code. For more information about accessibility rules, see Access Modifiers (C# Programming Guide).

Implement the extension method as a static method with at least the same visibility as the containing class.

The first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier.

In the calling code, add a using directive to specify the namespace that contains the extension method class.

Call the methods as if they were instance methods on the type.

Note that the first parameter is not specified by calling code because it represents the type on which the operator is being applied, and the compiler already knows the type of your object. You only have to provide arguments for parameters 2 through n.

The sample above is an extension method that has no parameter. What if I want parameters?

classProgram {staticvoid Main(string[] args) {string s = "The quick brown fox jumped over the lazy dog.";// Call the method as if it were an // instance method on the type. Note that the first// parameter is not specified by the calling code.int i = s.WordCount();Console.WriteLine("Word count of s is {0}", i);String str1 = DateTime.Now.ToLongDateString();String str2 = str1.Greetings("Eriawan", "Mister");Console.WriteLine(str2);Console.ReadLine(); } }

Pretty cool, isn't it? But one thing is, be careful with the name of the extension method. You can get errors if you extend some type that already has some extension methods with the same name somewhere else in your project.

Tuesday, January 15, 2008

I can just declare variable without typing?

On my previous post on LINQ, I discussed quick overview of LINQ. If you read the code, there are many uses of "untyped" variable, I just used var in C# or Dim in VB.NET. This is also one of new features of VS 2008. This feature is known as "type inferencing".

"When used with local variables, the var keyword instructs the compiler to infer the type of the variable or the array elements from the expression on the right side of the initialization statement."

Also MSDN of VB.NET says:

"By using local type inference (also referred to as implicit typing), the compiler determines the data types of local variables based on the values that are used to initialize them."

Yes, they're both the same context and concept. The point is, the type inferencing is not .NET 3.5 new features. It's simply a language feature. But I decide to discuss it here since it's often in describing LINQ samples used throughout MSDN for VS 2008. Type inferencing can be used for primitive types such as integer, boolean, string. Complex types such as arrays and collections or just classes of IEnumerable are welcome.

Although there are many ORM product that's been trying to solve this and in some degrees they solved it, none of them offer the deep integration of query language inside the general language programming such as C# and VB.NET. As a side effect, many has asked, "Is ORM tools dead?" But none of this make enough sense for me. LINQ is not meant to kill other ORM tools! Believe it or not, comparing to some aspects of IdeaBlade DevForce and Wilson's ORM, LINQ is still a long way to go, and LINQ shouldn't be used alone.

Some sample uses of LINQ

This is the easiest sample of LINQ, try to do SELECT query. I'm now querying the available (collection of) running processes in my computer (yes, LINQ can query collections).

First, make a Console project using C# or VB.NET before running this sample.

Those two codes above will display current running processes on your machine with the id and working set. You can also display ProcessName if you want to. It's simple, right?

Actually, query variable is of type IEnumerable<T>. This means you can treat query as a collection and it's also queryable.

Now, enough introduction. LINQ is actually consisting of:

LINQ to Objects (it's the sample above)

LINQ to SQL (DLINQ)

LINQ to XML

LINQ to DataSet

LINQ to Entity (part of the ADO.NET Entity Framework)

Note, that LINQ to SQL only works for SQL Server 2005 and above, but not for others such as Oracle or IBM DB2.

If you're using VS 2008, you can code using DLINQ generated object and have them queryed directly. Later post on more on DLINQ.

But, there'll be more about .NET 3.5! I'll try to bring you more LINQ and the other new goodies in .NET 3.5.

What about .NET 3.0? In future posts I'll also make some flashback to .NET 3.0, where the buzzwords are WPF,WCF,WF, and CardSpace (although sadly enough there are very little examples and resources about CardSpace).

Remembering .NET 1.x

There, you can begin to delve .NET from outside view of non software developers.

Now, why do I call "Quick thoughts on .NET 1.x" instead of .NET 1.0 and .NET 1.1? Basically, the releases of .NET 1.0 and .NET 1.1 are essentially the same, although the language features from C# and VB.NET perspective, are different. The CLR is also the same between release of 1.0 and 1.1.

.NET 1.1 is basically adding minor new features while also squashing bugs in .NET 1.0. .NET 1.0 is of course the first release of .NET. Microsoft has long planned .NET Framework long before the release of Visual Studio 2002 (a.k.a VS 7.0). My interest and curiosity about .NET was awakened after I saw an article on BusinessWeek in late 1999. I forgot the exact date, but it had the cover of two Microsoft employees were setting up a .NET logo flag!

It was a huge bet for Microsoft, since it was dubbed as an application platform, and it's somehow could bring confusion to existing Microsoft platform of Win32 API, while facing the fact that web itself was becoming a platform too. XML was also the center of

In 2000, in MSDN Library online or offline version (from MSDN subscription), Microsoft began to provide many articles and preliminary documentation of .NET. The namespaces, class names, were quite changed many times. In July 2001 of MSDN Library (offline) edition, .NET was added as .NET beta documentation. At that time, .NET 1.0 namespace changes was frozen, but class name changes were there, but only small changes.

As always, Microsoft makes gimmicks and beta documentation of their products, but they often got the fact not yet released for public.

But after the introduction of Visual Studio 2002, many things had happened.

VB 6 developers were revolting!

Sadly, on the VB 6 programmer side, it makes some of old VB 6 developers to be left in the cold. VB.NET is a whole new programming concept, although the basic language keywords are remain the same. As a result, there is a VB petition from many die hard VB 6 MVPs and developers, but I assume some of you will ignore this. Let's just say from Robert McLaws perspective, don't be a spoiled brat of being a Microsoft MVP. I believe many of you, including me, are not MVP, but we have a good spirit of software geek, including always and continuous learning and coding, right? But in the end, the choice is ours to make.

As a matter of fact, in my objective opinion, a petition of voicing concerns of many huge bases of VB 6 developers is definitely a good thing, which means that MVP has to be independent from Microsoft.

Okay, we had .NET 2.0 in 2005 back then...

In early 2004, again, Microsoft had begun voicing the next major release of ,NET 1.x, the .NET 2.0. Some of my .NET 2.0 early adopters friends told me that they began toying with .NET 2.0 in late 2003. But in MSDN Library April 2005 edition, Microsoft stated that .NET 2.0 was frozen (in features) and would be released soon.

But what makes me quite disappointed even until now, that offline version of MSDN Library is always only geared toward .NET specific release and Visual Studio specific release, instead of giving enough time to make transition between releases. But sadly, in MSDN Library that is specific for Visual Studio 2008, you still find many old articles of .NET 1.x. What I want is, if it's really geared toward .NET 3.5 and Visual Studio 2008, why do I still have megabytes of .NET 1.x article references? But, you can download MSDN Library for Visual Studio 2008 freely, anyway. Be patient if you have really slow Internet connection, though. Since it's about 2GB in size. If you have a good/decent connection, you can always view online MSDN Library.

.NET 2.0 brought a newer CLR, and although it's backward compatible with .NET 1.1, you should recompile your source in .NET 2.0 if you want to migrate it smoothly. Don't take any risk! Because .NET 2.0 has different CLR and this means different IL (.NET Microsoft Intermediate Language) to handle. That's also a runtime backward problem. For example: don't try to run/debug .NET 2.0 executable program in .NET 1.1 environment. It won't work.

One notable features that brings the new release on both .NET 2.0 and Visual Studio 2005, is the inclusion of Generics. This is one of my reason of deciding which platform and which platform's version have.

Thursday, January 3, 2008

Yes, the current version of .NET is .NET 3.5. It contains new features, but the most notable new feature is the release of LINQ, Language INtegrated Query.

First, let's talk about CLR in .NET 3.5

But before I delve more deep, let's see the fact that there's no new CLR for this release (3.5) since .NET 2.0. Again, Daniel Moth has brought us quite deep explanation about this. But this is quite a relieve, since the incompatibilities of .NET 1.x and .NET 2.0. I remember when I was finishing ASP.NET 1.1 project, my client's web hosting quietly changed their .NET version to 2.0. And then ASPX pages stopped working, since almost all of them displayed errors and exceptions. (I won't share the name of my client's web host, but email or message me in private if you want to).

I'm happy that there's no new CLR at this moment of 3.5. There are (yes, even until now, not were) some irrelevant arguments about whether there's a new CLR or not. If you find news about new LINQ and new CLR, and if there's somebody thinks new that new language keywords == new CLR, you're dead wrong! LINQ and .NET 3.5 don't bring new CLR. These new language keywords and hence, constructs, are not bringing new CLR. These new keywords of LINQ in C# 3.0 and VB 9 are just language features. Your new CLR of 3.5 still run under .NET 2.0, unless you're using newer class libraries of .NET 3.5.

Can I have the illustration about this?

Yes.

On many occasions, Microsoft's bloggers often mention red bits, green bits, and some additional features in .NET 3.5. Somasegar, the VP of Dev Division at Microsoft, also discussed what these color bits mean.

Hmm... looks like more and more headache concerning new technologies? Fear not, there are numerous resources of .NET 3.5 for us. From that simple Venn diagram above, it's clear that .NET 3.5 is also .NET 2.0.

So, there's no standalone .NET 3.0 SDK to download. Another sad thing is, there's no standalone .NET 3.5 SDK to download at this time. .NET 3.5 SDK will be included in release of Windows 2008 SDK, which is about 1.3 GB in size!

Try to download Windows 6.0 SDK? It's whopping 1.2GB in size! Unless you have broadband connection at least DSL, you should wait for VS 2008 Standard Edition or Professional Edition to be sold worldwide, or you can get them if you're MSDN Premium subscriber.

Wednesday, December 5, 2007

I already have some blogs before, but this blog is only specific for .NET 2.0 and above technological knowledges and experiences. It may contains some of new .NET technologies such as WPF, WF, and many other things such as LINQ and ADO .NET Entity Framework.