Archives

Archives / 2007
  • ASP.NET 3.5 Extensions CTP Preview Released

    Earlier today we released the first CTP preview of an "ASP.NET 3.5 Extensions" release that we've been working on (click here to read my previous post about our product roadmap).  This release brings additional runtime functionality to ASP.NET and .NET 3.5.  You can download it here (if you are using the MVC features also click here to download the MVC Toolkit extras).

  • ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

    The last few weeks I have been working on a series of blog posts that cover the new ASP.NET MVC Framework we are working on.  The ASP.NET MVC Framework is an optional approach you can use to structure your ASP.NET web applications to have a clear separation of concerns, and make it easier to unit test your code and support a TDD workflow.

  • ASP.NET MVC Framework (Part 2): URL Routing

    Last month I blogged the first in a series of posts I'm going to write that cover the new ASP.NET MVC Framework we are working on.  The first post in this series built a simple e-commerce product listing/browsing scenario.  It covered the high-level concepts behind MVC, and demonstrated how to create a new ASP.NET MVC project from scratch to implement and test this e-commerce product listing functionality.

  • ASP.NET MVC Framework (Part 1)

    Two weeks ago I blogged about a new MVC (Model View Controller) framework for ASP.NET that we are going to be supporting as an optional feature soon.  It provides a structured model that enforces a clear separation of concerns within applications, and makes it easier to unit test your code and support a TDD workflow.  It also helps provide more control over the URLs you publish in your applications, and can optionally provide more control over the HTML that is emitted from them.

  • Optimizing the Silverlight Install Experience

    One of the things that is important to think about when you start using Silverlight in your sites/applications is to make sure you handle the "what if the end user doesn't have Silverlight installed yet?" scenario.  Ideally you want to make sure that the installation experience for Silverlight is very seamless, and nicely integrated into your overall end user experience.

  • Important Notice: VS 2008 Beta2 VPC Images Expiring on Nov 1st

    Earlier this month we discovered that the VPC (Virtual PC) images we distributed as part of the VS 2008 Beta2 release this summer unfortunately have an operating system timeout of November 1st of this year.  The standalone VS 2008 setup packages do not have this issue - only the pre-built VPC images do.  So if you've installed VS 2008 on your own operating system image you won't have any issues.

  • ASP.NET MVC Framework

    One of the things that many people have asked for over the years with ASP.NET is built-in support for developing web applications using a model-view-controller (MVC) based architecture.

  • Tip/Trick: Automating Dev, QA, Staging, and Production Web.Config Settings with VS 2005

    One of the questions I get asked fairly regularly is: "how can I can easily change different configuration settings in my web.config file based on whether my application is in a dev, qa, staging or production mode?"  The most common scenario for this is one where an application uses different database connection-strings for testing and production purposes.

  • VS 2008 Support to Treat HTML, CSS and JScript Validation issues as warnings instead of errors

    One of the features that VS 2005 added was support for HTML source validation.  This enabled you to validate your page markup against different HTML schemas and standards (XHTML Transitional/Strict, HTML 4.01, various browser types, etc).  You could also use the HTML validation features to detect missing link, image or style references in your markup.

  • LINQ to SQL (Part 9 - Using a Custom LINQ Expression with the <asp:LinqDatasource> control)

    Over the last few weeks I've been writing a series of blog posts that cover LINQ to SQL.  LINQ to SQL is a built-in O/RM (object relational mapper) that ships in the .NET Framework 3.5 release, and which enables you to model relational databases using .NET classes.  You can use LINQ expressions to query the database with them, as well as update/insert/delete data.

    Below are the first eight parts in this series:

    In Part 5 of the series I introduced the new <asp:LinqDataSource> control in .NET 3.5 and talked about how you can use it to easily bind ASP.NET UI controls to LINQ to SQL data models.  I also demonstrated how to use it a little more in a follow-up post I did that discusses the new <asp:ListView> control (Part 1 - Building a Product Listing Page with Clean CSS UI).

  • LINQ to SQL (Part 8 - Executing Custom SQL Expressions)

    Over the last few weeks I've been writing a series of blog posts that cover LINQ to SQL.  LINQ to SQL is a built-in O/RM (object relational mapper) that ships in the .NET Framework 3.5 release, and which enables you to model relational databases using .NET classes.  You can use LINQ expressions to query the database with them, as well as update/insert/delete data.

    Below are the first seven parts in this series:

    In my last two posts (Part 6 and Part 7) I demonstrated how you can optionally use database stored procedures (SPROCs) to query, insert, update and delete data using a LINQ to SQL data model. 

    One of the questions a few people have asked me since doing these posts has been "what if I want total control over the SQL expressions used by LINQ to SQL - but I don't want to use SPROCs to-do it?"  Today's blog post will cover that - and discuss how you can use custom SQL expressions that you provide to populate your LINQ to SQL data model classes, as well as perform insert, updates, and deletes.

    Using LINQ Query Expressions with LINQ to SQL

    For the purposes of this blog post, let's assume we've used the LINQ to SQL ORM designer in VS 2008 to define a set of data model classes like below for the Northwind database (note: read Part 2 of this series to learn how to use the LINQ to SQL ORM designer to do this):

    In Part 3 of this blog series I covered how you can use the new LINQ language support in VB and C# to query the above data model classes and return back a set of objects that represent the rows/columns in the database. 

    For example, we could add a "GetProductsByCategory" helper method to the DataContext class of our data model that uses a LINQ query to return back Product objects from the database:

    VB:

    C#:

    Once we've defined our encapsulated LINQ helper method, we can then write code like below that uses it to retrieve the products, and iterate over the results:

    VB:

     

    When the LINQ expression within our "GetProductsByCategory" method is evaluated, the LINQ to SQL ORM will automatically execute dynamic SQL to retrieve the Product data and populate the Product objects.  You can use the LINQ to SQL Debug Visualizer to see in the debugger how this LINQ expression is ultimately evaluated.

    Using Custom SQL Queries with LINQ to SQL

    In our sample above we didn't have to write any SQL code to query the database and retrieve back strongly-typed Product objects.  Instead, the LINQ to SQL ORM automatically translated the LINQ expression to SQL for us and evaluated it against the database. 

    But what if we wanted total control over the SQL that is run against our database, and don't want LINQ to SQL to-do it for us in this scenario?  One way to accomplish this would be to use a SPROC like I discussed in Part 6 and Part 7 of this series.  The other approach is to use the "ExecuteQuery" helper method on the DataContext base class and use a custom SQL expression that we provide.

    Using the ExecuteQuery Method

    The ExecuteQuery method takes a SQL query expression as an argument, along with a set of parameter values that we can use to optionally substitute values into the query.  Using it we can execute any raw SQL we want against the database (including custom JOINs across multiple tables).

    What makes the ExecuteQuery method really useful is that it allows you to specify how you want the return values of your SQL expression to be typed.  You can do this either by passing a type-object as a parameter to the method, or by using a generic-based version of the method. 

    For example, we could change the GetProductsByCategory() helper method we created earlier - using a LINQ expression - to instead use the ExecuteQuery method to execute our own raw SQL expression against the database and return "Product" objects as a result:

    VB:

    C#:

    We can then call the GetProductsByCategory() helper method using the exact same code as before:

    But unlike before it will be our custom SQL expression that will run against the database - and not dynamic SQL executed in response to using a LINQ query expression.

    Custom SQL Expressions and Object Tracking for Updates

    By default when you retrieve a data model object using LINQ to SQL, it will track all changes and updates you make to it.  If you call the "SubmitChanges()" method on the DataContext class, it will then transactionally persist all of the updates back to the database.  I cover this in more depth in Part 4 of this LINQ to SQL series.

    One of the cool features of the ExecuteQuery() method is that it can fully participate in this object tracking and update model.  For example, we could write the code below to retrieve all products from a specific category and discount their prices by 10%:

    Because we typed the return value of our ExecuteQuery call in the GetProductsByCategory method to be of type "Product", LINQ to SQL knows to track the Product objects we returned from it.  When we call "SubmitChanges()" on the context object they will be persisted back to the database.

    Custom SQL Expressions with Custom Classes

    The ExecuteQuery() method allows you to specify any class as the return type of a SQL query.  The class does not have to be created using the LINQ to SQL ORM designer, or implement any custom interface - you can pass in any plain old class to it.

    For example, I could define a new ProductSummary class that has a subset of Product properties like below (notice the use of the new C# Automatic Properties feature):

    We could then create a GetProductSummariesByCategory() helper method on our NorthwindDataContext that returns results based on it.  Notice how our SQL statement below requests just the subset of product values we need - the ExecuteQuery method then handles automatically setting these on the ProductSummay objects it returns:

    We can then invoke this helper method and iterate over its results using the code below:

    Custom SQL Expressions for Inserts/Updates/Deletes

    In addition to using custom SQL expressions for queries, we can also execute them to perform custom Insert/Update/Delete logic.

    We can accomplish this by creating the appropriate partial Insert/Update/Delete method for the entity we want to change in a partial class on our DataContext.  We can then use the ExecuteCommand method on the DataContext base class to write the SQL we want to execute.  For example, to override the Delete behavior for Product classes we could define this DeleteProduct partial method:

    And now if we write the below code to remove a specific Product instance from our database, LINQ to SQL will call the DeleteProduct method - which will cause our custom SQL to execute in place of the default dynamic SQL that LINQ to SQL would otherwise use:

    Summary

    The LINQ to SQL ORM automatically generates and executes dynamic SQL to perform queries, updates, inserts and deletes against a database.

    For advanced scenarios, or cases where you want total control over the SQL query/command executed, you also have the ability to customize the ORM to use either SPROCs, or your own custom SQL Expressions, instead.  This provides you with a great deal of flexibility when building and extending your data access layer.

    In future blog posts in this series I'll cover some remaining LINQ to SQL concepts including: Single Table Inheritance, Deferred/Eager Loading, Optimistic Concurrency, and handling Multi-Tier scenarios. 

    Hope this helps,

    Scott

  • LINQ to SQL (Part 7 - Updating our Database using Stored Procedures)

    Over the last few weeks I've been writing a series of blog posts that cover LINQ to SQL.  LINQ to SQL is a built-in O/RM (object relational mapper) that ships in the .NET Framework 3.5 release, and which enables you to model relational databases using .NET classes.  You can use LINQ expressions to query the database with them, as well as update/insert/delete data.

    Below are the first six parts in this series:

    In part 6 I demonstrated how you can optionally use database stored procedures (SPROCs) and user defined functions (UDFs) to query and retrieve data using your LINQ to SQL data model. In today's blog post I'm going to discuss how you can also optionally use SPROCs to update/insert/delete data from the database.

    To help illustrate this - let's start from scratch and build-up a data access layer for the Northwind sample database:

    Step 1: Creating our Data Access Layer (without using SPROCs yet)

    In my Part 2: Defining our Data Model Classes tutorial I discussed how to use the LINQ to SQL ORM designer that is built-in to VS 2008 to create a LINQ to SQL class model like below:

    Adding Validation Rules to our Data Model Classes

    After defining our data model classes and relationships we'll want to add some business logic validation to our data model.  We can do this by adding partial classes to our project that add validation rules to our data model classes (I cover how to-do this in-depth in my Part 4: Updating our Database LINQ to SQL tutorial).

    For example, we could add validation rules to enforce that the Customer's phone number follows a valid phone pattern, and that we don't add Orders where the customer's RequiredDate for delivery is before the actual OrderDate of the Order.  Once defined in partial classes like below, these validation methods will automatically be enforced anytime we write code to update our data model objects in an application.

    VB:

    C#:

     

    Adding a GetCustomer() Helper Method to our DataContext

    Now that we have our data model classes created, and have applied validation rules to them, we can query and interact with the data.  We can do this by writing LINQ expressions against our data model classes to query the database and populate them (I cover how to-do this in my Part 3: Querying our Database LINQ to SQL tutorial).  Alternatively we could map SPROCs to our DataContext and use them to populate the data model classes (I cover how to-do this in my Part 6: Retrieving Data using Stored Procedures LINQ to SQL tutorial).

    When building a LINQ to SQL data layer you'll usually want to encapsulate common LINQ queries (or SPROC invocations) into helper methods that you add to your DataContext class.  We can do this by adding a partial class to our project.  For example, we could add a helper method called "GetCustomer()" that enables us to lookup and retrieve a Customer object from the database based on their CustomerID value:

    VB:

    C#:

     

    Step 2: Using our Data Access Layer (still without SPROCs)

    We now have a data access layer that encapsulates our data model, integrates business validation rules, and enables us to query, update, insert, and delete the data.

    Let's look at a simple scenario using it where we retrieve an existing customer object, update the customer's ContactName and Phone Number, and then create a new Order object and associate it with them.  We can write the below code to do all of this within a single transaction.  LINQ to SQL will ensure that our business logic validation rules are clean before saving anything in the database:

    VB:

    C#:

    LINQ to SQL monitors the modifications we make to the objects we retrieve from the DataContext, and keeps track of all of the objects we add into it.  When we call DataContext.SubmitChanges() at the end, LINQ to SQL will check that our business logic rules are valid, and if so automatically generate the appropriate dynamic SQL to update our Customer record above, and insert a new record into the Orders table. 

    Hang on a second - I thought this post was about using SPROCs??? 

    If you are still reading this, you might be feeling confused about where SPROCs fit into this post.  Why did I show you above how to write code that works with our data model objects, and then causes dynamic SQL to run?  Why haven't I showed you how to call a SPROC for doing inserts/updates/deletes instead yet? 

    The reason is that the programming model in LINQ to SQL for working with data model objects backed by SPROCs is the same as those updated via dynamic SQL.  The way you add data model validation logic is exactly the same (so all the validation rules on our data model classes above still apply when we use SPROCs).  The code snippet above where we use our data access layer to retrieve a customer, update it, and then add a new order associated with it is also exactly the same regardless of whether we are using dynamic SQL for updates, or whether we have configured our data model classes to use SPROCs instead.

    This programming model symmetry is powerful both in that you don't have to learn two ways of doing things, and also because it means that you don't have to decide up front at the beginning of your project whether you are going to use SPROCs or not.  You can start off using the dynamic SQL support provided by the LINQ to SQL ORM for all queries, inserts, updates and deletes.  You can then add your business and validation rules to your model.  And then later you can optionally update your data mapping model to use SPROCs - or not if you decide you don't want to.   The code and tests you write against your data model classes can stay the same regardless of whether you use dynamic SQL or SPROCs.

    We'll now spend the rest of this blog post demonstrating how we can update the data model we've built to use SPROCs for updates/inserts/deletes - while still using the same validation rules, and working with the same code snippets above.

    How to Use SPROCs for Insert/Update/Delete Scenarios

    We can modify the data access layer we've been building to use SPROCs to handle updates, instead of dynamic SQL, in one of two ways:

    1) By using the LINQ to SQL designer to graphically configure SPROCs to execute in response to Insert/Update/Delete operations on our data model classes.

    or:

    2) By adding a NorthwindDataContext partial class in our project, and then by implementing the appropriate Insert/Update/Delete partial methods provided on it (for example: InsertOrder, UpdateOrder, DeleteOrder) that will be called when we insert/update/delete data model objects.  These partial methods will be passed the data model instances we want to update, and we can then execute whatever SPROC or SQL code we want to save it within the database. 

    When we use approach #1 (the LINQ to SQL designer) to graphically configure SPROCs to call, it is under the covers generating the same code (in a partial class it creates) that you'd write when using approach #2.  In general I'd recommend using the LINQ to SQL designer to configure the SPROCs for the 90% case - and then in more advanced scenarios go in and custom tweak the SPROC invocation code it generates if you need to. 

    Step 3: Doing Order Inserts with a SPROC

    We'll begin switching our data model to use SPROCs by starting with the Order object. 

  • Public Hotfix Patch Available for VS 2005 F5 Debugging Performance Issue with ASP.NET

    Over the last year we've seen several people report having performance problems when using F5 to run/debug ASP.NET 2.0 applications using Visual Studio 2005.  The problem in theses cases typically wasn't with building the project, but rather that it sometimes took the debugger a really long time to hit the first breakpoint once it attached to the application (45+ seconds and longer sometimes).

  • LINQ to SQL (Part 6 - Retrieving Data Using Stored Procedures)

    Over the last few weeks I've been writing a series of blog posts that cover LINQ to SQL.  LINQ to SQL is a built-in O/RM (object relational mapper) that ships in the .NET Framework 3.5 release, and which enables you to model relational databases using .NET classes.  You can use LINQ expressions to query the database with them, as well as update/insert/delete data.

    Below are the first five parts of my LINQ to SQL series:

    In these previous LINQ to SQL blog posts I demonstrated how you could use LINQ query expressions to programmatically retrieve data from a database.

    In today's blog post I'll cover how you can also use database stored procedures (SPROCs) and user defined functions (UDFs) with your LINQ to SQL data model.  Today's blog post will specifically cover how to call SPROCs to query and retrieve data from the database.  In my next blog post in this series I'll then show how you can optionally also use SPROCs to update/insert/delete data from the database.

    To SPROC or not to SPROC?  That is the question....

    The question of whether to use Dynamic SQL generated by an ORM or instead use Stored Procedures when building a data layer is a topic that generates endless (very passionate) debate amongst developers, architects and DBAs.  A lot of people much smarter than me have written on this topic, so I won't rehash the arguments for and against each side here.

    The LINQ to SQL ORM that ships in .NET 3.5 is pretty flexible, and can be used to create data model classes whose object model can be independent of the underlying database schema, and which can encapsulate business logic and validation rules that work regardless of whether the data model is populated/persisted via dynamic SQL or via SPROCs.

    In my LINQ to SQL Part 3: Querying our Database post I discussed how you can write LINQ query expressions against a LINQ to SQL data model using code like below:

    When you write LINQ query expressions like this the LINQ to SQL ORM will execute the necessary dynamic SQL for you to retrieve Product objects that matches your query.

    As you'll learn in this post, you can also optionally map SPROCs in the database to your LINQ to SQL DataContext class, which allows you to alternatively retrieve the same Product objects by calling a stored procedure instead:

     

    This ability to use both dynamic SQL and SPROCs with a clean data model layer is pretty powerful, and provides a great deal of flexibility when working on projects.

    The Steps to Map and Call a SPROC using LINQ to SQL

    In my Part 2: Defining our Data Model Classes tutorial I discussed how to use the LINQ to SQL ORM designer to create a LINQ to SQL class model like below:

    Notice above how there are two panes on the LINQ to SQL ORM designer surface.  The left pane enables us to define data model classes that map to our database.  The right method pane allows us to optionally map SPROCs (and UDFs) to our LINQ to SQL DataContext object, which we can then use in-place of dynamic SQL to populate the data model objects.

    How to Map a SPROC to a LINQ to SQL DataContext

    To map SPROCs to our DataContext class, let's first go to the VS 2008 Server Explorer window and look at the SPROCs within our database:

    We can double click any of the SPROCs above to open and edit them.  For example, below is the "CustOrderHist" SPROC in Northwind:

    To map the above SPROC to our LINQ to SQL DataContext, we can drag/drop it from the Server Explorer onto our LINQ to SQL ORM designer.  This will automatically create a new method on our LINQ to SQL DataContext class like below:

    By default the method name created on the DataContext class will be the same as the SPROC name, and the return type of the method will be an automatically created type that follows the "[SprocName]Result" naming pattern. For example: the SPROC above would return a sequence of "CustOrderHistResult" objects.  We could optionally change the name of the method by selecting it in the designer and then use the property grid to rename it.

    How to Call our Newly Mapped SPROC

    Once we've done the steps above to map a SPROC onto our DataContext class, it is easy to use it to programmatically retrieve data.  All we need to-do is call the new method we mapped on our DataContext class to get back a sequence of strongly typed results from the SPROC:

    Calling the SPROC in VB:

    Calling the Sproc in C#:

    In addition to programming looping over the result like in the code samples above, I could also obviously bind the results to any UI control to display them.  For example, the below code databinds the result of our SPROC to a <asp:gridview> control:

    Which then displays the product history of our customer on a page like so:

    Mapping the Return Type of SPROC Methods to Data Model Classes

    In the "CustOrderHist" SPROC example above the stored procedure returned a sequence of product history results containing two columns of data: the ProductName of the product, and the Total Number of orders the customer has made for that product.  The LINQ to SQL designer automatically defined a new "CustOrderHistResult" class to represent this result.

    We could alternatively choose to have the return result of a SPROC map to an existing data model class we have already defined in the LINQ to SQL designer (for example: an existing Product or Order entity class). 

    For example, assume we have a "GetProductsByCategory" SPROC in our database that returns product information like so:

    Like before we can create a "GetProductsByCategory" method on our DataContext that calls this SPROC by dragging it onto our LINQ to SQL designer.  Rather than just dropping the SPROC anywhere on the designer, though, we'll instead drop the SPROC on top of the existing "Product" class in our data model designer:

    This gesture of dropping the SPROC onto the Product class tells the LINQ to SQL designer to have the "GetProductsByCategory" method return a sequence of "Product" objects as a return result:

     

    One of the cool things about having our SPROC return "Product" objects like above is that LINQ to SQL will automatically track the changes made to the returned Product objects just like it would Product objects returned via LINQ queries.  When we call the "SubmitChanges()" method on our DataContext, the changes we have made to these objects will automatically be saved back to the database.

    For example, we could write the code below to retrieve (using a SPROC) and change the price of all products within a specific Category to be 90% of their current value:

    When we call SubmitChanges() at the end it will transactionally update all of the product prices.  To understand more about how change tracking and the SubmitChanges() method work, as well as about how Validation Business Logic can be added to data model entities, please read my LINQ to SQL Part 4: Updating our Database tutorial. 

    In my next blog post in this LINQ to SQL series I'll also cover how you can replace the dynamic insert/update/delete SQL generated by the ORM with custom SPROCs that handle the database updates instead.  The nice thing is that the code above wouldn't change at all if I configured my DataContext to use SPROCs for updates - it would purely be a mapping layer change and the code written against my data model would be oblivious to it. 

    Handling SPROC Output Parameters

    LINQ to SQL maps "out" parameters in SPROCs as reference parameters (ref keyword), and for value types declares the parameter as nullable.

    For example, consider the below "GetCustomerDetails" SPROC which takes a CustomerID as an input parameter, and which returns the company name as an output parameter in addition to its order history as a query result:

    If we drag the above SPROC onto our "Order" class in the LINQ to SQL designer, we could then write the below code to call it:

    VB:

    C#:

    Notice in the code above how the SPROC helper method returns back a sequence of Order objects - but also then returns the CompanyName as an output parameter to the helper method.

    Handling Multiple Result Shapes from SPROCs

    When a stored procedure can return multiple result shapes, the return type of the SPROC method on the DataContext cannot be strongly typed to a single class shape.  For example, consider the SPROC below which returns either a product result or an order result depending on the input parameter:

    LINQ to SQL supports the ability to create SPROC helper methods that can return either a Product or Order shape by adding a partial "NorthwindDataContext" class to the project that defines a method (which in this case we'll call "VariablesShapeSample") that invokes the SPROC and returns an IMultipleResult object like so:

    VB:

    C#:

    Once this method is added into our project we can then call it and convert the result to be either a Product or Order sequence when we are using it:

    VB:

    C#:

    Supporting User Defined Functions (UDFs)

    In addition to SPROCS, LINQ to SQL also supports both scalar-valued and table-valued user defined functions (UDFs), as well as the in-line counterpart to both.  Once added to your DataContext as a method, you can use these UDF functions within your LINQ queries.

    For example, consider a simple scalar user defined function called "MyUpperFunction":

    We can drag/drop it from the Visual Studio Server Explorer onto our LINQ to SQL Designer to add it as a method on our DataContext:

    We can then use this UDF function inline within our LINQ expressions when writing queries against our LINQ to SQL data model (notice it is being used within the "where" clause below):

    VB:

    C#:

    If you use the LINQ to SQL Debug Visualizer that I blogged about here, you can see how LINQ to SQL transforms the above expression queries into raw SQL that execute the UDF inside the database at runtime:

    Summary

    LINQ to SQL supports the ability to call Stored Procedures and UDFs within the database and nicely integrate them into our data model.  In this blog post I demonstrated how you can use SPROCs to easily retrieve data and populate our data model classes.  In my next blog post in this series I'll cover how you can also use SPROCs to override the update/insert/delete logic when you SubmitChanges() on your DataContext to persist back to the database.

    Hope this helps,

    Scott

  • The asp:ListView control (Part 1 - Building a Product Listing Page with Clean CSS UI)

    One of the new controls in ASP.NET 3.5 that I think will be very popular is the <asp:ListView> control.  The ListView control supports the data editing, insertion, deleting, paging and sorting semantics of higher-level controls like the GridView.  But - unlike the GridView - it provides you with complete control over the html markup generated. 

  • Using LINQ to XML (and how to build a custom RSS Feed Reader with it)

    One of the big programming model improvements being made in .NET 3.5 is the work being done to make querying data a first class programming concept.  We call this overall querying programming model "LINQ", which stands for .NET Language Integrated Query.

    LINQ supports a rich extensibility model that facilitates the creation of efficient domain-specific providers for data sources.  .NET 3.5 ships with built-in libraries that enable LINQ support against Objects, XML, and Databases.

  • LINQ to SQL Debug Visualizer

    Probably the biggest programming model improvement being made in .NET 3.5 is the work being done to make querying data a first class programming concept.  We call this overall querying programming model "LINQ", which stands for .NET Language Integrated Query.  Developers can use LINQ with any data source, and built-in libraries are included with .NET 3.5 that enable LINQ support against Objects, XML, and Databases.

    Earlier this summer I started writing a multi-part blog series that discusses the built-in LINQ to SQL provider in .NET 3.5.  LINQ to SQL is an ORM (object relational mapping) implementation that 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.

  • VS 2008 Web Designer and CSS Support

    One of the big features that web developers will quickly discover with VS 2008 is its dramatically improved HTML designer, and the rich CSS support it brings. 

    VS 2008 now uses the same web designer that ships with Microsoft's new Expression Web product.  In addition to providing lots of new functionality, you'll also find that this web designer is much faster than the VS 2005 version (which was based on a much older code base).

    Below is a quick tour of some of the new web designer features that you'll be able to take advantage of with both VS 2008 as well as the free Visual Web Developer 2008 Express:

    Split View Editing

    In addition to supporting both source-view and design-view, VS 2008 adds support for a new "split-view" mode when working on pages.  This allows you to see both the HTML source and the Design View at the same-time, and easily have any changes you make in one view be updated in the other:

     

    CSS Style Manager

    VS 2008 supports a new tool window inside the IDE called "Manage Styles".  This shows all of the CSS stylesheets, and their corresponding rules, for the page you are currently editing.  It can be used both when you are in design-view, as well as when you are in source view on a page:

    A circle around a CSS rule in the manage styles window indicates that particular rule is in use within the current document.  Using the mouse to hover over the rule allows you to quickly see the CSS rule values:

    You can then either right-click on a CSS rule and select "Modify Style" to bring up a graphical CSS rules editor, or you can double click on the rule in the manage styles window to automatically open the stylesheet file and jump immediately to the CSS source definition to edit (with full intellisense):

    For even more tips/tricks about how to best use the "Manage Styles" tool window please read this blog post.

    CSS Properties Window

    One of the other cool new CSS features that is also supported in both design and source view is the new CSS Properties Window:

    When you select an HTML element or ASP.NET server control, the CSS property window will show you all of the CSS settings currently applied to it. You can also change any of the values using the CSS property grid. The "target rule" drop-down in the style toolbar allows you to determine under what rule the settings are applied (read this blog post to learn more about the style toolbar and target rule dropdown). 

    If, like me, you sometimes struggle with large CSS stylesheets and find yourself shouting "why the $!#@ is it looking like that?", you'll find the "summary" view of the CSS Properties window really useful (just click the summary button at the top of the CSS properties pane).  When you press this button it enables a filtering mode that shows you the full inheritance set of CSS rules for the current HTML element or ASP.NET control you are working with:

    In the properties grid above you'll notice that some values are duplicated multiple times - with red arrows striking out previous values.  This indicates that a parent CSS rule setting is being overridden by another CSS rule's value.  You can see both the original value as well as the overridden one in the summary view at the bottom. 

    You can click on the individual values to see where in the CSS precedence hierarchy this value was inherited from or overridden.  In the example below you can see that the final color for the current element that my cursor is on is a dark brown color.  If I select this final color value, the CSS properties window will draw a blue box in the applied-rules list above indicating that this setting is set in the "singlecontent h3" rule:

    If I click on the lighter brown color setting that this rule overrode (and which has the red strike-thru), you can see that it originated with the page's HTML body CSS rule (notice how the body rule below is selected in the applied rules list when I select the overridden value below):

    Please read this dedicated CSS Properties Window blog post to learn even more how to use the CSS property window.

    CSS Source View Intellisense

    The HTML designer supports the ability to select an element or control in design-view, and graphically select a rule from the CSS list to apply to it. 

    You'll also find when in source mode that you now have intellisense support for specifying CSS class rules:

    This is true for both HTML element (like above), as well as with ASP.NET server controls:

    This CSS intellisense is supported in both regular HTML / ASP.NET pages, as well as when working with pages based on master pages and nested master pages.

    Nested Master Page Support

    Earlier this month I wrote a dedicated blog post that covered the new VS 2008 Nested Master Page Support.  All of the above designer and CSS features obviously work with that as well:

    Summary

    The above post provides a quick look at some of the new HTML designer and CSS tool support in VS 2008 (all of the above features also ship with the free Visual Web Developer 2008 Express edition). 

    Because VS 2008 now has multi-targeting support you'll be able to use these feature immediately without having to install .NET 3.5 on your servers.  You can open existing ASP.NET 2.0 projects in VS 2008, have VS 2008 continue to target .NET 2.0 as the runtime target, and begin using these features immediately.

    Over the next week I'll also be starting a new multi-part blog series that covers the new <asp:listview> control that ships as part of ASP.NET in .NET 3.5.  One of the big benefits of the <asp:listview> is that it enables developers to have total control over the HTML output emitted in data scenarios.  This works well with all of the new CSS tool features above, and enables you to more easily create great looking web sites and applications.

  • First Look at IronRuby

    Over the last few years we've been working to make .NET and the CLR a great environment for dynamic languages.  About 14 months ago we formed a dedicated group within my team that has been focused on adding richer CLR runtime support for dynamic languages, as well as delivering first class .NET implementations of popular dynamic languages.

    DLR Background

    This spring we shipped the first preview release of a new .NET library that we call the "Dynamic Language Runtime" (or DLR for short).  It provides a set of features on top of the CLR designed explicitly for dynamic language scenarios.  These include a shared dynamic type system, language hosting model, and support to make it possible to generate fast dynamic code.  These features make it much easier to build high-quality dynamic language implementations on .NET.  These implementations can access and use any of the APIs in the .NET Framework, as well as easily interoperate with code written in any other .NET language (for example: you could write a Ruby class that invokes and uses a C# class, which in turn invokes a Python class).

    This spring at the MIX 07 conference we announced that Microsoft will be shipping 4 dynamic language implementations of our own for .NET:

    • IronPython
    • IronRuby (new)
    • Javascript
    • Dynamic VB (new)

    The source code of our IronPython implementation, as well as the source code for the underlying DLR library, was published on CodePlex in April.  You can download both of them today from the IronPython codeplex site.  All of the source is made available under the MSPL permissive license - which provides full commercial and non-commercial modification rights.

    IronRuby Pre-Alpha Release

    Today we are making available the first public drop of our IronRuby implementation.  You can learn more about how to download the source, build it, and try it out from John Lam's blog post here.

    Today's IronRuby drop is still a very early version, and several language features and most libraries aren't implemented yet (that is why we are calling it a "pre-alpha" release).  It does, though, have much of the core language support implemented, and can also now use standard .NET types and APIs.

    IronRuby has been architected to take advantage of a new DLR feature we call "Dynamic Sites" - which delivers a fast adaptive call-site method caching implementation.  It also uses the lightweight-code generation features of the CLR.  Lightweight code generation enables dynamic language implementations to create in-memory IL that is then JIT'd into native code at runtime (without ever having to save anything to disk).  This can yield much better runtime performance than interpreted code, and the lightweight codegen feature ensures that once we are finished with the JIT'd code we can optionally garbage collect it to avoid leaking. 

    We are releasing today's drop mainly for developers interested in language implementations to start looking at the IronRuby source code, and learn how it was implemented.  Developers interested in playing with an early version of Ruby for .NET can also download it and give it a spin.

    IronRuby Project Plans

    Next month we will be moving the IronRuby source code repository to be hosted on RubyForge.  As part of this move we are also opening up the project to enable non-Microsoft developers to enlist in the project and contribute source code. We'll then work to implement the remaining features and fix compatibility issues found as more libraries and source are ported to run on top of it. 

    The end result will be a compatible, fast, and flexible Ruby implementation on top of .NET that anyone can use for free.

    IronRuby "Hello World" Console Sample

    If you download and build the IronRuby source code, you are probably wondering "how do I start using it?" 

    The easiest way to get started is to run the "rbx.exe" interactive console application that by default is built under the \bin\release directory:

    This console shell provides you with the ability to write Ruby code interactively.  After each line, the shell will interactively execute it. 

    For example, we could output hello world by typing puts "Hello World":

    To output this 10 times in a row, we could type the following:

    To use Windows Forms functionality in IronRuby, we could type a require statement that references the System.Windows.Forms assembly, and then use the MessageBox.Show method to display a message in a modal dialog:

    IronRuby "Hello World" WPF Sample

    One of the benefits of implementing a language on top of .NET is that it enables developers using that language to get full access to the rich framework libraries provided with the .NET Framework.  

    For a simple example of this in action, I could create a "HelloWPF.rb" text file and type in the following Ruby code below:

    The above code uses the WPF UI framework to create a Window that hosts a StackPanel layout manager that initially contains just a button.  When the button is pressed, a new label control is created and added into the StackPanel (causing it to automatically be flowed in the Window). 

    I can then run the above application using IronRuby by passing the "HelloWPF.rb" text file as an argument to rbx.exe:

    When I run it I'll get a window with a WPF button (note above I added a nice DropShadowBitmapEffect to it in the code above):

    And each time I press the button a new label will be added to the Window:

    Not only does having the ability to use all of the .NET APIs provide a lot of power, but you'll notice in the code we wrote how it is possible to naturally integrate .NET APIs into other language syntaxes:

    In the code snippet above I'm using the Ruby block language feature (similar to a Lambda expression with C# 3.0 and VB9) to implement a "Click" event handler on the WPF button.  Notice how within the block the standard Ruby naming patterns can be used when accessing any .NET API.  For example, instead of using the "FontSize" property on the WPF Label we are accessing it using "font_size" as the property accessor name. IronRuby automatically handles the naming conversion - enabling developers to program with a consistent naming pattern regardless of their language of choice.

    Summary

    If you are interested in trying out this first early drop of IronRuby, you can download the source and build it here.

    You can then download my WPF sample above and run it yourself here (note: you must have .NET 3.0 or 3.5 installed - since those deliver the WPF APIs).  To learn more about WPF, I also highly recommend Adam Nathan's excellent WPF Unleashed book (read the review comments on Amazon to see why).

    Hope this helps,

    Scott

  • VS 2008 JavaScript Debugging

    A few weeks ago I blogged about the new JavaScript Intellisense support in VS 2008.

    One of the other JavaScript features that I'm sure will be popular in VS 2008 is the much-improved support for JavaScript debugging.  This is enabled in both the free Visual Web Developer 2008 Express edition as well as in Visual Studio, and makes using JavaScript and building AJAX applications significantly easier.

    Setting JavaScript breakpoints in ASP.NET pages

    One of the annoying things with VS 2005 is that you have to first run your ASP.NET pages before you can set JavaScript breakpoints in them in the debugger.  

  • LINQ to SQL (Part 5 - Binding UI using the ASP:LinqDataSource Control)

    Over the last few weeks I've been writing a series of blog posts that cover LINQ to SQL.  LINQ to SQL is a built-in O/RM (object relational mapper) that ships in the .NET Framework 3.5 release, and which enables you to easily model relational databases using .NET classes.  You can use LINQ expressions to query the database with them, as well as update/insert/delete data.

    Below are the first four parts of my LINQ to SQL series:

    In these previous LINQ to SQL blog posts I focused on how you can programmatically use LINQ to SQL to easily query and update data within a database.

  • LINQ to SQL (Part 4 - Updating our Database)

    Over the last few weeks I've been writing a series of blog posts that cover LINQ to SQL.  LINQ to SQL is a built-in O/RM (object relational mapper) that ships in the .NET Framework 3.5 release, and which enables you to easily model relational databases using .NET classes.  You can use LINQ expressions to query the database with them, as well as update/insert/delete data.

    Below are the first three parts of my LINQ to SQL series:

    In today's blog post I'll cover how we we can use the data model we created earlier, and use it to update, insert, and delete data.  I'll also show how we can cleanly integrate business rules and custom validation logic with our data model.

  • LINQ to SQL (Part 3 - Querying our Database)

    Last month I started a blog post series covering LINQ to SQL.  LINQ to SQL is a built-in O/RM (object relational mapping) framework that ships in the .NET Framework 3.5 release, and which enables you to easily model relational databases using .NET classes.  You can then use LINQ expressions to query the database with them, as well as update/insert/delete data from it.

  • VS 2008 JavaScript Intellisense

    One of the features that web developers will really like with VS 2008 is its built-in support for JavaScript intellisense.  This is enabled in both the free Visual Web Developer 2008 Express edition as well as in Visual Studio, and makes using JavaScript and building AJAX applications significantly easier. 

  • VS 2008 Multi-Targeting Support

    Earlier this month at TechEd we announced the official name of Visual Studio "Orcas" - which will be called Visual Studio 2008.  We also said that the official name for the .NET Framework "Orcas" release will be called .NET Framework 3.5 (it includes the new LINQ support, integrated ASP.NET AJAX support, new ASP.NET data controls, and more).

  • Building Silverlight Applications using .NET

    I'm just about to hop on the flight back to Seattle after finishing up a 10 day business trip to Europe where I spoke at conferences and user group events in Budapest, Amsterdam and Zurich.  Although trips like these are a little exhausting, I find them really valuable as a way to connect with developers from around the world, as well as provide me the opportunity to create and deliver new presentations and samples.

  • Tip/Trick: Creating Packaged ASP.NET Setup Programs with VS 2005

    You have built an ASP.NET Web Application using Visual Studio 2005, and want to enable customers to automatically install and deploy it on servers via an easy setup program.

    Specifically, you want to create a standard Windows setup program that will create and configure the application on IIS, copy all of the application’s files to the appropriate location on the server, and ensure that ASP.NET 2.0 is correctly mapped to run the application. You also want the setup program to prompt the customer for the database location that the new application should use, and have the setup program automatically update the web.config file with the database connectionstring settings the customer provided.

    One solution to consider using is the built-in "Web Setup Project" support that is built-in to Visual Studio 2005.  Web Setup Projects can be used to pipe the compilation outputs from VS 2005 Web Application Projects as well as Web Site Projects (when used with VS 2005 Web Deployment Projects), to create encapsulated Windows setup programs. The below walkthrough demonstrates step-by-step how to create and use one.

    1) Create a VS 2005 Web Application Project

    To begin with, we’ll start with an empty instance of Visual Studio and create a new VS 2005 Web Application project (select File->New Project->ASP.NET Web Application).  For the purposes of this simple sample we’ll have two pages in the project:

    We’ll add a label to the Default.aspx page and a Page_Load event handler in the code-behind to output the current timestamp on each request. When I press F5 to build and run the application, the project will compile and run as I’d expect (and by default use the built-in VS Web Server):

    2) Add a VS 2005 Web Setup Project to the Solution

    Now that we have a simple ASP.NET application built, we’ll want to add a VS 2005 Web Setup Project to the solution. Choose the File->Add->New Project menu item to add one into your solution:

    Note that the “Web Setup Project” type shows up under the “Other Project Types->Setup and Deployment” node in the New Project dialog above. Name it whatever you want and hit ok. It will then show up in your solution explorer as a separate project.

    Our next step will be to configure the web setup project to take the compiled assemblies (\bin directory contents) + content markup (.aspx, .config, etc files) from our Web Application Project and use them as inputs within our setup project. To-do this, right-click on the web setup project node in the solution explorer and choose the “Add->Project Output” context menu item:

    A dialog will then appear allowing us to select which project in the solution, and which of its project contents, we want to add to the setup package:

    For ASP.NET Web Application Projects it is really important that we select both the “Primary Output” (which are the compiled assemblies for the \bin directory) as well as the “Content Files” (which are the .aspx markup files) within this dialog.

    By default, the web setup project will copy both of these items into the root of the target Web Application Folder that the setup project will create. You can see that it is configured this way by opening up the “File System” view within the web setup project (right click on the web setup project root and choose View->File System):

    This actually isn’t what we want to have happen though – since we really want the assemblies (indicated by the Primary Output node) to be copied into the application’s \bin directory instead (otherwise ASP.NET won’t be able to find them at runtime). To fix this, drag/drop the “Primary Output from MyApplication” node into the \bin directory. Once this is done you should be able to click on the “Web Application Folder” node on the left-hand side and see this:

    And then click on the “bin” folder sub-node and see this:

    We now have a basic web setup project created and configured for our ASP.NET Web Application. Next step is to build and run it.

    3) Build and Run the VS 2005 Web Setup Project to the Solution

    To build the web-setup project we can right-click on the web setup project node within the solution explorer and choose the “Build” option:

    If you open the output window within VS (View->Output menu item), you will see the results of this build operation:

    Our “MyApplicationSetup” project created a new MyApplicationSetup.msi Windows installer file and compressed and packaged the contents of our ASP.NET Web Application (note: in the web setup project properties dialog you can choose whether the compression algorithm used is optimized for size or speed).

    Very Important: Because setup projects take awhile to build, they are by default marked not to build as part of the solution.  What this means is that you need to right-click on them and explicitly do a build in order for them to be recompiled.  Be careful to-do this when you make and test changes - otherwise you'll be running the previously compiled version and not the one with your latest code!

  • Microsoft Surface and WPF

    Microsoft earlier today announced a new product called "Microsoft Surface".  If you haven't checked out the online videos of it yet, I highly recommend watching them here.  It is one of those products that looks and feels like it comes from a science fiction movie - but it is actually real.

  • Using LINQ to SQL (Part 1)

    Over the last few months I wrote a series of blog posts that covered some of the new language features that are coming with the Visual Studio and .NET Framework "Orcas" release.  Here are pointers to the posts in my series:

    The above language features help make querying data a first class programming concept.  We call this overall querying programming model "LINQ" - which stands for .NET Language Integrated Query.

    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.

  • New "Orcas" Language Feature: Anonymous Types

    Over the last two months I've published a series of posts covering some of the new language features that are coming as part of the Visual Studio and .NET Framework "Orcas" release.  Here are pointers to the first four posts in my series:

    Today's blog post covers the last new feature in my language series: Anonymous Types. 

    What are Anonymous Types?

    Anonymous types are a convenient language feature of C# and VB that enable developers to concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.

    Anonymous types are particularly useful when querying and transforming/projecting/shaping data with LINQ.

    Anonymous Type Example

    In my previous Query Syntax blog post I demonstrated how you could transform data with projections. This is a powerful feature of LINQ that enables you to perform query operations on a data source (regardless of whether it is a database, an XML file, or an in-memory collection), and shape the results of the data being queried into a different structure/format than the original data source is in.

    In my previous Query Syntax blog post I defined a custom "MyProduct" class that I used to represent my transformed product data.  By explicitly defining the "MyProduct" class I have a formal CLR type contract that I can use to easily pass my custom-shaped product results between web-services or between multiple classes/assemblies within my application solution.

    However, there are times when I just want to query and work with data within my current code scope, and I don't want to have to formally define an explicit class that represents my data in order to work with it.  This is where anonymous types are very useful, as they allow you to concisely define a new type to use inline within your code. 

  • New "Orcas" Language Feature: Query Syntax

    Last month I started a series of posts covering some of the new VB and C# language features that are coming as part of the Visual Studio and .NET Framework "Orcas" release.  Here are pointers to the first three posts in my series:

    Today's blog post covers another fundamental new language feature: Query Syntax.

  • Tip/Trick: Enabling SSL on IIS 7.0 Using Self-Signed Certificates

    SSL enables browsers to communicate with a web-server over a secure channel that prevents eavesdropping, tampering and message forgery.  You should always use SSL for login pages where users are entering usernames/passwords, as well as for all other sensitive pages on sites (for example: account pages that show financial or personal information). 

  • JSON Hijacking and How ASP.NET AJAX 1.0 Avoids these Attacks

    Recently some reports have been issued by security researchers describing ways hackers can use the JSON wire format used by most popular AJAX frameworks to try and exploit cross domain scripts within browsers.  Specifically, these attacks use HTTP GET requests invoked via an HTML <script src=""> include element to circumvent the "same origin policy" enforced by browsers (which limits JavaScript objects like XmlHttpRequest to only calling URLs on the same domain that the page was loaded from), and then look for ways to exploit the JSON payload content.

  • IIS 7.0

    IIS 7.0 is one of the products that my team is shipping later this year that I'm most excited about.  It is the most significant release of our web-server that we've done since IIS 1.0, and introduces a huge number of improvements for both administrators and developers.

  • Microsoft Joins OpenAJAX Alliance

    The OpenAjax alliance is a group of vendors, open source projects and companies using AJAX that are focused on developing common AJAX standards and ensuring interoperability across different AJAX frameworks, tools and technologies.  Joining the group will help ensure that the Microsoft AJAX Library and ASP.NET 2.0 AJAX Extensions integrate well with other AJAX frameworks and server technologies.  

  • New C# "Orcas" Language Features: Automatic Properties, Object Initializers, and Collection Initializers

    Last week we shipped the March CTP of our Visual Studio and .NET Framework "Orcas" release.   It is available as a free download by anyone, and can be downloaded as as both a VPC (allowing you to run it in a virtual machine) as well as a standalone setup install (note: if you are running Vista you want to make sure you only use the VPC version).  You can download it here.

  • Tip/Trick: Url Rewriting with ASP.NET

    People often ask me for guidance on how they can dynamically "re-write" URLs and/or have the ability to publish cleaner URL end-points within their ASP.NET web applications.  This blog post summarizes a few approaches you can take to cleanly map or rewrite URLs with ASP.NET, and have the option to structure the URLs of your application however you want.

  • WPF Text Reading and Flow Document Support, and the new NYTimes, Daily Mail, and Seattle Post-Intelligencer Reader Applications

    Windows Presentation Foundation (WPF aka "Avalon") is a massive step forward for Windows client development, and delivers a super-rich .NET UI framework that integrates vector graphics, rich flow text support, and 3D visualization with a powerful control model framework.  You get WPF support with .NET 3.0 (which is built-in with Windows Vista and available as a separate download for other Windows OS versions).

  • Visual Studio "Orcas" Web Designer Integrated into Main

    This weekend was a really exciting one for the VS Web Tools team.  On Saturday they checked in their new HTML and ASP.NET WYSIWYG designer into Visual Studio.  This designer is a major, major improvement over previous HTML designers within Visual Studio, and will be a shared component used by both Visual Studio and Expression Web Designer going forward.