Thursday, November 30, 2006

A New Coding Standard

This post is a little off topic, but still interesting.
Instead of fighting Blogger every time I want to add some code snippet, a friend (Mushon saved me again ;)) sent me a nice tool called The Syntax Highliter, which is a set of javaScript libraries that automatically color your code!

Although it took me quite some time to make Blogger like my jscript code, but finally they became friends once again ;)

Here's an example:



All done!

Wednesday, November 29, 2006

FW 3.0 Enhancements

The .Net framework 1.1 was basically a big service-pack for 1.0, and 2.0 brought the Generics concept, but mainly focused on enhancing ASP.Net.

.Net 3.0 does not focus on a specific side of the framework, instead its goal is to enhance the flexibility of the language itself.

Lets have a look at some of these enhancements:

Implicit Variables
As minor as these feature might look, other features like LINQ rely heavily on it.
In C# 3.0, there's a new variable type - var (variant).
When a variable is declared as var, it's type will be chosen by the compiler based on the first variables initialization.
For example:


var x = 5; //the compiler will deal x as a simple int.

The only limitation is, that a variable declared as var must have an initializer,
For example, the next line will produce an error:
var x;

Note: Using implicit variables as a norm is NOT good, not because of performance issues (no boxing is made), but the code is less readable and you get minimum to no design-time support.

Anonymous Types
Following the implicitly typed variables, a complementary step is the ability to create an implicit type.
Lets have a look at the following code:


var myself = new { FirstName = "R", LastName="Stern", HasBlog=true};
var other = new { FirstName = "Slash", LastName="The" HasBlog=false };


I defined 2 implicit variables, and instantiate them as a new type that has 2 string properties and a Boolean.
If we look at the IL generated by this code, we'll get:


class __Anonymous1
{
private T1 f1;
private T2 f2;
private T3 f3;

public T1 FirstName { get { return f1 ; } set { f1 = value ; } }
public T2 LastName { get { return f2 ; } set { f2 = value ; } }
public T3 HasBlog { get { return f1 ; } set { f1 = value ; } }
}


Notice the compiler automatically generated a getter and a setter for each property in our type.
Furthermore, since both variables - myself & other has the same initializers, they are considered of the same type!

Lambda Expressions
Lambda expressions allows us to take anonymous methods to the next level.
Instead of writing these methods in the standard "verbose" way, why not simple describe it?
For example:
Instead of:


// get an array of string items in the collection that equal to 'A'
string[] AStrings = col.FindAs(delegate(string str)
{
if (sItem[0] == 'A')
return true;
else
return false
;
});


Consider the following:

string[] AStrings = col.FindAs(Func<string,bool> f = str => sItem=='A');


I'll continue the post tomorrow with some more examples.

WCP (Indigo) First Steps

To be honest I haven't tested it yet, but I thought I'd let you read it too until I post a proper post about it:
WCP Walkthrough

Tuesday, November 28, 2006

C++ Calling .Net

C++ & .Net

Calling COM objects from .Net is very trivial using the interop.x assemblies or by creating the wrapper classes mannualy using the tlbimp.exe utility supplied by M$.

But, what about the opposite direction – it doesn’t look that simple at all…

Well, Appararently it is.

First Step: .Net Side

First thing, in order for a .Net class to be exposed to unmanaged code, there are some steps needed.
First, we need to assinge our project with a strong file.
Add the following line to the AssemblyInfo.cs file:
(in VS.Net 2K5, you can do this in the properties page)



[assembly: AssemblyKeyFileName(@"C:\Sternr.snk")]


Next, we need to tell the VS.Net to register it as a COM object, using the "Register For Com Interop" checkbox in the Project Settings.

Ok, now we need to create (if you don’t already have!) an interface for each class we want to expose.
Both the interface and your class should have the following attribute:


[System.Runtime.InteropServices.Guid("YOUR-GUID")]


Notice: Each one of them should have a DIFFERENT GUID

The C++ (unmanaged) Side
Add the following to your code:
(remmember to change from IDotNetClass to your interface name)


IDotNetClass *dotNetInstance=NULL;

/* Initialize the COM Server */
CoInitialize(NULL);

HRESULT hr;
/* Create the instance of the .Net object */
hr = coCreateInstance(CLSID_DotNetClass,
    NULL,CLSCTX_LOCAL_SERVER,
    IID_IDotNetClass,reinterpret_cast(&dotNetInstance));

if (FAILED(hr))
{
//TODO: Add error logging
return;
}

/* And that's it - call your .Net methods like any COM object */
dotNetInstance->MyFunc(myParameters);

/* Finalization code */
dotnetInstance->Release();
CoUninitialize();


And that's it!
Aint so hard isnt it?
For further info, or the source code of an example project, mail me

Sunday, November 26, 2006

DataBinding Model In ASP.Net 2.0

Here's a good MSDN article by Espozito about the DataBinding model in ASP.Net 2.0 with focus on the DataSorceObject.

Really worth reading, especially for 1.x developers.

Wednesday, November 22, 2006

Aspect Oriented Programming

AOP - Aspect Oriented Programming.

One of the main reasons to use OOP, is for the SoC (Separation Of Concern) - the ability to separate each "problem" into an object (class).

This approach is well-suited for most tasks, because many problems can be easily and naturally described by objects.

But sometimes there are aspects of the problem which can't be encapsulated: they somehow cut through the whole object model and you won't be able to take them out into separated objects - for example - (you guessed it) logging.

Although I've got only one logging class in my system, almost every other class needs logging abilities.

In my examples, I'm using the NAspect framework, although there are plenty of other AOP frameworks for .Net.

Defining Aspects

First off, I define the interface of my class, and mark the wanted methods as logging enabled:


public interface IMyTestClass
{
    [Log()]
    void DoStuff1(out int a);
    [CheckSecurity()]
    int DoStuff2([Parameter()] int a);
    [Log()]
    string DoStuff2(int a, [NotNullParameter()] string b);
    int SomeProperty { get; set; }
}



Now, in my code, I first need to configure my AOP engine:


IEngine c = ApplicationContext.Configure();




And request a new MyTestClass object from the engine:


IMyTestClass t = c.CreateProxy(typeof (MyTestClass)) as IMyTestClass;




And that's it – now I write my standard code with logging enabled:

t.DoStuff2(1);
t.DoStuff2(2);

The example I've shown here is prety simple and not complete, but it should let you a small glimpse at how AOP is looked like.

You can download the the code for the example here

As I said before, there are many AOP frameworks for the .Net framework out there, 2 of my favorites are: NAspect of the Puzzle Project and the Aspect# of the Castle bulk.

Monday, November 20, 2006

Multiple IE's

A few days ago, I've finally given up and installed M$'s new browser - IE 7.

Oh the horrors the horrors.

Not only it's horribly slow, has NO tabbing customization and tends to get stuck, but since M$ has changed it's user-agent (which is basically a good thing), I cant use TestDirector which, it turns out, supports ONLY IE 6.0.

Anyways, I found (thanks to Mushon ;)) a nice cute utility that allows you to install older versions of IE - including 5.x & 4!
Although IE 6 acted a little bit different (some script errors etc.), it gets the job done - TestDirector and I are friends again ;)

Download Multiple IE's

Sunday, November 19, 2006

Web Controls Access Modifiers ASP.Net 2.0

In ASP.Net 1.x, when you drag a new web-control to the page, the controls declaration would be added to the code behind as follows:

protected TextBox txtTest;

On ASP.Net 2.0, the control definition is in-accessible, hence in order to change the modifier of a specific control, you must encapsulate it inside a property or a method, i.e:
public TextBox txtTest
{
get {return _txtTest;}
set {_txtTest=value; }
}

On one hand, yeah this pretty stinks, but on the other it makes more sense, I mean after all what's the difference between a control and a private member?

Client Side Logging

Server-side logging is pretty much old news - whether it's log4net, NLog or the .Net trace - you wont see an application without a logging framework\utility.

But while developing Web applications, most of our code will be executed on the browser, so no matter how strong our logging utility is, it wont cover a hole bunch of our code.

There are many solutions for this problem, and I'll cover 2 of my favorite.

Log4JavaScript
Log4JS's main goal is to have identical code for logging whether it's on your client side or - server side.
In order to do so, Log4JS implements almost fully the Log4J API.
For example:
In order to obtain a logger object, I request one from my repository:

var log = log4javascript.getLogger();


Then I configure my desired appender:

var popUpAppender = new log4javascript.PopUpAppender();
popUpAppender.setNewestMessageAtTop(true);
log.addAppender(popUpAppender);


And finally write to the log:
log.debug("Hello world!");


Pretty neat if you ask me ;)

JSLog
JSlog is a lot simpler and less customizable than the Log4JS but it still gets the job done and is very pretty ;)

There are many other client-side logging utilities but basically they're all the same.
But the question still stands - is client-side logging useful???

Saturday, November 18, 2006

TestDriven.Net NEW Reflector Add-In

Before I start about the real subject of this post, if you're not already intimately familiar with TestDriven.Net and Lutz's .Net Reflector, you should stop reading this post, download them, USE them and come back here for more ;)

The new Reflector add-in, not only integrates Reflector inside the VS.Net intellisense, but will automatically put you in the same method on the same assembly you're standing with your cursor.
OK you're probably saying - that's cute, but... I can just look at my IDE and see the real thing?!$#@!
You're a real smart-ass you know that???
You can now run (every) .Net assembly, attach a debugger to it (using VS.Net) - even if you don't have it's symbols or code, activate the Reflector add-in and vuala! you're standing on the actual code of the function you're currently running!

Don't believe me?
Try for yourself

For further information you can go to Jamie Cansdale - the creator of this brilliant add-in.

Well done Jamie! ;)

P.S
Jamie has posted a link to a live demo of the add-in

Friday, November 17, 2006

To DataSet Or Not To DataSet

The DataSet object is nice. really. it has many features.
But I Hate It.

Why DataSet Is BAD
1. Separation Of Concerns: Using the DataSet makes your business or even the ui tier strongly bound to the dataAcccess, because a change in the order or the name of one field in the query will break the data structure of the DataSet.

2. DataSet Is NOT a part of your Domain Model - In order for the DataSet to be generic enough to contain every possible query result, it was build according to the lowest common denominator - which is the structure of a query result - a table.
Because of that, after building the DataSet I need to map it's table-data to the real structure it represents - for example a PersonDM object, which means I'm basically reading the data twice - once from the DB into the DataSet and again from the DataSet into my PersonDM.

3. Too Much Data: The dataset contains useful data - besides the raw query data, for example - db constraints etc., but mostly this data is NOT used! unused data = bad data.

4. Performance - Although it has been greatly improved in 2.0, the DataSet object still has many wonderful features and hence is still pretty "heavy".

So Should I Never Use DataSet???
No, there are many times when using a dataset is a good choice (or even the only choice).

When working with Databases, there are 2 "mode's" of work: Connected & Disconnected.

While disconnected, the use of dataSet is not only recommended but a must!
Think of a client-server application that in order to show a simple grid it needs to connect to the remote DB Server and query it.
In this case, working with dataSet will greatly improve your performance - instead of running row-by-row like the DataReader, you query the database only once receiving bulk data into the DataSet.

The problem is, that Web applications - for that matter (only),belong to the connected environment category - because our client is the WebServer and not the browser.

Conclusion:
The DataSet is a very rich object, so much rich that mostly it's an overhead.
Before choosing whether to work with DataSet or DataReader, check first whether your application is connected or disconnected.

Just my 2 penny's on DataSet ;)

Thursday, November 16, 2006

Dojo Framework

That's it, I've got to say it out load...
I HATE CLIENT SCRIPTING!!!
And because of it, I'm in a constant search for utilities\libraries\work-arounds\framework basically - anything that will help me with it.

Dojo is a JavaScript toolkit that offers a full set of (client-side) controls and utilities.
Just a small warning before I continue - Dojo has nothing to do with .Net or any other server-side language\technology - it's simply put a client side framework.

What Does It Do?
Dojo offers a set of controls called widgets, a rich event system that supports more complex use (i.e overridden events), validation support (i.e: simple declare dojo.widget.validate.UsZipTextbox), call-back manipulation support (i.e hidding it using XMLHttpRequest) And much more.

The Dojo framework is very rich, but it still encourage you to write client-side code - although it's not the ugly standard jscript ui games, but still - client scripts are client scripts...

Oh well - keep on looking...

Wednesday, November 15, 2006

Web Vs. Win - Web Nockout?

There are many advantages and disadvantages for Web over Win development, but always the main reason not to develop web-based applications is the all known too well client side scripting aka JScript hell.
Writing and maintaining java script is simply put, a hell on e... IDE.
But then I found this cool new tool\technology called Script#.

Script# Is a project led by on of the ASP.Net architect team (Nik Hilk.net) that is aiming to create a C# compiler that outputs pure javascript code.

How Do I Do It?
You open a new VisualStuido.Net (2.0) C# Script# Project (the script# project template is a part of the binary download), and you write your C# code of-course with FULL ide support, and upon building the project, instead of getting a *.dll in your output folder, you get a *.js file ready for use.

As well as the compiler, Script# also has some extra utilities and useful classes.

The Script# is pretty far from my wet dream (if your wet dream also has something to do with Java script, than you've got some REALL problems!!!), of no client side scripting, but it's worth reading about.

Tuesday, November 14, 2006

MagicAjax (Ajax #2)

Continuing My pursuit, I'v found another Ajax framework - MagicAjax

MagicAjax.Net is a OpenSource ajax... "utility" that very much looks like a withered version of Atlas.

MagicAjax (has a cool name and ;)) is constituted by 2 parts:
1. MagicPanel: A container WebControl, that catches PostBacks made by its Child Controls, and sent to the server as an AjaxCall (hidden post-back).

2. MagicHandler: An HttpModule that receives the AjaxCalls made by the MagicPanel, and executes the corresponding Server-Side code, and sends back to the client only the changed HTML.

Basically, MagicAjax is a pretty thin Ajax layer, but is very easy to use, and has many customization abilities such as Async requests support.

Another thing, on my last Ajax post, I've talked about the ComfortASP library,
Well, I found a VERY big "bug" - every XMLHttpRequest made returns an error!

After talking to the developer, apparently it's by design - I didn't get any more detailed reason why.

Oh well, back to sketching board...

Monday, November 13, 2006

Windsor IoC

A Couple of days ago Oren Eini has posted a really interesting article on MSDN about the InversionOfControl design pattern, or more specifically about the Windsor OpenSource IoC Framework.

Although this article is very good, for a deeper drill down into the design patter, I'd recommend reading Martin Fowler's article.

The Windsor IoC is a part of the Castle Project which is a pack of OpenSource library\frameworks for .Net (i.e ActiveRecord, MonoRail etc.).

The Castle project goal is to guide .Net developers how a project should "look" like, starting from the UI tier to the Service Layer.

Although this post started about the Windsor framework, I'd recommend reading about the Spring.Net which is a port from the Java Spring framework.

The Spring.Net is still in it's beta status, but it's transaction model is already running and is a reall state-of-the art design work.

Sunday, November 12, 2006

Ajax Framework's

On my search for the "Ultimate Ajax Framework", I've stumbled upon a prety nice, and more important - free (though not OpenSource) library called ComfortASP.

ComfortASP is a non-intrusive Ajax framework, meaning the only thing you need to do, is simply inherit from the base ComfrotASP page, instead of M$ System.Web.UI.Page, and... voila! you'r a fully-compliant ajax app! ;)

How Does It Work?
Every PostBack made on a ComfortASP enabled page, is caught by the framework and sent as a XmlHttpRequest.

On the server-side, the ComfortASP_Page "catches" the request and handles it like a normal post-back, thus supporting all server-side events etc.

After all your server-side code is executed, the ComfortASP_Page sends back to the client only the delta of the html (compressed of-course), thus reducing bandwith, speeding up the client side work, and replacing only the changed parts in the HTML.

Besides that, ComfortASP keeps a "stack" of all the postback made on each page to enable the browsers back action (damn! that nice).

The main goal of ComfortASP is not to give you a set of tools or controls with Ajax "abilities" like other frameworks (i.e Atlas), but instead - you write you'r ordinary ASP.Net code and I'll take care of the rest.

Worth a shot

http://www.comfortasp.de

First Post

WOOT!