Monthly Archives: May 2007 - Page 2

Silverlight Basics

Nice article which I found on dotnetslackers.com explaining the basics of Silverlight and its usage. Check it out here:

Silverlight is Microsoft’s new Flash Killer but it will be so much more! Learn all about the present and future features of Microsoft’s new web front end.

What is Silverlight?

Silverlight is a browser plug-in that that extends the web development experience far beyond the limitations of plain HTML and JavaScript. Being a Microsoft product, you might expect it to work best (or only) on Windows and Internet Explorer. So you may be pleasantly surprised to know that it works equally well on Windows and on the Mac, and it also works equally well on the Firefox and Safari web browsers. Since Silverlight is a client side technology, it doesn’t matter what backend server software or platform you’re running – even Apache/Linux will do just fine.

Version 1.0

Silverlight version 1.0 – scheduled for release this summer – is very comparable to Adobe Flash. It delivers high performance multimedia and animation capabilities that can blend seamlessly with HTML. It’s capable of playing a variety of audio and video file formats, such as MP3, WMA, and WMV. It handles streaming quite well, so media can start playing immediately without having to wait for the entire file to download.

Silverlight’s user interface is defined with a subset of XAML – an XML format shared with Windows Presentation Foundation (WPF). This facilitates vector based animations, a claim that goes beyond Flash’s current capabilities. Silverlight’s compiled object model can be navigated via JavaScript for seamless interaction between embedded Silverlight components and the page that hosts them.

When users encounter a Silverlight 1.0 enhanced web page for the first time, they’ll be prompted with the quick & easy installation that’s only about a 1.2 megabyte download.

You can download the beta version of Silverlight 1.0 now.

Version 1.1

While the multimedia and animation capabilities of Silverlight 1.0 are certainly great for graphic designers, Silverlight version 1.1 (currently in alpha) starts to provide the kind of business oriented functionality that the majority of web developers need.

Probably the most exciting feature of version 1.1 is the built-in cross platform subset of the .NET Framework. While you can still mix in as much (or as little) JavaScript as you’d like, you’ll now have the option of running your own fully compiled .NET code within IE, Firefox, or Safari. Those developers who hate JavaScript should be thrilled to know they can now write their client side code in C#, VB.NET, or any other .NET language. This .NET code can interact with the browser’s object model so it can manipulate the page’s HTML in addition to interacting with any Silverlight user interface that may be embedded in the page. You’ll now be able to replace slow performing JavaScript code with fully compiled .NET code that could easily execute hundreds of times faster.

A variety of useful classes are included in Silverlight 1.1 for working with cutting edge technologies like LINQ, generics, multithreading, and invocation of Windows Communication Foundation (WCF) web services. There’s also support for XML manipulation, networking, I/O, collections, globalization, and JSON serialization.

ASP.NET support is also provided for things like personalization, profiles, role membership, and invocation of ASMX web services. On a related note, the next release of ASP.NET is expected to include a variety of tools for easing Silverlight development, including built-in controls that make it easy to embed Silverlight content.

Unfortunately there are currently no definite plans to include any significant number of controls in Silverlight 1.1 – not even a basic button control is currently in the mix. They do at least provide a control class that can be used to build your own controls, and alternately it’s not terribly difficult to make basic controls using XAML and some custom code – but certainly we’d prefer not to have to write such basic code. Luckily there are several controls available in the separate Silverlight 1.1 Alpha SDK download.

Since Silverlight 1.1 is still only in alpha, its uncertain exactly what other functionality may ultimately make it into the release version. The current download size for this far more functional version of Silverlight hovers at around 4MB.

Future Versions

From my conversations with Silverlight mastermind Scott Guthrie and his merry band of genius underlings, they’ve got a lot of mouthwatering functionality planned for upcoming versions of Silverlight. General themes include a rich set of built-in controls, data binding support, XLINQ, RSS, Xml Serialization, Opera support, and improved layout management. And that’s just for starters.

In general the vision is to transform Silverlight from its current 1.0 state of multimedia powerhouse into a highly productive business tool capable of powering rich applications of virtually every kind.

Even with all this extra functionality, Silverlight’s team has a long term secret goal of keeping the download size under 5MB. Shhhh! Don’t tell anybody!

Development Tools

Currently the lack of polished tools for developing Silverlight applications is its biggest hindrance. The next version of Visual Studio (codenamed Orcas) is expected to ship with rich Silverlight support. However, the current beta version of Orcas clearly still needs a lot of work before achieving this goal. If you’re brave enough to be tinkering with the Orcas beta then you might as well download the Silverlight Tools Alpha add-on to try out its Silverlight development capabilities.

Microsoft’s new Expression suite of products is currently closer to being in a finished state. They are presently more polished and less buggy than Orcas. Specifically, Expression Blend is probably the most valuable Expression product for Silverlight development. However, be forewarned that the Expression suite is intended more for graphic designers than software developers. Therefore Visual Studio-oriented developers should expect a significant learning curve.

Summary

Silverlight is a brilliant idea that still has a ways to go before it reaches its potential. Nevertheless, it should definitely be on every web developer’s radar. It’s a distinct possibility that Silverlight could be the future of web development. Imagine a world where web developers no longer deal with HTML, and instead write rich, compiled .NET code that runs everywhere as ubiquitously as HTML does now. If Microsoft plays its cards right, this will happen.

References

view original

May 22nd Links: ASP.NET, Visual Studio, Silverlight, WPF and .NET

Sum up of not-to-miss articles and topics provided weekly by Scott:

One of the things I’m going to try and start doing is a weekly blog post of useful/interesting links on .NET related topics that I’ve found on the web. Below is this week’s version:

ASP.NET

  • Storing Binary Files Directly in the Database using ASP.NET 2.0: Scott Mitchell has a good article that shows how to upload and store images within a SQL database, and then serve them out dynamically from within a web application (very useful for photo albums). You could combine this article with Rick’s above to enable an optional “Save As” option that allows site visitors to save high-resolution versions of images or other file types.

Visual Studio

  • Debugging SQL Server 2005 Stored Procedures in Visual Studio: Scott Mitchell published another great article on how to debug SPROCs using Visual Studio 2005. You can use this approach to set a breakpoint within a SPROC in your database, and then hit it like a normal debug breakpoint when debugging an ASP.NET application that calls it.
  • Using Visual Studio Macros to Increase Productivity: Dan has a nice post describing some of the Macros he has created to manage large projects in Visual Studio. The Visual Studio macro recorder and editor are two features that not enough developers take advantage of (myself included). Whenever you find yourself repeating a task a number of times, I’d highly recommend creating a macro within VS to automate it for future uses.

Silverlight

  • Silverlight 1.1 Alpha Layout System and Controls Framework: One of the features missing in the Silverlight 1.1 Alpha that we shipped at MIX is support for layout management. This is a powerful feature of WPF, and makes it much easier to position and control UI on a page (I’ll post more about this in the future). Dave Relyea from the Silverlight UI team posted a cool sample on his blog that provides a sample implementation of layout management that works with the 1.1 Alpha and includes both Stack and Grid layout manager support. He also then shipped a number of cool custom controls including buttons, labels, textbox, and border controls. Very cool stuff.
  • Silverlight Toolbar Example: A nice sample from Vivek that describes how to create an animated toolbar where the buttons expand when you hover over them. You might also want to check out the “Office UI Ribbon” sample on the www.silverlight.net sample gallery web-site that demonstrates how to build a really cool toolbar within the browser.

WPF

.NET General

  • NDepend 2.2: Scott Dorman has written up a great post on NDepend – which is a .NET utility that enables you to perform code analysis on your .NET projects. This can be useful especially with large projects that you’ve inherited. NDepend also supports a SQL-like query language that enables you to define your own code rules/analytics to search a code base with.
  • Dynamic Language Runtime (DLR) ported to Mono: One of the announcements we made at MIX was that we are shipping a new “dynamic language runtime” framework library for .NET that makes it much easier to build dynamic languages on top of .NET (both the full .NET Framework and Silverlight). We are also shipping four dynamic language implementations of our own: IronPython, IronRuby, Javascript and Dynamic VB. We shipped the source code to the DLR and IronPython as a CodePlex project with a permissive license. This article on O’Reilly describes how someone has already taken the code and got it up and running on Mono. Miguel de Icaza was up in Redmond this week at a compiler dev lab we held and JasonZ and I got a chance to take him out to dinner last night. You can read about Miguel’s trip on his blog here.


read original

210 Ajax Frameworks and Counting

Interesting reading which I found on ajaxian.com. Its about the count of available frameworks. Of course all the numbers are quotes from Google spreadsheet so the exact number is still secret. But the tendency is clear – more ajax frameworks than last year. Here is the whole article:

A year ago, I posted this article showing a count of 134 Ajax frameworks, according to the frameworks area on AjaxPatterns.org.

Today, a recount shows there are 210 Ajax frameworks and libraries listed on the site – the real figure is probably much higher, and by the same token, some of those listed may well be past expiry date. And there’s probably a miscount or two in there, or a duplicated framework – so take it all with a grain of salt! In any event, this means around 1.5 new frameworks per week, a little less than the previous period (around 1 every 3 days from December, 2005 to May, 2006). This time round, there’s a more detailed breakdown available as a Google Spreadsheet, counting by language and framework category. There are 79 pure-Javascript frameworks and 131 server-side frameworks, up from 58 and 76 last year.

Pure Javascript

Multipurpose 37
Remoting 19
Graphics and Effects 6
Flash 3
Logging 5
XML 6
Specialised 3
Subtotal 79

Server-Side

4D 1
C++ 1
Coldfusion 4
Eiffel 0
DotNet (+ASP/C*) 19
Java 44
Lisp 1
Lotus Notes 2
Multi-Language 11
Perl 2
PHP 38
Python 5
Ruby 1
Smalltalk 1
Tcl 1
Subtotal 131

TOTAL 210

The Ruby count caught my eye: one, but it’s a biggie icon smile 210 Ajax Frameworks and Counting .

What does this mean? That a Java developer has 44 frameworks and libraries to choose from? No, the more accurate answer would be around 130-odd. That’s 44 Java, around 8 multi-language (most of the multi-language frameworks offer Java plus one or more other languages) and 79 Javascript frameworks. If you’re still rolling your own XMLHttpRequests or visual effects, now might be a good time to start investigating the alternatives.

view original

Using LINQ to SQL (Part 1)

It’s all about eductaion, thats what my mom used to say to me. Its all about education – thats what Scott Guthrie is doing. Again he posted great article describing how to use LING to SQL. Thats the first part of this series, here is the whole of it:

Developers can use LINQ with any data source. They can express efficient query behavior in their programming language of choice, optionally transform/shape data query results into whatever format they want, and then easily manipulate the results. LINQ-enabled languages can provide full type-safety and compile-time checking of query expressions, and development tools can provide full intellisense, debugging, and rich refactoring support when writing LINQ code.

LINQ supports a very rich extensibility model that facilitates the creation of very efficient domain-specific operators for data sources. The “Orcas” version of the .NET Framework ships with built-in libraries that enable LINQ support against Objects, XML, and Databases.

What Is LINQ to SQL?

LINQ to SQL is an O/RM (object relational mapping) implementation that ships in the .NET Framework “Orcas” release, and which allows you to model a relational database using .NET classes. You can then query the database using LINQ, as well as update/insert/delete data from it.

LINQ to SQL fully supports transactions, views, and stored procedures. It also provides an easy way to integrate data validation and business logic rules into your data model.


Modeling Databases Using LINQ to SQL:

Visual Studio “Orcas” ships with a LINQ to SQL designer that provides an easy way to model and visualize a database as a LINQ to SQL object model. My next blog post will cover in more depth how to use this designer (you can also watch this video I made in January to see me build a LINQ to SQL model from scratch using it).

Using the LINQ to SQL designer I can easily create a representation of the sample “Northwind” database like below:

step1 Using LINQ to SQL (Part 1)

My LINQ to SQL design-surface above defines four entity classes: Product, Category, Order and OrderDetail. The properties of each class map to the columns of a corresponding table in the database. Each instance of a class entity represents a row within the database table.

The arrows between the four entity classes above represent associations/relationships between the different entities. These are typically modeled using primary-key/foreign-key relationships in the database. The direction of the arrows on the design-surface indicate whether the association is a one-to-one or one-to-many relationship. Strongly-typed properties will be added to the entity classes based on this. For example, the Category class above has a one-to-many relationship with the Product class. This means it will have a “Categories” property which is a collection of Product objects within that category. The Product class then has a “Category” property that points to a Category class instance that represents the Category to which the Product belongs.

The right-hand method pane within the LINQ to SQL design surface above contains a list of stored procedures that interact with our database model. In the sample above I added a single “GetProductsByCategory” SPROC. It takes a categoryID as an input argument, and returns a sequence of Product entities as a result. We’ll look at how to call this SPROC in a code sample below.

Understanding the DataContext Class

When you press the “save” button within the LINQ to SQL designer surface, Visual Studio will persist out .NET classes that represent the entities and database relationships that we modeled. For each LINQ to SQL designer file added to our solution, a custom DataContext class will also be generated. This DataContext class is the main conduit by which we’ll query entities from the database as well as apply changes. The DataContext class created will have properties that represent each Table we modeled within the database, as well as methods for each Stored Procedure we added.

For example, below is the NorthwindDataContext class that is persisted based on the model we designed above:

step2 Using LINQ to SQL (Part 1)


LINQ to SQL Code Examples

Once we’ve modeled our database using the LINQ to SQL designer, we can then easily write code to work against it. Below are a few code examples that show off common data tasks:


1) Query Products From the Database

The code below uses LINQ query syntax to retrieve an IEnumerable sequence of Product objects. Note how the code is querying across the Product/Category relationship to only retrieve those products in the “Beverages” category:

C#:

step3 Using LINQ to SQL (Part 1)

VB:

step9 Using LINQ to SQL (Part 1)


2) Update a Product in the Database

The code below demonstrates how to retrieve a single product from the database, update its price, and then save the changes back to the database:

C#:

step5 Using LINQ to SQL (Part 1)

VB:

step11 Using LINQ to SQL (Part 1)

Note: VB in “Orcas” Beta1 doesn’t support Lambdas yet. It will, though, in Beta2 – at which point the above query can be rewritten to be more concise.


3) Insert a New Category and Two New Products into the Database

The code below demonstrates how to create a new category, and then create two new products and associate them with the category. All three are then saved into the database.

Note below how I don’t need to manually manage the primary key/foreign key relationships. Instead, just by adding the Product objects into the category’s “Products” collection, and then by adding the Category object into the DataContext’s “Categories” collection, LINQ to SQL will know to automatically persist the appropriate PK/FK relationships for me.

C#

step4 Using LINQ to SQL (Part 1)

VB:

step12 Using LINQ to SQL (Part 1)


4) Delete Products from the Database

The code below demonstrates how to delete all Toy products from the database:

C#:

step6 Using LINQ to SQL (Part 1)

VB:

step13 Using LINQ to SQL (Part 1)


5) Call a Stored Procedure

The code below demonstrates how to retrieve Product entities not using LINQ query syntax, but rather by calling the “GetProductsByCategory” stored procedure we added to our data model above. Note that once I retrieve the Product results, I can update/delete them and then call db.SubmitChanges() to persist the modifications back to the database.

C#:

step7 Using LINQ to SQL (Part 1)

VB:

step14 Using LINQ to SQL (Part 1)


6) Retrieve Products with Server Side Paging

The code below demonstrates how to implement efficient server-side database paging as part of a LINQ query. By using the Skip() and Take() operators below, we’ll only return 10 rows from the database – starting with row 200.

C#:

step8 Using LINQ to SQL (Part 1)

VB:

step10 Using LINQ to SQL (Part 1)


Summary

LINQ to SQL provides a nice, clean way to model the data layer of your application. Once you’ve defined your data model you can easily and efficiently perform queries, inserts, updates and deletes against it.

Hopefully the above introduction and code samples have helped whet your appetite to learn more. Over the next few weeks I’ll be continuing this series to explore LINQ to SQL in more detail.

read original

AJAX Slide Show

he Slide Show is a simple to use application of the Google AJAX Feed API that is designed to let you add photo slide shows to your pages, sites, and blogs. The slide show control takes photo feeds from all popular sites, such as PhotoBucket, Flickr, and Picasa Web Albums. Any feeds that use Media RSS can be used without customization. However, the slide show control allows any photo-based feed to be accomodated, such as iTunes feeds similar to those found in the Tune Bar solution or the custom feed example below.

The Slide Show control is highly customizable, allowing you to specify options such as the number of photos to display, display and transition time between photos, how the photos link back to their source, etc.

Adding the Slide Show to your page is a snap. The easiest way is to start with our sample “hello world” sample. If you want to tweak the code even further, we have a complete Slide Show Programming Guide available for you to learn from.

view original

Full screen experience with Silverlight

Mr.Guthrie is presenting how Silverlight uses entire browser window:

One of the nice features that Silverlight supports is the ability to go “full screen” and effectively take over the entire screen of a computer (hiding everything else from sight – including the browser frame). This can be very useful when building immersive UI experiences, games, rich video players, etc.

For a nice example of this feature in action, make sure to check out the Fox Movies Sample on www.silverlight.net:

step1 Full screen experience with Silverlight

Once the page loads and the movie starts playing, double-click on the video surface in the middle to switch into full-screen mode (note: the screen-shot above is not in full-screen but rather browser mode). You can then hit the escape key to switch back into normal browser viewing.

How to Implement Full Screen Mode with Silverlight 1.1 using .NET

One of the questions I’ve seen a few people ask is “how can you implement full screen-mode when building Silverlight applications using .NET?” The good news is that the answer is actually pretty easy:

1) First add an input driven event handler to your application (for example: a mouse down or keyboard event handler). For security reasons Silverlight doesn’t allow developers to switch an application into full-screen mode on first application load (you don’t want an application to spoof you). So you’ll instead need to trigger full-screen mode in response to a user action.

2) Within your input event handler set the BrowserHost.IsFullScreen property to true (note: the BrowserHost class lives within the System.Windows.Interop namespace). This will cause Silverlight to switch into full screen mode. Setting this property to false will return it back to normal browser mode.

Simple Full Screen Mode Sample

You can download a simple Silverlight full screen-mode sample I put together written in C# here.

When you run the sample it will load a super simple Silverlight application within the browser and display a text message prompting you to click it to switch into full-screen mode:

step3 Full screen experience with Silverlight

If you click the “Click for Full Screen” text, the application will switch into full-screen mode – which will hide everything else running on the system and take over the entire screen:

step4 Full screen experience with Silverlight

When you switch into full-screen mode, Silverlight will display a user message blurb that will pop-up on the screen for a few seconds and instruct the user that they can press the escape key to switch back into browser mode. After a few seconds this message will disappear and only your content will be visible. In my sample above I also allow the user to click on the “Click to Return to Browser” text and switch back into browser mode as well.

Walkthrough the Simple Full Screen Mode Code

The code to implement the above sample is pretty simple.

To begin with we can open and edit the root .XAML file for the application, and add a UI element to it that we want to use to trigger the full-screen mode. In the sample above I used a control that I named “MyMessage”. Below is all of the XAML for the entire application:

step2 Full screen experience with Silverlight

The below screen-shot shows the code-behind for the .XAML file above – and contains all of the code for the entire application:

step5 Full screen experience with Silverlight=”">

Within the application’s Page_Loaded() event handler above I am wiring up two event handlers:

MyMessage_MouseLeftButtonDown – This event handler will execute anytime a user clicks on the TextBlock message control I added into my XAML file. Within this event handler I’m simply toggling the BrowserHost.IsFullScreen property to true or false depending on whether or not it is already in full screen mode.

BrowserHost_FullScreenChange – This event handler will execute anytime Silverlight switches between full screen and browser mode. It provides a good place to add logic to update the UI when this happens. In the example above I am changing the text on the TextBlock control. I could also have optionally resized controls and/or moved them around the screen to new coordinate positions. Currently the Silverlight 1.1 Alpha doesn’t have layout manager support, so controls won’t automatically re-position unless you write code to manage this yourself (don’t worry – layout manager controls for Silverlight like in the desktop WPF version are coming).

In addition to the IsFullScreen property, BrowserHost class has a number of additional properties and events that are very useful:

step6 Full screen experience with Silverlight

The ActualHeight and ActualWidth properties are particularly useful to lookup the screen dimensions when you switch into full-screen mode – which you can then use when positioning and scaling your UI controls on the page.

Summary

Supporting full-screen mode within Silverlight applications is pretty easy to enable, and offers the ability to provide a nice, immersive user experience.

To learn more about Silverlight, please read my comprehensive Silverlight announcement post as well as visit the www.silverlight.net community site.

To watch me walkthrough building a Silverlight application from scratch using .NET and Visual Studio “Orcas”, please watch this video here.


view original

ASP.NET "Futures" Release

The Microsoft ASP.NET Futures May 2007 (“Futures”) release contains an early developer preview of features providing a wide range of new functionality for both ASP.NET and Silverlight. The Futures release includes early experimental versions of features currently being considered for future versions of ASP.NET and the .NET Framework. The Futures releases assume prior knowledge of the core features of ASP.NET including the previous ASP.NET AJAX Futures January CTP.

ASP.NET AJAX

New functionality includes CSS selector APIs, navigation history support (Back button support), a utility for extracting resources from assemblies, and more. Check out my mix talk for some cool stuff on back button support.

image%7B0%7D thumb%5B1%5D ASP.NET "Futures" Release

image%5B7%5D ASP.NET "Futures" Release

Silverlight Controls for ASP.NET

Enables the ability to include media (video, audio) vector graphics, and animations by using familiar and powerful ASP.NET server controls. This is very cool because it enable server side databinding for video, audio, etc.

Again, Check out my mix talk and Nikhil’s talk

image8 ASP.NET "Futures" Release

image thumb%5B33%5D ASP.NET "Futures" Release

Dynamic Data Controls for ASP.NET

Introduces a set of data controls that provide a simple, intuitive user interface for data-driven Web pages. Check out Maheshp and Polita’s talk from some cool demos.

ASP.NET Application Services

Offers new application services to make AJAX and Silverlight Web applications more discoverable from search engines and easily searchable from within the site. Additional services help you gather and analyze data about client errors.

Check out Stefan and Johnathan’s talk

image thumb%5B21%5D ASP.NET "Futures" Release

image thumb%5B22%5D ASP.NET "Futures" Release

Dynamic Languages support in ASP.NET

Begins support for two languages that are hosted on the DLR, IronPython and Managed Jscript.. Check out Just Glue it

oh, and be sure the check out the reference pages we have for this release. I think it is very complete for such an early release.

view original

Introducing LINQ – Part 4

Part four of Granville Barnett’s series of Introducing LINQ is online. Read it here:

Introduction

The ASP.NET application that we will create we be a 3 tier application, consisting of a data access layer (DAL), a business logic layer (BLL) and a presentation layer (PL).

We will be using Visual Studio Orcas Beta 1 for this tutorial.

Defining our database schema

Before we jump into coding some C# or ASP.NET we need to setup our database, more importantly we first need a database! If you haven’t already go and grab yourself a copy of SQL Express 2005. I will be using SQL Server Management Studio 2005 to create and define my database; however, you can do all of this using Visual Studio 2005 if you want.

Creating a database

Let’s go ahead and create a database for this tutorial. I’m going to create a database called TodoList. To create a database right click the Databases folder in the Object Explorer window and click New Database (Figure 4-1).

Figure 4-1: Creating a database

CreatingADatabase Xlinq4 Introducing LINQ – Part 4

When the New Database window is visible enter TodoList (or any other name you want to use) as the Database name (Figure 4-2).

Figure 4-2: Specifying the database name

Specifyingthedatabasename XLinq4 Introducing LINQ – Part 4

Adding the Tasks table

With our database created we will now add a Tasks table. In SQL Server Management Studio right click the Tables folder and select New Table (Figure 4-3).

Figure 4-3: Creating the Tasks table

CreatingTheTasksTable Xlinq4 Introducing LINQ – Part 4

In the table designer replicate the settings from Figure 4-4.

Figure 4-4: Defining the columns

DefiningTheColumns Xlinq4 Introducing LINQ – Part 4

Note: In Figure 4-4 TaskID is a primary key and identity.

When you save the table, save it as Tasks (Figure 4-5).

Figure 4-5: Saving the table

SavingTheTable Xlinq4 Introducing LINQ – Part 4

Creating the stored procedures

We need to define three stored procedures, one for adding a new task, one for updating the state of a task, and finally one for retrieving all tasks of a specific state (either active, or closed).

Creating a stored procedure is easy, simply right click on the Stored Procedures folder and click New Stored Procedure (Figure 4-6).

Figure 4-6: Creating a stored procedure

CreatingStoredProcedure Xlinq4 Introducing LINQ – Part 4

Below are the three code listings for the stored procedures we will use.

Figure 4-7: AddTask

  1. create procedure AddTask
  2. @Title nvarchar(50),
  3. @Complete bit
  4. as
  5. insert into Tasks (Title, Complete)
  6. values (@Title, @Complete)


Figure 4-8: GetTasksByState

  1. create procedure GetTasksByState
  2. @Complete bit
  3. as
  4. select TaskID, Title, Complete
  5. from Tasks
  6. where Complete = @Complete
  7. order by Title


Figure 4-9: UpdateTaskState

  1. create procedure UpdateTaskState
  2. @TaskID int,
  3. @Complete bit
  4. as
  5. update Tasks
  6. set Complete = @Complete
  7. where TaskID = @TaskID


Setting up our data access layer

With our database ready let’s go ahead and create our DAL. We will use the LINQ to SQL file designer in Visual Studio Orcas to do this.

Note: You will first need to add a connection to the TodoList database in the Server Explorer window.

Right click on your website project and add a new LINQ to SQL file called TodoList (Figure 4-10).

Figure 4-10: Adding a LINQ to SQL file to our project

AddingLINQToSQL Xlinq4 Introducing LINQ – Part 4

With the file created drag and drop the Tasks table and the three stored procedures we created on to the design canvas of the designer (Figure 4-11).

Figure 4-11: Adding our table and sprocs to our DAL

AddingTableTSprocs Xlinq4 Introducing LINQ – Part 4

That’s it! Our DAL is all ready to use.

Adding a business logic layer

In this tutorial there is not much point to adding a BLL, but we will add one nonetheless.

This layer in a real life application this layer would enforce any business rules (parameter checking etc…). Also in a real life application you would want to separate your DAL and BLL into their own components.

Right click the App_Code folder and add a new class called TasksBll.cs, then copy and paste the class definition given in Figure 4-12 into that file.

Figure 4-12: TasksBll.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Org.GBarnett.Dns
  5. {
  6. public static class TasksBll
  7. {
  8. ///
  9. /// Gets all tasks of a particular state
  10. ///
  11. public static List GetTasksByState()
  12. {
  13. using (TodoListDataContext db = new TodoListDataContext())
  14. {
  15. return (from t in db.GetTasksByState() select t).ToList();
  16. }
  17. }
  18. ///
  19. /// Adds a new task
  20. ///
  21. public static void AddTask(string title, bool complete)
  22. {
  23. using (TodoListDataContext db = new TodoListDataContext())
  24. {
  25. db.AddTask(title, complete);
  26. }
  27. }
  28. ///
  29. /// Updates a tasks state
  30. ///
  31. public static void UpdateTaskState(int taskId, bool complete)
  32. {
  33. using (TodoListDataContext db = new TodoListDataContext())
  34. {
  35. db.UpdateTaskState(taskId, complete);
  36. }
  37. }
  38. }
  39. }

Each method of the TasksBll.cs (Figure 4-12) performs the appropriate operation by accessing methods defined in our DAL.

Enter ASP.NET…

As previously mentioned we will use ASP.NET to define the UI.

The UI will consist of 3 controls:

  • DropDownList
  • GridView
  • FormView

Before we begin add a new AJAX Web Form to your project, the name you give it is irrelevant. Add all the following code snippets inside the form tag of the page.

We have two states

Either a task is active or complete. We will use a drop down list control to store these values (Figure 4-12).

Figure 4-13: DropDownList containing the tasks states

  1. <asp:DropDownList ID=“ddlState” runat=“server” AutoPostBack=“true”>
  2. <asp:ListItem Selected=“True” Text=“Active” Value=“false” />
  3. <asp:ListItem Text=“Complete” Value=“true” />
  4. </asp:DropDownList>


Adding an ObjectDataSource

Before we add any more controls to our web page we need to hook our presentation layer up with our BLL. To do this we will add an ObjectDataSource and wire it up to the appropriate methods defined in our BLL.

Figure 4-14: Adding an ObjectDataSource

  1. <asp:ObjectDataSource
  2. ID=“odsTasks”
  3. runat=“server”
  4. TypeName=“TasksBll”
  5. SelectMethod=“GetTasksByState”
  6. InsertMethod=“AddTask”
  7. UpdateMethod=“UpdateTaskState”>
  8. <SelectParameters>
  9. <asp:ControlParameter
  10. ControlID=“ddlState”
  11. Name=“complete”
  12. PropertyName=“SelectedValue”
  13. Type=“Boolean” />
  14. </SelectParameters>
  15. <UpdateParameters>
  16. <asp:Parameter Name=“taskId” Type=“int32″ />
  17. <asp:Parameter Name=“complete” Type=“boolean” />
  18. </UpdateParameters>
  19. <InsertParameters>
  20. <asp:Parameter Name=“title” Type=“string” />
  21. <asp:Parameter Name=“complete” Type=“boolean” />
  22. </InsertParameters>
  23. </asp:ObjectDataSource>


Using a GridView to view the tasks

We will now go ahead and add a GridView to our page (Figure 4-15).

Note: I have customized the Item and Edit templates for the checkbox control.

Figure 4-15: Adding a GridView to our page to display the tasks

  1. <asp:GridView
  2. ID=“gvTasks”
  3. runat=“server”
  4. DataSourceID=“odsTasks”
  5. AutoGenerateColumns=“false”
  6. DataKeyNames=“TaskID”
  7. AllowPaging=“true”
  8. GridLines=“None”
  9. AlternatingRowStyle-CssClass=“alternate”>
  10. <Columns>
  11. <asp:BoundField DataField=“Title” HeaderText=“Task” ReadOnly=“true” />
  12. <asp:TemplateField HeaderText=“Complete”>
  13. <ItemTemplate>
  14. <asp:CheckBox ID=“cbI” runat=“server” Checked=
  15. Enabled=“false” />
  16. </ItemTemplate>
  17. <EditItemTemplate>
  18. <asp:CheckBox ID=“cbE” runat=“server” Checked= />
  19. </EditItemTemplate>
  20. </asp:TemplateField>
  21. <asp:CommandField ShowEditButton=“true” />
  22. </Columns>
  23. </asp:GridView>


Using the FormView to add more tasks

To add a new task we will use a FormView (Figure 4-16).

Note: I have not included any data input checking to keep the example as simple as possible.

Figure 4-16: Adding a FormView to allow the user to add new tasks

  1. <asp:FormView ID=“fvTask” runat=“server” DefaultMode=“Insert” DataSourceID=“odsTasks”>
  2. <InsertItemTemplate>
  3. <p><strong>Title:</strong>
  4. <asp:TextBox ID=“txtTitle” runat=“server” Text= /></p>
  5. <p><strong>Complete:</strong>
  6. <asp:CheckBox ID=“cbC” runat=“server” Checked= /></p>
  7. <p><asp:LinkButton ID=“lbAdd” runat=“server” Text=“Add Task” CommandName=“Insert” /></p>
  8. </InsertItemTemplate>
  9. </asp:FormView>


Adding AJAX functionality to the GridView and the FormView controls

Just to smooth things up I’ve added a few UpdatePanel’s to the page, each wrapping the GridView and FormView respectively.

Figure 4-17: The updated GridView

  1. <asp:UpdatePanel ID=“upTasks” runat=“server”>
  2. <ContentTemplate>
  3. <asp:GridView
  4. ID=“gvTasks”
  5. runat=“server”
  6. DataSourceID=“odsTasks”
  7. AutoGenerateColumns=“false”
  8. DataKeyNames=“TaskID”
  9. AllowPaging=“true”
  10. GridLines=“None”
  11. AlternatingRowStyle-CssClass=“alternate”>
  12. <Columns>
  13. <asp:BoundField DataField=“Title” HeaderText=“Task” ReadOnly=“true” />
  14. <asp:TemplateField HeaderText=“Complete”>
  15. <ItemTemplate>
  16. <asp:CheckBox ID=“cbI”
  17. runat=“server”
  18. Checked=
  19. Enabled=“false” />
  20. </ItemTemplate>
  21. <EditItemTemplate>
  22. <asp:CheckBox ID=“cbE” runat=“server” Checked= />
  23. </EditItemTemplate>
  24. </asp:TemplateField>
  25. <asp:CommandField ShowEditButton=“true” />
  26. </Columns>
  27. </asp:GridView>
  28. </ContentTemplate>
  29. <Triggers>
  30. <asp:AsyncPostBackTrigger ControlID=“ddlState” />
  31. </Triggers>
  32. </asp:UpdatePanel>


Figure 4-18: The update FormView

  1. <asp:UpdatePanel ID=“upAdd” runat=“server”>
  2. <ContentTemplate>
  3. <asp:FormView ID=“fvTask” runat=“server” DefaultMode=“Insert” DataSourceID=“odsTasks”>
  4. <InsertItemTemplate>
  5. <p><strong>Title:</strong>
  6. <asp:TextBox ID=“txtTitle” runat=“server” Text= /></p>
  7. <p><strong>Complete:</strong>
  8. <asp:CheckBox ID=“cbC” runat=“server” Checked= /></p>
  9. <p>
  10. <asp:LinkButton ID=“lbAdd” runat=“server” Text=“Add Task” CommandName=“Insert” />
  11. </p>
  12. </InsertItemTemplate>
  13. </asp:FormView>
  14. </ContentTemplate>
  15. </asp:UpdatePanel>

And on that note we are finished! You can download the full source code at the end of this tutorial.

The experience

From personal experience coding the data access layer can be a very boring process – in this tutorial we have seen how effective LINQ to SQL can be when creating our DAL.

Visual Studio Orcas has introduced a few really cool tools to further assist with the creation of the DAL – we no longer need to spend hours on OR mapping. The great thing about LINQ is the ability to further query your DAL, and create some anonymous type.

There is no doubt in my mind that LINQ is set to revolutionize the way programmers interact with data, more so is the fact that we always use a familiar set of standard query operators!

If you download and run the source you will see the site shown in Figure 4-19.

Figure 4-19: Our to-do list web site

ToDoList Xlinq4 Introducing LINQ – Part 4

Summary

This tutorial showed you how to update the to-do list application Scott Guthrie did some time ago to use LINQ. I really hope that this tutorial has shown you how simply you can build an application using LINQ, and I really do encourage you to play around with the sample code and further extend the application.

view original