Monthly Archives: June 2007 - Page 2

ASP.NET Master Pages Tips and Tricks

Really nice article by Dan Wahlin in which he writes about ASP.NET Master Pages Tips and Tricks. Here is part of it:

With the release of ASP.NET 2.0, developers were given a simple and effective way to apply a consistent layout across multiple pages in a website. By creating a file with a .master extension that defined a website’s overall layout template and referencing it with the Page directive’s MasterPageFile attribute, website development and maintenance took a step forward in the direction of greater productivity.

Master pages have been around for over one and a half years, so I won’t cover the fundamentals of creating and using them, as many tutorials and books have already been written about the topic. Instead, I’ll focus on a few tips and tricks that can be applied when using master pages. To start, let’s examine how the MasterType directive can be used to reference master page controls in a strongly-typed manner from a content page.

Using the MasterType Directive

Pages that reference controls in a master page, such as a Label in the header, or Menu on the left or right of a website template, typically do so by using the Page class’s Master property along with the FindControl() method, as shown in Figure 1.

Label lbl = this.Master.Page.FindControl("lblHeader") as Label;if (lbl != null){lbl.Text = "Welcome from the content page!";}

Figure 1: controls in a master page can be accessed by using the Master property combined with the FindControl() method.

While this approach certainly works, any misspellings in the quotes will not be caught by the compiler, resulting in a runtime error or a null object reference being returned. Fortunately, a strongly-typed solution is available that doesn’t involve casting the Master property to the base class of the master page in order to access its members (keep in mind that any server controls defined in the master page won’t be accessible even after a cast is performed, because they’re marked as protected by default).

read original

New Weekly Series: Silverlight Video Tutorials

On this page you will find dozens of videos designed for all Silverlight designers and developers, from the novice to the professional.

Video Categories

MIX 2007 Silverlight Sessions

“How Do I?” with Silverlight 1.0

“How Do I?” with Silverlight 1.1

Using Blend with Silverlight 1.0

Safari 3 Public beta Available for Windows

Safari for windows have just been announced today during the Apple WWDC conference. The new Beta is available for download free for Mac, WinXP and Vista, and will make the competition between browsers very aggressive after that IE stopped its development for mac platform. Some interesting performance numbers have been announced on the new Safari home page, according to it :

  • HTML performance: Safari3 2.14 Seconds, FF2 3.67s, IE7 4.63s and Opera9 6.22s
  • JavaScript performance : Safari3 0.88 Seconds, Opera9 0.98s, FF2 1.72s and IE7 2.48s
  • Application launch : Safari3 1.74 Seconds, Opera9 1.82, FF2 2.22s and IE7 2.34s

safari performance thumb Safari 3 Public beta Available for Windows

The tests have been made on a 2.16GHz Intel Core 2 Duo-based iMac system running Windows XP Professional SP2, configured with 1GB of RAM and an ATI Radeon X1600 with 128MB of VRAM. The greatest news for today, it’s just not working correctly on my winxp !

Update: Safari for windows seems to be good only as iPhone validator (for buzz words lovers). Applications running correctly on Safari will work fine on iPhone also according to Steve Jobs. Otherwise better call this a pre-alpha.

read original

New ASP.NET AJAX Control Toolkit Release

Scott is writting about the new ASP.NET Ajax Control Toolkit. Here is his post:

Yesterday the ASP.NET AJAX Control Toolkit team released an updated version. You can download it from the http://ajax.asp.net web-site, and run samples built with it on the online samples page here.

The ASP.NET AJAX Control Toolkit is a free download and contains more than 40 additional AJAX controls and components that work on top of the core ASP.NET AJAX 1.0 release. In addition to having Microsoft developers contribute, the project also has more than 15 non-Microsoft contributors adding great features and controls.

You can download either a binary version of the ASP.NET AJAX Control Toolkit to use (just add to your toolbox and you are good to go), or you can download the source for the project itself and tweak/extend it if you want (all source is released under a permissive license allowing you to make your own modifications to it).

New ToolkitScriptCombiner Support

One of the biggest improvements with this toolkit release is support for a new “ToolkitScriptCombiner” control. This control allows you to replace the default control behavior, and supports the ability to dynamically merge multiple client-side Javascript scripts into a single file that is downloaded to the client at runtime. Better yet, only the Javascript needed by the specific controls on the page are included within the combined download, to make it as small as possible.

The big benefit with this feature is that is can significantly reduce the number of Javascript files the browser needs to download, as well as reduce the overall download size of the scripts. This can provide some really nice performance and load-time wins on pages. Best of all – you don’t need to change any code or refactor any script yourself to take advantage of this.

Other ASP.NET AJAX Control Toolkit Improvements

This week’s release contains a number of other new improvements, including:

  • More than 125 bug fixes
  • Extended client side event support – new client side event handler extensibility points are available with common toolkit server controls
  • ASP.NET Validation Controls now work with the Toolkit Controls
  • Accessibility fixes: Slider and AutoComplete have support for high contrast and other controls have JAWS accessibility support built-in when doing AJAX callbacks.
  • Animation support: More toolkit controls now have generic animation support built-in
  • Nice design mode improvements for the controls, including: 1) designer support for the TabContainer. You can now select/add/remove tabs within the tabcontainer directly from the designer, and you can directly edit both the content and the title, 2) page methods can now automatically be generated for those extender controls that call web-services, 3) nice icon support within the toolbox.

You can learn more about all of the improvements in blog posts from Shawn, David, Kirti and Garbin.

ASP.NET AJAX Control Toolkit Videos

Joe Stagner has been cranking away at recording “How Do I?” videos for the AJAX Control Toolkit, and now has 39 free ASP.NET AJAX “How Do I?” videos hosted on the www.asp.net site.

step2 New ASP.NET AJAX Control Toolkit Release

Click here to watch them for free and learn how to-do common tasks with ASP.NET AJAX and the ASP.NET AJAX Control Toolkit. The most recent videos are now available to download in a variety of video and audio formats, including: WMV, Zune, iPod, PSP, MPEG-4, and 3GP.

ASP.NET AJAX Books

As I mentioned in my links post from last week, the first books specifically targeting the final ASP.NET AJAX 1.0 release were recently published. Below are links to two of them that are shipping today:

step4 New ASP.NET AJAX Control Toolkit Release step3 New ASP.NET AJAX Control Toolkit Release

Both books include a chapter on using the controls within the ASP.NET AJAX Control Toolkit.


read original

What is the difference between VB 9, VBx and Silverlight? (Scott Wisniewski)

Today I came across that post at Visual Basic Team blog which is quite good. Enjoy it reading!
I recently received an email from a customer asking for clarification as to what the difference was between VB 9, VBx and Sliverlight. In particular, it seems as if we have been releasing so much information about cool new stuff that at least a few people have become confused, making them a bit nervous about the future of VB.

The customer had also expressed some concerns about upgrading from VS 2005 to Orcas (VS 2008), particularly because he was considering making an upgrade from VB 6 to VS 2005 and wanted to make sure he would be able to take advantage of Orcas when it was released.

I figured there may be other customers that have similar concerns, and so thought this would make a good blog post, particularly because it’s been a while since I’ve posted anything (J).

As a result I’ve included a few of the questions he asked (paraphrased) below, along with my answers.

I hope this helps.

What is the difference between VB 9 and VBx? Which one is the next version of Visual Studio?

Visual Basic 9 is the next version of Visual Basic. Visual Basic 10, or VBx as it’s sometimes called, is the version of Visual Basic that will follow VB 9. Currently VBx is in very early stages, and is a long way off from production. In fact, most of our development team is actively working on VB 9.

Why on earth would you start talking about VB 10 before you’ve even released VB 9? This is confusing.

The product cycle for VB 9 is starting to wind down. We recently released Beta 1 of Visual Studio Code Name “Orcas”, and are currently working on releasing Beta 2. As the product cycle starts to wind down, our language design team is starting to think about what the “next next” version of the product will look like. They do this mainly as a way to “keep the pipeline moving”. If they had to wait until VB 9 was 100% complete before they started thinking about VB 10, then there would end up being a significant delay from when we finished VB 9 until we could start working on VB 10. This is because designing a product, and coming up with a plan to develop it can be extremely time consuming. It requires us to come up with a design, create a schedule, make any necessary organizational changes, and ensure we have the right staffing levels, all before we start coding. By “overlapping” the early design work for VB 10 with the “end game” work for VB 9 we are able to better “bootstrap” the whole process, thus making the transition from one project to the next as smooth as possible.

As our design team comes up with designs they like to release information about them as early as possible. The earlier we can get information out to our customers, the earlier we can get feedback about the things we are doing. This helps us to build the products that actually meet our customers’ needs. One thing we’ve managed to learn over the years is that the best possible way we can learn what it is that our customers want is to engage with them early and often.

As a result, near the end of a product cycle we will release information about our plans for the version of the product to follow the one we are currently working on. This gives our customers the chance to comment on it and let us know what they think. We then take that feedback and use it to develop a more complete plan for what we want to do.

What is VB 10 going to be like? What is this Silverlight Thing I keep hearing about? Is Silverlight a replacement for Visual Studio?

Our plans for VBx and Silverlight are still very rough and are nowhere near complete. As our customers start to use VB 9 and provide us with feedback that data will drive exactly what we end up doing in VB 10. That being said, however, we do have some rough ideas of the things we would like to do.

Silverlight 1.1 is a new light weight version of the .NET Framework that will allow you to develop rich applications that run in a web browser using .NET languages. The basic idea is to allow you to replace client side java script with .NET enabled languages, allowing you to write both the client side and sever side portions of your web applications in the same language. It also allows you to use WPF (windows presentation foundation) and WCF (windows communication foundation) to create extremely rich and interactive web applications in a way that is much easier than what is possible using HTML, Ajax, Java Script, or Flash.

VB 10 is going to be the version of Visual Basic that will follow VB 9 (the “next next version”). It will include new features designed to make VB a really great language for developing SilverLight apps, as well as enhancements to many of the new feature we are delivering in VB 9, such as Linq. You should still be able to do all the things with VB 10 that you could do with both VB 9 and VB 8.

The migration from VB 6 to VS 2005 is non-trivial. If I upgrade to VS 2005 will I able to use VB 9 when it comes out, or will I have to scrap all my work? What about VB 10? Should I be worried about the future of VB?

The transition from VB 8.0 to VB 9.0 should be smooth and relatively painless. We have gone to great lengths to ensure this.

Our plan is to also make the migration from VB 9 to VB 10 equally painless.

Although the migration from VB 6 to VB.NET is a bit tough, we are actively working on making that easier as well. We have been releasing a “VB Interoperability Toolkit” that allows an application to be gradually migrated from VB 6 to VS 2005, rather than requiring the whole thing to be migrated at once.

You can get more information about it here:

http://msdn2.microsoft.com/en-us/vbasic/aa701257.aspx

As far as the future of VB, you should definitely not be worried.

Microsoft is committed to VB, and making it a great language for developing applications for our various platforms. The future of VB should be a bright one!
read original

Introducing LINQ – Part 5

Introduction

Whenever someone asks me about the DataContext I always refer to it as the “brains” of Linq to SQL, why? Because it is. It is responsible for the translation of Linq to T-SQL, and the mapping of the results (rows) of that query to objects, and so much more.

If you run any codegen tool (SqlMetal, or Linq to SQL file (VS Orcas designer)) you always get a class that derives from the DataContext class. The DataContext can be equated to a database, in that it contains a series of tables (normally this is implemented as a property that returns a Table), and sprocs (methods calls that invoke underlying sprocs at the DB layer).

Note: The DataContext can also handle other SQL Server features like views, and table functions etc.

What’s so special about the DataContext class?

Most notably the DataContext takes some Linq code and generates the appropriate T-SQL statement for that query; if that query returns rows then the DataContext object will take care of mapping those rows to objects.

Figure 5-1: DataContext core functionality

DataContextCorefunctionality Introducing LINQ – Part 5

I want to see the T-SQL generated by my LINQ

If you are a control freak/perfectionist like me then you probably want to know exactly what T-SQL is being generated for you at all times.

Before I show you some code please remember that the T-SQL generation by the DataContext object is not perfect, if you know of a very efficient T-SQL solution then implement that in a sproc. Saying that I have found the T-SQL generation of the DataContext object to be efficient in some advanced queries. Like so many things in programming one way, and one way alone is often not the best approach – experiment to see what offers the best performance for your query.

There are a few ways in which we can monitor the T-SQL being generated by our DataContext object, these include:

  • Visual Studio Orcas
  • ToString() override of query
  • DataContext Log property
  • SQL Server 2005 profiler (not included with Express edition)
Note: As the majority of people reading this article will be using the Express editions of the developer tools I will skip the SQL Server 2005 profiler demo. Those who have used the profiler before will know that it is a real time T-SQL dump of everything that a particular SQL Server 2005 instance is doing so seeing what T-SQL the DataContext is generating is a trivial task.

Visual Studio Orcas

As Linq is a 1st class citizen within the C# and VB.NET languages it should be no surprise to you whatsoever to see rich debugging support within the IDE.

Figure 5-2: Seeing the T-SQL generated by the DataContext object in VS Orcas

DataContextObjectInVSOrcas Introducing LINQ – Part 5

ToString() override

This is a really nice feature – if you call the ToString() method on any variable whose value is a query you can see the associated T-SQL for that query.

Figure 5-3: Calling ToString()

  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4. namespace ConsoleApplication4
  5. {
  6. public class Program
  7. {
  8. public static void Main(string[] args)
  9. {
  10. using (BookShopDataContext db = new BookShopDataContext())
  11. {
  12. IEnumerable query = from b in db.Books select b;
  13. Console.WriteLine(query);
  14. }
  15. }
  16. }
  17. }


Figure 5-4: Result of running the code in Figure 5-3

5 4 Introducing LINQ – Part 5

Concurrency

Concurrency is always an issue – Linq to SQL by default uses optimistic concurrency. Take an example of where we retrieve a particular piece of data and then update that data, we then try to submit the updated data to the server but we get an exception as Linq to SQL knows that we have violated a concurrency check as we were acting upon “old” data.

Just to show this I did a pretty simple operation by adding a breakpoint on the line where I call the SubmitChanges(...) method and then executed some T-SQL code to alter that record and then continued the execution of my application so I would get an exception.

Figure 5-6: ChangeConflictException

ChangeConflictException Introducing LINQ – Part 5

The SubmitChanges(...) method is overrided to take a ConflictMode enum where we can change the default behaviour when data is submitted to the database, these are:

  • ContinueOnConflict
  • FailOnFirstConflict

The above can be used when within a TransactionScope. There are a few attribute values we can apply to our generated code to specifically say “we don’t care if this particular bit of data is changed – just overwrite it”. We do this using the UpdateCheck parameter to the Column attribute.

Figure 5-7: We don’t care about this data – just overwrite the value with what we have!

  1. [global::System.Data.Linq.Column(Storage="_Title", Name="Title",
  2. DBType="NVarChar(50) NOT NULL", CanBeNull=false,
  3. UpdateCheck=System.Data.Linq.UpdateCheck.Never)]

The UpdateCheck enum values:

  • Always
  • Never
  • WhenChanged

I’m pretty sure I’ve not covered everything in Linq to SQL with regards to concurrency – remember though that you can use the TransactionScope type in the .NET framework to assist you.

Using VS Orcas to look at data

Remember – queries only execute when we call the GetEnumerator() of the variable that holds the query! In previous CTP’s of VS Orcas it was hard to see what data we pulled back from the database as the debugger didn’t call the GetEnumerator() method when you wanted to look at that particular variable – the March CTP does however which is really great!

Let’s go ahead and look at using VS Orcas to look at data returned from our database using the Locals window when debugging. First place a breakpoint after the line you define a query, you don’t need a foreach to call the GetEnumerator() – the IDE will do that for us. When you get to your breakpoint you will see a screen similar to that in Figure 5-8 where the variable holding our query has a message saying something like “expand me to enumerate this IEnumerable”.

Figure 5-8: Thinking about enumerating the IEnumerable

EnumeratingIEnumerable Introducing LINQ – Part 5

Expand the results! You know you want to.

Figure 5-9: Viewing the results

5 9 Introducing LINQ – Part 5

You can see that in Figure 5-9 I have two objects returned from my query, I can drill down into the values of their properties and so forth.

On the face of it this is a pretty basic enhancement to the IDE, and you would be right in thinking so – but this is a great visual tool which I’m sure you will love when using Linq to SQL!

LINQ to SQL FAQ

Will LINQ to SQL support Oracle?

This is a common question, the answer to which is no. Linq to SQL is a lightweight O/R mapper targeted for use with SQL Server 2000/2005. For a more powerful O/R mapper look at the Entity Data Model (EDM) – EDM will support Oracle and other 3rd party databases.

I hate codegen tools, how much code does it really take to hook up to my DB using LINQ to SQL?

Surprisingly little, essentially you need to create a property with the correct access (get, set, or both?) with the appropriate Column attribute. The class with your properties should be pluralized and use the Table attribute to map it to the corresponding table in the database.

Finally you will need to create a class that derives from DataContext. In this class you will want to expose some properties that return a generic Table.

Below is the code for the TodoListDataContext and Task types:

Task.cs (type that is associated with records in Tasks):

  1. using System;
  2. using System.Data.Linq;
  3. namespace ConsoleApplication5
  4. {
  5. [Table(Name="Tasks")]
  6. public class Task
  7. {
  8. private int _taskId;
  9. [Column(Name = "TaskID", Storage = "_taskId",
  10. IsDBGenerated = true, IsPrimaryKey = true,
  11. CanBeNull = false, DBType = "int not null identity")]
  12. public int TaskID
  13. {
  14. get { return _taskId; }
  15. }
  16. [Column(Name = "Title", CanBeNull = false,
  17. DBType = "nvarchar(50) not null")]
  18. public string Title
  19. {
  20. get;
  21. set;
  22. }
  23. [Column(Name = "Complete", CanBeNull = false)]
  24. public bool Complete
  25. {
  26. get;
  27. set;
  28. }
  29. }
  30. }


TodoListDataContext.cs (type that exposes a Table of type Task, and defines connection string)

  1. using System;
  2. using System.Data.Linq;
  3. namespace ConsoleApplication5
  4. {
  5. public class TodoListDataContext : DataContext
  6. {
  7. public TodoListDataContext(string conn) : base(conn)
  8. {
  9. }
  10. public Table Tasks
  11. {
  12. get { return GetTable(); }
  13. }
  14. }
  15. }


Why are the changes to my data in SQL Server not being persisted?

Remember, in order to persist changes to SQL Server you need to call the SubmitChanges(...) method on your DataContext object after you have made changes to any data.

Can I use XML to define the O/R mapping?

Yes. You can use SqlMetal to generate an XML mapping file, when creating a DataContext you need to specify that your mapping is defined in an XML file by using the XmlMappingSource type.

I’m hitting the database every time for two identical queries, can I prevent this?

To prevent hitting the database every time you can load the results into memory (e.g. Append ToList() to a query) any subsequent calls to that query will use the in-memory collection rather than going off and querying the database again.

Is it possible to create code from XML?

Yes. You can create a .dbml file using SqlMetal and then generate a codefile (either VB.NET or CS) based on the XML defined in the .dbml.

What’s this deferred loading stuff?

Linq to SQL uses deferred loading when accessing properties of a related entity. Given a simple select query returning all Books, if I then want the publisher for each book then I can do so, however, behind the scenes the DataContext is doing a select where query to get the publisher for the current book. This is deferred loading.

Note: You can disable deferred loading using the EnableDeferredLoading property of a DataContext object.

Summary

There is a ton of stuff that’s special about the DataContext that I haven’t covered – I encourage everyone to go check out the DataContext class and experiment. I hope that I have provided you with the knowledge to get started with Linq, and Linq to SQL – if you have any questions about a particular feature of Linq to SQL I have/haven’t covered then please feel free to email me via the address on http://gbarnett.org/about.

read original

Silverlight Tutorials

I got that one from Michael Schwarz’s blog. He put it all together at one place. Below its the list:

There are a couple of great tutorials on how to developer Microsoft Silverlight 1.0 or 1.1 Web applications:

Mix 07 Silverlight Sessions

Silverlight 1.0 Tutorials

Silverlight 1.1 Tutorials

Expression Blend with Silverlight 1.0

Silverlight QuickStarts

MSDN Library

Tutorials from other Web sites

read original

The JavaScript Dilemma

The last post from Rick Strahl’s blog! Its a great piece of reading. Check it out also here(at the bottom I have a link to his original post):

rick The JavaScript Dilemma

In the last year or so the Ajax lifestyle has become common practice for Web development even in the developer mainstream after a few years where the technology was primarily treated as bleeding edge technology. Today however, Ajax is drifting more and more into the mainstream of Web development and you’d be hard-pressed to find a Web development tool that doesn’t support it in some highly abstracted way.

Ajax is all about JavaScript and HTML DOM scripting and I thought in this column I’ll review some of the approaches that are available to satisfy the requirements to build richer client applications and offer some thoughts on issues that I am struggling with as I compare the choices available for my own development and solutions that I work on with customers.

It’s pretty clear that the days of hand coding most of the JavaScript to deal with client side logic are over. These days the complexity of what’s happening on the client and the UI is quickly getting as complex if not more so than what’s happening on the server. And while in the past we might have written a couple of lines of JavaScript here or there to validate forms, these days the requirements are much more involved. It’s almost a foregone conclusion that the client side now also requires some sort of framework which is often completely decoupled from the server side.

JavaScript Frameworks

At the moment client side frameworks are all the rage. There are basic JavaScript libraries that help with common tasks automating the DOM. The most popular along these lines is Prototype which provides basic JavaScript language enhancements as well as basic browser independent DOM manipulation functionality. Many other libraries build ontop of Prototype to build additional libraries the most common of which these days are user interface widget libraries. Dojo and Yahoo’s Widgets are examples of Widget frameworks. Similar are effects libraries like Scriptalicious, Moo.fx

ASP.NET Ajax

The first stop for most ASP.NET developers likely is the MS Ajax toolset along with its various support libraries. MS Ajax provides both a server centric and client centric toolset. The server side functionality is primarily driven through the UpdatePanel control that allows wrapping server side controls and containers into an updateable panel container that allows for partial page updates. This component is the basis of MS Ajax’s server functionality and provides a core set of features that can be taken advantage of by other controls. The MS Ajax Control Toolkit can also be used in combination with the MS Ajax library to provide many other controls that provide server centric implementations with client side. The Control Toolkit takes uses a common pattern to create client side control implementation and also expose the control or behavior via a server side control which allows getting the base behavior exposed in a way familiar to ASP.NET developers with a minimum or no client side scripting.

MS Ajax also includes a large client side JavaScript framework that provides core language features and basic HTML DOM accessibility through a common JavaScript API. The key feature of the client side framework is that it provides a .NET like type system and a common implementation pattern for classes and components. So you will typically use a set of guidelines based on namespace, interfaces and classes to implement your classes. You’ll use property get/set syntax for property declaration and invocation when creating your own classes and the framework more or less forces you into a specific way of doing things which is both a good thing and a bad thing depending on whether you agree with the design decisions Microsoft made. But the rigid structure of the framework also means that using it requires a certain discipline and in some ways is much more verbose than other JavaScript frameworks.

The client side framework in version 1.0 can be thought of as core framework services rather than as a complete Ajax framework. This includes the type and language facilities, extensions to some of the base JavaScript objects and the base Html DOM element. Of course there’s also support for remote communication via XmlHttp both on a low and high level as well as JSON serialization facilities and the ability to use ASMX and WCF Web Services.

To me MS Ajax is completely mixed bag. On the one hand I think Microsoft did a great job of providing a deep framework that is modeled closely to the .NET framework’s design which makes it somewhat familiar to .NET developers. But on the other hand the framework is bulky and it feels very rigid and formal in its implementation and usage.

But there’s no doubt that there is some allure in MS Ajax because it provides a single framework for client and server. The above mentioned rigidity of the framework can also be advantageous to control developers as it clearly forces common patterns for implementing components that work and expose functionality consistently. There are also many advanced features baked into the client framework like localization, testing and instrumentation at every level and not just at an afterthought.

Pure JavaScript Frameworks

Microsoft started from scratch when they built MS Ajax but there are a number of very popular JavaScript libraries available most of which are easier to use and more light weight to boot.

If you are a developer who’s familiar with JavaScript and not afraid to code on the client side, a raw JavaScript library might offer you much more flexibility and options to create cool interfaces because there are a large number of libraries available. The most difficult portion of a JavaScript/Ajax framework is the browser interoperability and functionality extension of the base JavaScript objects and basic DOM objects and all of the libraries I mention here address this scenario. These libraries do away with the inconsistency of dealing with various browsers which is easily the biggest time waster when dealing with client side scripting. Take that away and you might find that JavaScript coding is not a big deal after all.

The most popular among the JavaScript frameworks is Prototype which is a highly usable and relatively small library that provides JavaScript type extensions and a large number of DOM abstraction and enhancement functions. Prototype is small and concise and is easy to pick up by anyone reasonably familiar with JavaScript which accounts for its popularity. It’s definitely going to be less familiar to ASP.NET developers as it’s clearly a JavaScript centric framework. Prototype has pretty much become the yardstick by which other libraries are compared. Prototype is also the basis of many other higher level frameworks and many smaller add-on libraries exist that provide specialty functionality on top of Prototype.

There are other frameworks that follow a similar base approach. A couple of others that I’ve used on several occasions are jQuery which is very light weight and provides mostly AJAX/ JSON functionality, plus basic browser abstraction. MooTools is a full featured library that focuses heavily on effects (like drag and drop, animation etc) . I’ve found MooTools to be very enjoyable to work with and it feels like the cleanest and easiest to use implementation of the JavaScript frameworks I’ve played with. It also uses a very Prototype like base implementation although it doesn’t rely on Prototype itself so it will be immediately familiar to users of Prototype. Mootools also has a cool feature on their site that lets you customize the MooTools JavaScript library by feature so you get only the features you want include in your set (or sets).

Other libraries yet aim to extend the popular Prototype library. script.aculo.us for example, provides an effects library that runs on top of Prototype as does Moo.Fx, which is a tiny effects library that can work with Prototype or as part of MooTools.

All of the the libraries I’ve described so far (including the MS Ajax client library) are really core framework libraries. They provide language, object and DOM extensions, but they don’t provide much in the way of new user interface functionality. There are a number of libraries available that address this space with Widget frameworks. A couple of prominent entries in this space are Dojo, the Yahoo UI Library and even OpenLazlo (works either with Flash or DHTML) which provide a host of client controls. These frameworks are big and are often complex to use, but they provide really rich client side functionality that allows building interfaces that mimic desktop applications to some degree.

The good news with any of these tools is that they will work without any sort of server implementation so they’re easy to drop into any application – simply reference the JS libraries and off you go.

Unlike MS Ajax these libraries are purely client side – they know nothing about ASP.NET and the server side. But that’s part of the benefit of these frameworks as they are completely server agnostic. Communication between client and server is provided using XmlHttp and JSON serialization, deserialization, but if you plan on using it in combination with ASP.NET you probably will want to at least implement a custom JSON service interface that you can use to pass typed data between client and server. There are several open source .NET JSON libraries available (JSON.net, here and also my own wwHoverPanel) that make short work of this task. wwHoverPanel for example implements a self-contained HttpHandler implementation that lets you call JSON methods and return results from them.

Other ASP.NET based libraries like Anthem.NET, Ajax.NET and several others also provide server side JSON functionality. These libraries are also options for ASP.NET developers, but they tend to be server centric, and my focus here is on client side scripting so I won’t go into more detail here.

Build your Own

When I started out with Ajax about 3 years ago, roughly about the same time Microsoft announced MS Ajax (Atlas at the time), I also got excited about Ajax functionality and thought that it wouldn’t be too difficult my own library with some basic functionality. Before long the library grew into a small client framework with a very focused feature set that did exactly what I needed in my applications and life was good. However, I also quickly found out that building your own is not as trivial as it sounds at first once you go down the path of building more sophisticated functionality. My library ended up adding things like drag and drop functionality, modal dialogs, pop up windows and various basic effects. At the time my JavaScript skills were pretty creaky and it took a bit of time and refactoring of the JavaScript code to get up to speed and actually understand more about JavaScript’s language peculiarities and browser DOM quirks. This is an ongoing effort that continues to this day.

Today as I’m looking back I’m really glad I went through this experience as it taught me tons about JavaScript that I probably would have never figured out and now I feel at least reasonably proficient with JavaScript not to cringe at the thought of having to write client script. But I also realized that writing sophisticated client side JavaScript DOM code is damn hard especially if it has to work across many browsers and I really started to appreciate the efforts that have gone into libraries like Prototype or MS Ajax’s client library.

I still see a lot of value in building a custom library, however. If I had to do it over (and I may) I would almost certainly use one of the more prominent base frameworks as my base library and build on top of it. Using Prototype or MooTools would cut my framework code in half and let me focus on the specialty features I want in my framework.

The design I chose ended up creating matching client and server controls for most components built in such a way that the client control interfaces largely matched the server controls. The key features were to provide easy and flexible remote callback functionality to the server, a small windowing library that makes it easy to present pop up window content, along with a host of basic client side behaviors all in a small package. And finally combining all of this into an easy to use ASP.NET based interface.

Building your own is probably an edge case, but I’m often surprised how many people like me have gone down this path mostly because in the early days there weren’t as many choices available as there are today. The advantage with this approach is that you can build a truly customized framework that matches your toolset. It can also be beneficial to do this as a tool developer so you can provide additional functionality that is self contained. For example, even today with MS Ajax you can’t easily have client side code call back into a control without major hassles but with a custom interface it’s as easy as adding a method to a control and calling it from the client side. These are the kind of things you may never see in an official framework but are indispensible when you’re dealing control development for example.

Script#

So far I’ve looked at client side JavaScript coding which is often regarded as a hassle. But there are a also a few alternatives available that let you code in a different language and output JavaScript from it. One such tool is the Google Web Toolkit which lets you write Java code to generate JavaScript code. Being a .NET developer using Java doesn’t sound so enticing, but luckily there’s a .NET project available that provides similar functionality by using C#.

Nikhil Kothari is one of the Program Managers on the ASP.NET team and he keeps cranking out some highly valuable and useful tools. One of the most exciting tools he’s created some time ago and recently updated is Script#. Script# at its core is a C# compiler that rather than spitting out MSIL compiled assembly spits out JavaScript source files. There are two pieces to this magic – the actual compiler/parser that does the translation and a set of libraries that provide the supported set of features that you can use with the C# code you write. The thing to understand is that you don’t get access to the full CLR and .NET libraries, but rather to a specific subset that is available to Script# and capable of being mapped into JavaScript code.

The benefits of this approach are that you get full support for a rich editing environment in Visual Studio, strong type support and Intellisense for the supported features.

There are a number of ways that you can create Script# generated JavaScript – one is inline inside of pages via a Scriptlet control that can contain C# code that gets converted on the fly and a more traditional library type approach that creates a separate .js files.

One of the cool things that Nikhil has done is provided a mapping assembly that provides a good chunk of the MS Ajax client library so you can generate code for MS Ajax compatible controls and behaviors. But even without the MS Ajax support, Script#’s core JavaScript support libraries provide many of MS Ajax’s type system like namespaces and class registeration etc.

Script# is an interesting concept and Nikhil himself has used it for building a number of controls and helpers he’s published recently which is a validation of this concept for real work in a lot of ways.

Unfortunately this project currently has not been given any official support from Microsoft, so currently it’s impressively maintained by Nikhil himself. The toolset includes pretty good integration into Visual Studio .NET with project and item templates and integrated editor support for most things in the way you’d expect from C# source editing. But some of these integration features are a little rough around the edges which is to be expected for an early release (0.3.0).

I’ve played around with Script# off and on and it provides some really interesting possibilities, but somehow I can’t shake the feeling that this is somehow limiting my options for coding general purpose JavaScript. Script# also subscribes to the MS Ajax way although it can work without MS Ajax. If I were to build MS Ajax controls I think I would start seriously looking into this tool to provide some of the core plumbing. Script# will manage things like automatic property creation (MS Ajax style), class and namespace registration, handling and providing Intellisense for the core MS Ajax infrastructure which provides great discoverability and a great reduction in the amount of plumbing code you have to type to create the tedious MS Ajax client code.

There’s a lot of potential for this sort of tool as a lot of people feel a lot more comfortable in the C# vs. JavaScript. But without official support from Microsoft it’s unlikely that this tool will gain wide acceptance although there are certainly some people who will find it useful for their work.

SilverLight 1.1 and .NET on the Client

Microsoft recently announced SilverLight 1.1 and one of the features of the 1.1 version when it releases later this year or early next year will be the capability to run .NET code on the client. I don’t want to dwell on the rich user interface features of Silverlight here since this has been beaten to death recently, but rather focus on the .NET programmability and the ability of the .NET code to reach out and manipulate the HTML DOM from within the Silverlight .NET runtime. This gives yet another option for managing client side code using a .NET language rather than JavaScript. This means that you can use Silverlight in combination with .NET to write fully standard compliant HTML.

The way this works is that the .NET runtime hosted in Silverlight provides a programmable reference to the HTML DOM that Silverlight is hosted in. This may be IE or FireFox or Safari on the Mac or Windows. Silverlight provides interface to the the browser’s DOM and allows automation of it.

In concept this is a great idea, but before you get too excited remember that the current DOM support is very limited and deals primarily with accessing HtmlElement at the raw DOM level. There’s no browser abstraction or any support for specific HTML constructs. However, it’s quite possible to extend this basic functionality using .NET code to provide a much richer abstraction and browser independent access to the DOM. This would require somebody to build a browser abstraction layer first, but once done imagine the benefits that this would bring: You could build a browser abstraction layer that’s driven through the .NET coding model providing all the benefits of compilation and discovery and of course Intellisense.

We’re not there yet, but the possibilities of this technology have tremendous promise not just to address the flashy scenario we’ve seen so much of with Silverlight but also using Silverlight as a behind-the-scenes scripting engine for the HTML document.

Too many Choices?

As you’ve seen there are quite a few options available these days to build client side code. It’s no longer just about the remote AJAX functionality but also about building rich and snazzy client side interfaces.

There are many ways to skin this cat. The Ajax framework market is hugely fragmented and this is a problem especially since many of the Ajax frameworks and tools are so drastically different that moving between them is nearly impossible.

Even if you look only at the ASP.NET space, you’ll find that the MS Ajax release late last year has not found the universal adoption that’s typical for anything major coming out of Microsoft. While MS Ajax almost certainly has quickly become the most prominent ASP.NET Ajax framework by default, many early adopters of Ajax technologies are finding that MS Ajax is not a must-switch solution and continue on with their existing tools. That may change as time goes on and MS Ajax matures and adds more useful functionality that makes it more compelling as a client side tool.

Where does that leave us? I feel right now just about all of the Ajax tools out there are immature and often buggy. That doesn’t mean they don’t work, but they are not necessarily easy to use or maintain. The best that we can do as developers is to try and pick a toolset and stick to it if possible. But even that is often difficult if you work with multiple clients that have different preferences for the toolset used. Over the last year I’ve worked with at least 5 different Ajax frameworks on various projects and switching between these frameworks and building interfaces that run on top of them is not optimal to say the least. But it’s become a fact of life.

For my own internal work I’ve also landed myself in a dilemma. Do I stick with my custom built solution, or do I bite the bullet and make the switch to MS Ajax just because in the ASP.NET space at least it’s as close as it gets to a standard implementation? Even though I’m less than thrilled with that toolset? Or do I stick with what I got, possibly refactor and use a base library like Prototype? That’ll be most likely the path I take, but for now I’m sticking with the original framework I built. There are a lot of choices to make, benefits and tradeoffs to weigh.

Ajax and client side development is here to stay, but we are bound to see some consolidation and stabilization over the next few years. These are turbulent times.

Welcome to Web Development in 2007.

read original

Silverlight Examples

Michael Schwarz had collected this list of usefull Silverlight examples. Here is his post:
logo Silverlight Examples

During the weekend I spent some minutes to collect some of the greatest Silverlight examples. Most of them need the Silverlight 1.1 alpha runtime which is available for download here.

If you are missing any great demo or article please use the comments or contact page to add it.

  1. 3D in Silverlight 1.1 Alpha
  2. RadControls for Silverlight by Telerik
  3. Silverlight 1.1 2D Physics with Source Code
  4. Lutz’s Digger, Monotone and Inplay; see also .NET Reflector Plugin for Silverlight
  5. DLR Console
  6. Silverlight Chess (JavaScript vs. C#)
  7. SWF2XAML: A Slightly better Flash to XAML Conversion
  8. Scott Guthrie’s blog posts tagged with Silverlight
  9. Silverlight Toolbar
  10. Use File Open Dialog with Silverlight
  11. Microsoft PopFly
  12. Microsoft Silverlight 1.1 Alpha Developer Reference Poster
  13. How-to videos
  14. Silverlight Surface Demo
  15. Silverlight XPS Viewer
  16. Miguel de Icaza about Silverlight, DLR and OpenSource
  17. Eyeblaster Rich Media Silverlight AD
  18. SilverNibbles – Converting a Windows Forms Game to Silverlight
  19. Silverlight Controls and LINQ
  20. Silverlight Games 101 (Silverlight Rocks!)
  21. DLR & IconPython at Codeplex
  22. Silverlight Pad
  23. Video support with Silverlight Fox Example
  24. AOL Social Mail Gadget

Blogs about Silverlight (unsorted order)

  1. Scott Guthrie
  2. Jim Hugunin
  3. Mike Harsh
  4. Brad Abrams
  5. SqlXml Blogs tagged with Silverlight
  6. Tim Sneath
  7. Lutz Roeder
  8. Web.Next
  9. Shawn Wildermuth
  10. theWPFblog
  11. Delay
  12. IronPython
  13. Barak’s Blog about Silverlight and beyond
  14. Windows Vista blog tagged with Silverlight
  15. My own blog icon wink Silverlight Examples
  16. MVPs posts
  17. Jesse Ezell Blog
  18. Decintelligence
  19. BCL Team Blog
  20. John Lam
  21. Andrew’s Silverlight Blog
  22. Danny Thorpe
  23. Adventures with WPF

read original

Silverlight and JSON

Another artcile by Michael Schwarz, check it out here:

Silverlight 1.1 comes with an built-in JSON serializer which can serialize common data types like string, numbers and arrays. It includes a object serializer, too, I think it is nearly the same as in ASP.NET AJAX or Ajax.NET Professional.

I modified my IsolatedStorage demo and added a new method called GetFiles(string pattern) which will return an array of string containing the file names in the storage. Because I already did the managed JavaScript (DLR) demo in on of my earlier posts I’m now using C# (I love Silverlight, I can choose my favorite language all the time).

namespace IsolatedStorage{   [Scriptable]   public class Storage   {       [Scriptable]       public string GetFiles(string pattern)       {           using (IsolatedStorageFile isf =                  IsolatedStorageFile.GetUserStoreForApplication())           {               JavaScriptSerializer jss = new JavaScriptSerializer();               return jss.Serialize(isf.GetFileNames("*.*"));           }       }

       [Scriptable]       public bool WriteText(string filename, string s)       {           try           {               using (IsolatedStorageFile isf =                      IsolatedStorageFile.GetUserStoreForApplication())               {                   using (IsolatedStorageFileStream fsm =                          new IsolatedStorageFileStream(filename,                                           FileMode.OpenOrCreate, isf))                   {                       using (StreamWriter sw = new StreamWriter(fsm))                       {                           sw.Write(s);                       }                   }               }           }           catch (Exception)           {               return false;           }

           return true;       }

       [Scriptable]       public string ReadText(string filename)       {           try           {               using (IsolatedStorageFile isf =                      IsolatedStorageFile.GetUserStoreForApplication())               {                   using (IsolatedStorageFileStream fsm = new                          IsolatedStorageFileStream(filename,                                       FileMode.Open, isf))                   {                       using (StreamReader sr = new StreamReader(fsm))                       {                           return sr.ReadToEnd();                       }                   }               }           }           catch (Exception)           {               return null;           }       }   }}

Because Silverlight (or the Scriptable methods) don’t support more complex data types until now (I hope this will change in future releases) we have to return a JSON string that will be parsed on the client-side JavaScript later.

The JavaScriptSerializer is included in the namespace System.Windows.Browser.Serialization. You have to create a new instance of the JavaScriptSerializer class and call the Serialize method which you pass the .NET object you want to serialize. In our example it is a string array we get as result of the IsolatedStorageFile.GetFiles method.

On the client-side JavaScript code I use the eval statement, hm, is not the best way to parse JSON, but the easiest. Of course you can use the ASP.NET AJAX parser or the JavaScript parser at json.org:

var control = document.getElementById("SilverlightControl");var storage = control.Content.Storage;

// save any data to the storagealert(storage.WriteText("test2.txt", "Hello World!"));

// read data from the storagealert(storage.ReadText("test2.txt"));

// get all filenames in storagevar files;eval("files = " + storage.GetFiles("*.*")); // eval parse JSONalert("Files: " + files.join(","));

You can download this example here. For those of you don’t have Visual Studio Orcas installed I have included the binary files, too. So, simple double click on the TestPage.html. If you run the example you will see three message boxes: the first will display true if writing was sucessful, the second one will display the content of the file specified in the argument. The last message box will display all filenames in the storage.

read original