Using jQuery to Insert a New Database Record

The goal of this blog entry is to explore the easiest way of inserting a new record into a database using jQuery and .NET. I’m going to explore two approaches: using Generic Handlers and using a WCF service (In a future blog entry I’ll take a look at OData and WCF Data Services).

Create the ASP.NET Project

I’ll start by creating a new empty ASP.NET application with Visual Studio 2010. Select the menu option File, New Project and select the ASP.NET Empty Web Application project template.

clip_image002

Setup the Database and Data Model

I’ll use my standard MoviesDB.mdf movies database. This database contains one table named Movies that looks like this:

clip_image004

I’ll use the ADO.NET Entity Framework to represent my database data:

  1. Select the menu option Project, Add New Item and select the ADO.NET Entity Data Model project item. Name the data model MoviesDB.edmx and click the Add button.
  2. In the Choose Model Contents step, select Generate from database and click the Next button.
  3. In the Choose Your Data Connection step, leave all of the defaults and click the Next button.
  4. In the Choose Your Data Objects step, select the Movies table and click the Finish button.

Unfortunately, Visual Studio 2010 cannot spell movie correctly :) You need to click on Movy and change the name of the class to Movie. In the Properties window, change the Entity Set Name to Movies.

clip_image006

Using a Generic Handler

In this section, we’ll use jQuery with an ASP.NET generic handler to insert a new record into the database. A generic handler is similar to an ASP.NET page, but it does not have any of the overhead. It consists of one method named ProcessRequest().

Select the menu option Project, Add New Item and select the Generic Handler project item. Name your new generic handler InsertMovie.ashx and click the Add button.

Modify your handler so it looks like Listing 1:

Listing 1 – InsertMovie.ashx

  • using System.Web;   
  •   
  • namespace WebApplication1 {   
  •     /// <summary>   
  •     /// Inserts a new movie into the database   
  •     /// </summary>   
  •     public class InsertMovie : IHttpHandler {   
  •   
  •         private MoviesDBEntities _dataContext = new MoviesDBEntities();   
  •   
  •         public void ProcessRequest(HttpContext context) {   
  •             context.Response.ContentType = ”text/plain”;   
  •   
  •             // Extract form fields   
  •             var title = context.Request["title"];   
  •             var director = context.Request["director"];   
  •   
  •             // Create movie to insert   
  •             var movieToInsert = new Movie { Title = title, Director = director };   
  •   
  •             // Save new movie to DB   
  •             _dataContext.AddToMovies(movieToInsert);   
  •             _dataContext.SaveChanges();   
  •   
  •             // Return success   
  •             context.Response.Write(”success”);   
  •         }   
  •   
  •         public bool IsReusable {   
  •             get {   
  •                 return true;   
  •             }   
  •         }   
  •   
  •   
  •   
  •     }   
  • }  
  • using System.Web;
    
    namespace WebApplication1 {
        /// <summary>
        /// Inserts a new movie into the database
        /// </summary>
        public class InsertMovie : IHttpHandler {
    
            private MoviesDBEntities _dataContext = new MoviesDBEntities();
    
            public void ProcessRequest(HttpContext context) {
                context.Response.ContentType = "text/plain";
    
                // Extract form fields
                var title = context.Request["title"];
                var director = context.Request["director"];
    
                // Create movie to insert
                var movieToInsert = new Movie { Title = title, Director = director };
    
                // Save new movie to DB
                _dataContext.AddToMovies(movieToInsert);
                _dataContext.SaveChanges();
    
                // Return success
                context.Response.Write("success");
            }
    
            public bool IsReusable {
                get {
                    return true;
                }
            }
    
        }
    }

    In Listing 1, the ProcessRequest() method is used to retrieve a title and director from form parameters. Next, a new Movie is created with the form values. Finally, the new movie is saved to the database and the string “success” is returned.

    Using jQuery with the Generic Handler

    We can call the InsertMovie.ashx generic handler from jQuery by using the standard jQuery post() method. The following HTML page illustrates how you can retrieve form field values and post the values to the generic handler:

    Listing 2 – Default.htm

  • <!DOCTYPE html PUBLIC ”-//W3C//DTD XHTML 1.0 Transitional//EN” ”http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>  
  • <html xmlns=”http://www.w3.org/1999/xhtml”>  
  • <head>  
  •     <title>Add Movie</title>  
  •   
  •     <script src=”http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js” type=”text/javascript”></script>    
  • </head>  
  • <body>  
  •   
  • <form>  
  •     <label>Title:</label>  
  •     <input name=”title” />  
  •   
  •     <br />  
  •   
  •     <label>Director:</label>  
  •     <input name=”director” />  
  • </form>  
  •   
  • <button id=”btnAdd”>Add Movie</button>  
  •   
  •   
  • <script type=”text/javascript”>  
  •   
  •     $(”#btnAdd”).click(function () {   
  •         $.post(”InsertMovie.ashx”, $(”form”).serialize(), insertCallback);   
  •     });   
  •   
  •     function insertCallback(result) {   
  •         if (result == ”success”) {   
  •             alert(”Movie added!”);   
  •         } else {   
  •             alert(”Could not add movie!”);   
  •         }   
  •     }   
  •   
  •   
  • </script>  
  •   
  • </body>  
  • </html>  
  • <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Add Movie</title>
    
        <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script>
    </head>
    <body>
    
    <form>
        <label>Title:</label>
        <input name="title" />
    
        <br />
    
        <label>Director:</label>
        <input name="director" />
    </form>
    
    <button id="btnAdd">Add Movie</button>
    
    <script type="text/javascript">
    
        $("#btnAdd").click(function () {
            $.post("InsertMovie.ashx", $("form").serialize(), insertCallback);
        });
    
        function insertCallback(result) {
            if (result == "success") {
                alert("Movie added!");
            } else {
                alert("Could not add movie!");
            }
        }
    
    </script>
    
    </body>
    </html>

     

    When you open the page in Listing 2 in a web browser, you get a simple HTML form:

    clip_image008

    Notice that the page in Listing 2 includes the jQuery library. The jQuery library is included with the following SCRIPT tag:

    <script src=”http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js” type=”text/javascript”></script>

    The jQuery library is included on the Microsoft Ajax CDN so you can always easily include the jQuery library in your applications. You can learn more about the CDN at this website:

    http://www.asp.net/ajaxLibrary/cdn.ashx

    When you click the Add Movie button, the jQuery post() method is called to post the form data to the InsertMovie.ashx generic handler. Notice that the form values are serialized into a URL encoded string by calling the jQuery serialize() method. The serialize() method uses the name attribute of form fields and not the id attribute.

    Notes on this Approach

    This is a very low-level approach to interacting with .NET through jQuery – but it is simple and it works! And, you don’t need to use any JavaScript libraries in addition to the jQuery library to use this approach.

    The signature for the jQuery post() callback method looks like this:

    callback(data, textStatus, XmlHttpRequest)

    The second parameter, textStatus, returns the HTTP status code from the server. I tried returning different status codes from the generic handler with an eye towards implementing server validation by returning a status code such as 400 Bad Request when validation fails (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html ). I finally figured out that the callback is not invoked when the textStatus has any value other than “success”.

    Using a WCF Service

    As an alternative to posting to a generic handler, you can create a WCF service.

    You create a new WCF service by selecting the menu option Project, Add New Item and selecting the Ajax-enabled WCF Service project item. Name your WCF service InsertMovie.svc and click the Add button.

    clip_image010

    Modify the WCF service so that it looks like Listing 3:

    Listing 3 – InsertMovie.svc

  • using System.ServiceModel;   
  • using System.ServiceModel.Activation;   
  •   
  • namespace WebApplication1 {   
  •   
  •     [ServiceBehavior(IncludeExceptionDetailInFaults=true)]   
  •     [ServiceContract(Namespace = "")]   
  •     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]   
  •     public class MovieService {   
  •   
  •         private MoviesDBEntities _dataContext = new MoviesDBEntities();   
  •   
  •         [OperationContract]   
  •         public bool Insert(string title, string director) {   
  •             // Create movie to insert   
  •             var movieToInsert = new Movie { Title = title, Director = director };   
  •   
  •             // Save new movie to DB   
  •             _dataContext.AddToMovies(movieToInsert);   
  •             _dataContext.SaveChanges();   
  •   
  •             // Return movie (with primary key)   
  •             return true;   
  •         }   
  •   
  •     }   
  • }  
  • using System.ServiceModel;
    using System.ServiceModel.Activation;
    
    namespace WebApplication1 {
    
        [ServiceBehavior(IncludeExceptionDetailInFaults=true)]
        [ServiceContract(Namespace = "")]
        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
        public class MovieService {
    
            private MoviesDBEntities _dataContext = new MoviesDBEntities();
    
            [OperationContract]
            public bool Insert(string title, string director) {
                // Create movie to insert
                var movieToInsert = new Movie { Title = title, Director = director };
    
                // Save new movie to DB
                _dataContext.AddToMovies(movieToInsert);
                _dataContext.SaveChanges();
    
                // Return movie (with primary key)
                return true;
            }
    
        }
    }

     

    The WCF service in Listing 3 uses the Entity Framework to insert a record into the Movies database table. The service always returns the value true.

    Notice that the service in Listing 3 includes the following attribute:

    [ServiceBehavior(IncludeExceptionDetailInFaults=true)]

    You need to include this attribute if you want to get detailed error information back to the client. When you are building an application, you should always include this attribute. When you are ready to release your application, you should remove this attribute for security reasons.

    Using jQuery with the WCF Service

    Calling a WCF service from jQuery requires a little more work than calling a generic handler from jQuery. Here are some good blog posts on some of the issues with using jQuery with WCF:

    The primary requirement when calling WCF from jQuery is that the request use JSON:

    • The request must include a content-type:application/json header.
    • Any parameters included with the request must be JSON encoded.

    Unfortunately, jQuery does not include a method for serializing JSON (Although, oddly, jQuery does include a parseJSON() method for deserializing JSON). Therefore, we need to use an additional library to handle the JSON serialization.

    The page in Listing 4 illustrates how you can call a WCF service from jQuery.

    Listing 4 – Default2.aspx

  • <!DOCTYPE html PUBLIC ”-//W3C//DTD XHTML 1.0 Transitional//EN” ”http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>  
  • <html xmlns=”http://www.w3.org/1999/xhtml”>  
  • <head>  
  •     <title>Add Movie</title>  
  •   
  •     <script src=”http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js” type=”text/javascript”></script>    
  •     <script src=”Scripts/json2.js” type=”text/javascript”></script>  
  •   
  • </head>  
  • <body>  
  •   
  • <form>  
  •     <label>Title:</label>  
  •     <input id=”title” />  
  •   
  •     <br />  
  •   
  •     <label>Director:</label>  
  •     <input id=”director” />  
  • </form>  
  •   
  • <button id=”btnAdd”>Add Movie</button>  
  •   
  •   
  • <script type=”text/javascript”>  
  •   
  •     $(”#btnAdd”).click(function () {   
  •         // Convert the form into an object   
  •         var data = { title: $(”#title”).val(), director: $(”#director”).val() };   
  •   
  •         // JSONify the data   
  •         data = JSON.stringify(data);   
  •   
  •         // Post it   
  •         $.ajax({   
  •             type: ”POST”,   
  •             contentType: ”application/json; charset=utf-8″,   
  •             url: ”MovieService.svc/Insert”,   
  •             data: data,   
  •             dataType: ”json”,   
  •             success: insertCallback    
  •         });   
  •     });   
  •   
  •   
  •     function insertCallback(result) {   
  •         // unwrap result   
  •         resultresult = result["d"];   
  •            
  •         if (result === true) {   
  •             alert(”Movie added!”);   
  •         } else {   
  •             alert(”Could not add movie!”);   
  •         }   
  •     }   
  •   
  •   
  • </script>  
  •   
  • </body>  
  • </html>  
  • <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Add Movie</title>
    
        <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script>
        <script src="Scripts/json2.js" type="text/javascript"></script>
    
    </head>
    <body>
    
    <form>
        <label>Title:</label>
        <input id="title" />
    
        <br />
    
        <label>Director:</label>
        <input id="director" />
    </form>
    
    <button id="btnAdd">Add Movie</button>
    
    <script type="text/javascript">
    
        $("#btnAdd").click(function () {
            // Convert the form into an object
            var data = { title: $("#title").val(), director: $("#director").val() };
    
            // JSONify the data
            data = JSON.stringify(data);
    
            // Post it
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "MovieService.svc/Insert",
                data: data,
                dataType: "json",
                success: insertCallback
            });
        });
    
        function insertCallback(result) {
            // unwrap result
            result = result["d"];
    
            if (result === true) {
                alert("Movie added!");
            } else {
                alert("Could not add movie!");
            }
        }
    
    </script>
    
    </body>
    </html>

    There are several things to notice about Listing 4. First, notice that the page includes both the jQuery library and Douglas Crockford’s JSON2 library:

    <script src=”Scripts/json2.js” type=”text/javascript”></script>

    You need to include the JSON2 library to serialize the form values into JSON. You can download the JSON2 library from the following location:

    http://www.json.org/js.html

    When you click the button to submit the form, the form data is converted into a JavaScript object:

    // Convert the form into an object

    var data = { title: $(”#title”).val(), director: $(”#director”).val() };

    Next, the data is serialized into JSON using the JSON2 library:

    // JSONify the data

    var data = JSON.stringify(data);

    Finally, the form data is posted to the WCF service by calling the jQuery ajax() method:

    // Post it

    $.ajax({

      type: ”POST”,

      contentType: ”application/json; charset=utf-8″,

      url: ”MovieService.svc/Insert”,

      data: data,

      dataType: ”json”,

      success: insertCallback

    });

    You can’t use the standard jQuery post() method because you must set the content-type of the request to be application/json. Otherwise, the WCF service will reject the request for security reasons. For details, see the Scott Guthrie blog post:

    http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx

    The insertCallback() method is called when the WCF service returns a response. This method looks like this:

    function insertCallback(result) {

      // unwrap result

      result = result["d"];

      if (result === true) {

          alert(”Movie added!”);

      } else {

        alert(”Could not add movie!”);

      }

    }

    When we called the jQuery ajax() method, we set the dataType to JSON. That causes the jQuery ajax() method to deserialize the response from the WCF service from JSON into a JavaScript object automatically. The following value is passed to the insertCallback method:

    {”d”:true}

    For security reasons, a WCF service always returns a response with a “d” wrapper. The following line of code removes the “d” wrapper:

    // unwrap result

    result = result["d"];

    To learn more about the “d” wrapper, I recommend that you read the following blog posts:

    Summary

    In this blog entry, I explored two methods of inserting a database record using jQuery and .NET. First, we created a generic handler and called the handler from jQuery. This is a very low-level approach. However, it is a simple approach that works.

    Next, we looked at how you can call a WCF service using jQuery. This approach required a little more work because you need to serialize objects into JSON. We used the JSON2 library to perform the serialization.

    In the next blog post, I want to explore how you can use jQuery with OData and WCF Data Services

    Building a Windows Phone 7 Twitter Application using Silverlight

     On Monday I had the opportunity to present the MIX 2010 Day 1 Keynote in Las Vegas (you can watch a video of it here).  In the keynote I announced the release of the Silverlight 4 Release Candidate (we’ll ship the final release of it next month) and the VS 2010 RC tools for Silverlight 4.  I also had the chance to talk for the first time about how Silverlight and XNA can now be used to build Windows Phone 7 applications.

    During my talk I did two quick Windows Phone 7 coding demos using Silverlight – a quick “Hello World” application and a “Twitter” data-snacking application.  Both applications were easy to build and only took a few minutes to create on stage.  Below are the steps you can follow yourself to build them on your own machines as well.

    [Note: In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu]

    Building a “Hello World” Windows Phone 7 Application

    First make sure you’ve installed the Windows Phone Developer Tools CTP – this includes the Visual Studio 2010 Express for Windows Phone development tool (which will be free forever and is the only thing you need to develop and build Windows Phone 7 applications) as well as an add-on to the VS 2010 RC that enables phone development within the full VS 2010 as well.

    After you’ve downloaded and installed the Windows Phone Developer Tools CTP, launch the Visual Studio 2010 Express for Windows Phone that it installs or launch the VS 2010 RC (if you have it already installed), and then choose “File”->”New Project.”  Here, you’ll find the usual list of project template types along with a new category: “Silverlight for Windows Phone”. The first CTP offers two application project templates. The first is the “Windows Phone Application” template – this is what we’ll use for this example. The second is the “Windows Phone List Application” template – which provides the basic layout for a master‑details phone application:

    image

    After creating a new project, you’ll get a view of the design surface and markup. Notice that the design surface shows the phone UI, letting you easily see how your application will look while you develop. For those familiar with Visual Studio, you’ll also find the familiar ToolBox, Solution Explorer and Properties pane.

    image 

    For our HelloWorld application, we’ll start out by adding a TextBox and a Button from the Toolbox. Notice that you get the same design experience as you do for Silverlight on the web or desktop. You can easily resize, position and align your controls on the design surface. Changing properties is easy with the Properties pane. We’ll change the name of the TextBox that we added to username and change the page title text to “Hello world.”

    image

    We’ll then write some code by double‑clicking on the button and create an event handler in the code-behind file (MainPage.xaml.cs).

    image

    We’ll start out by changing the title text of the application. The project template included this title as a TextBlock with the name textBlockListTitle (note that the current name incorrectly includes the word “list”; that will be fixed for the final release.)  As we write code against it we get intellisense showing the members available.  Below we’ll set the Text property of the title TextBlock to “Hello “ + the Text property of the TextBox username:

    image

    We now have all the code necessary for a Hello World application.  We have two choices when it comes to deploying and running the application. We can either deploy to an actual device itself or use the built‑in phone emulator:

    image

    Because the phone emulator is actually the phone operating system running in a virtual machine, we’ll get the same experience developing in the emulator as on the device. For this sample, we’ll just press F5 to start the application with debugging using the emulator.  Once the phone operating system loads, the emulator will run the new “Hello world” application exactly as it would on the device:

    image

    Notice that we can change several settings of the emulator experience with the emulator toolbar – which is a floating toolbar on the top right.  This includes the ability to re-size/zoom the emulator and two rotate buttons.  Zoom lets us zoom into even the smallest detail of the application:

    image

    The orientation buttons allow us easily see what the application looks like in landscape mode (orientation change support is just built into the default template):

    image

    Note that the emulator can be reused across F5 debug sessions – that means that we don’t have to start the emulator for every deployment. We’ve added a dialog that will help you from accidentally shutting down the emulator if you want to reuse it.  Launching an application on an already running emulator should only take ~3 seconds to deploy and run.

    Within our Hello World application we’ll click the “username” textbox to give it focus.  This will cause the software input panel (SIP) to open up automatically.  We can either type a message or – since we are using the emulator – just type in text.  Note that the emulator works with Windows 7 multi-touch so, if you have a touchscreen, you can see how interaction will feel on a device just by pressing the screen.

    image

    We’ll enter “MIX 10” in the textbox and then click the button – this will cause the title to update to be “Hello MIX 10”:

    image

    We provide the same Visual Studio experience when developing for the phone as other .NET applications. This means that we can set a breakpoint within the button event handler, press the button again and have it break within the debugger:

    image

    Building a “Twitter” Windows Phone 7 Application using Silverlight

     

    Rather than just stop with “Hello World” let’s keep going and evolve it to be a basic Twitter client application.

    We’ll return to the design surface and add a ListBox, using the snaplines within the designer to fit it to the device screen and make the best use of phone screen real estate.  We’ll also rename the Button “Lookup”:

    image

    We’ll then return to the Button event handler in Main.xaml.cs, and remove the original “Hello World” line of code and take advantage of the WebClient networking class to asynchronously download a Twitter feed. This takes three lines of code in total: (1) declaring and creating the WebClient, (2) attaching an event handler and then (3) calling the asynchronous DownloadStringAsync method.

    In the DownloadStringAsync call, we’ll pass a Twitter Uri plus a query string which pulls the text from the “username” TextBox. This feed will pull down the respective user’s most frequent posts in an XML format. When the call completes, the DownloadStringCompleted event is fired and our generated event handler twitter_DownloadStringCompleted will be called:

    image

    The result returned from the Twitter call will come back in an XML based format.  To parse this we’ll use LINQ to XML. LINQ to XML lets us create simple queries for accessing data in an xml feed. To use this library, we’ll first need to add a reference to the assembly (right click on the References folder in the solution explorer and choose “Add Reference):

    image

    We’ll then add a “using System.Xml.Linq” namespace reference at the top of the code-behind file at the top of Main.xaml.cs file:

    image

    We’ll then add a simple helper class called TwitterItem to our project. TwitterItem has three string members – UserName, Message and ImageSource:

    image

    We’ll then implement the twitter_DownloadStringCompleted event handler and use LINQ to XML to parse the returned XML string from Twitter.  What the query is doing is pulling out the three key pieces of information for each Twitter post from the username we passed as the query string. These are the ImageSource for their profile image, the Message of their tweet and their UserName. For each Tweet in the XML, we are creating a new TwitterItem in the IEnumerable<XElement> returned by the Linq query. 

    We then assign the generated TwitterItem sequence to the ListBox’s ItemsSource property:

    image

    We’ll then do one more step to complete the application. In the Main.xaml file, we’ll add an ItemTemplate to the ListBox. For the demo, I used a simple template that uses databinding to show the user’s profile image, their tweet and their username.

    <ListBox Height="521" HorizonalAlignment="Left" Margin="0,131,0,0" Name="listBox1" VerticalAlignment="Top" Width="476">
        <ListBox.ItemTemplate>
            <DataTemplate>
               <StackPanel Orientation="Horizontal" Height="132">
                  <Image Source="{Binding ImageSource}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>
                  <StackPanel Width="370">
                     <TextBlock Text="{Binding UserName}" Foreground="#FFC8AB14" FontSize="28" />
                     <TextBlock Text="{Binding Message}" TextWrapping="Wrap" FontSize="24" />
                  </StackPanel>
               </StackPanel>
            </DataTemplate>
         </ListBox.ItemTemplate>
    </ListBox>

    Now, pressing F5 again, we are able to reuse the emulator and re-run the application. Once the application has launched, we can type in a Twitter username and press the  Button to see the results. Try my Twitter user name (scottgu) and you’ll get back a result of TwitterItems in the Listbox:

    image

    Try using the mouse (or if you have a touchscreen device your finger) to scroll the items in the Listbox – you should find that they move very fast within the emulator.  This is because the emulator is hardware accelerated – and so gives you the same fast performance that you get on the actual phone hardware.

    Summary

    Silverlight and the VS 2010 Tools for Windows Phone (and the corresponding Expression Blend Tools for Windows Phone) make building Windows Phone applications both really easy and fun. 

    At MIX this week a number of great partners (including Netflix, FourSquare, Seesmic, Shazaam, Major League Soccer, Graphic.ly, Associated Press, Jackson Fish and more) showed off some killer application prototypes they’ve built over the last few weeks.  You can watch my full day 1 keynote to see them in action. I think they start to show some of the promise and potential of using Silverlight with Windows Phone 7.  I’ll be doing more blog posts in the weeks and months ahead that cover that more.

    DevTeach 2010 Recap

    DevTeach is finally winding down and my sessions are all done. It’s been a great conference, as always. I have been speaking at DevTeach since the second year and it’s always a great time chatting with Canadians about software development. This year I had the pleasure of kicking off the conference on Tuesday morning with the Keynote. I did a Lap around Visual Studio 2010 and I showed fun IDE features and extensibility, showed off a couple of my favorite language enhancements, new Entity Framework 4 & WCF Data Services, new WPF designer and data binding, and Silverlight and SharePoint 2010 tools. It was fun and I think people were pumped.

    Here’s some good links to check out for VS2010:

    Right after the Keynote I had a session that I’ve spoken about many times before (always a crowd pleaser) on VB10 / C#4 language features which are covered in these walkthroughs, articles and videos, on MSDN:

    I also did an off-the-cuff talk yesterday with Jon Aneja at lunch on using Open XML and XML Literals in VB to manipulate Office document formats.

    My last session was today on Building Office Productivity Solutions with Visual Studio 2010 and according to the evals it went well just like my language talk. We created an OBA for good old Northwind Traders, bringing them into the 21st century. ;-)   I showed the new features of VS2010 that makes Office development easier focusing on RAD data binding (including WPF) and designers, ribbon and the other available designers, as well as SharePoint 2010 tools around workflow and visual web parts.

    My main goal was to provide a real-world scenario and architecture but keep the demo code manageable and simple while also introducing folks to all the RAD designers available. This way you can take apart the sample easily and reuse just the pieces you need. Check out the code and all the articles here: http://code.msdn.microsoft.com/OBANorthwind and check out the VSTO Developer Center for more awesome resources: http://msdn.com/vsto

    Some of the new features that make Office development and deployment easier are covered in these walkthroughs:

    Here are some pictures from the conference which was held at a really nice Microsoft facility in Mississauga

    Loading XAML Workflows in WF4

    Most of the time I used compiled workflows in Windows Workflow Foundation 4. Its nice and easy, you design the workflow, compile it and at runtime there is a .NET type you use to create and run workflows. The main drawback is that this approach isn’t very flexible, sometimes you want to be able to change your workflow definition at runtime or store it in a database so recompiling isn’t an option.

    Fortunately we can also load a workflow from the XAML file itself and execute the resulting workflow activity. This is done using the ActivityXamlServices class that will let us load the XAML file and return an activity, to be exact it returns a DynamicActivity as a wrapper around your definition.

    The simplest option is just to call Load() passing in the file name like this:

    Activity workflow = ActivityXamlServices.Load("YourWorkflow.xaml");

     

    If you are using activities, or other types, from the local assembly this is going to fail though and you need a slightly more verbose way of doing thing like this:

    var settings = new XamlXmlReaderSettings()
    {
        LocalAssembly = typeof(SendForManualApproval).Assembly
    };
    var reader = new XamlXmlReader("YourWorkflow.xaml", settings);
    Activity workflow = ActivityXamlServices.Load(reader);

     

    We need to use the XamlXmlReaderSettings to indicate what the local assembly reference in the XAML is.

    Beta of VS Team Explorer with Cross Platform Support

    The Teamprise products have been very popular with TFS customers who were developing applications across Microsoft and non-Microsoft platforms.  Often customers want to standardize on a single enterprise-wide solution for Application Lifecycle Management because of the cost savings and increased transparency this provides. The Teamprise technology is key in enabling cross platform TFS access.

    Since welcoming the Teamprise technology and the development team into Microsoft, we’ve been hard at work introducing the essential features of TFS 2010 and working towards a high quality release. 

    Today we are announcing a broadly available beta of Microsoft Visual Studio Team Explorer 2010.  This release includes the Team Foundation Server Plugin for Eclipse as well as the Team Foundation Server Cross Platform Command Line Client.  It works on Windows, Mac, Linux, and multiple flavors of UNIX, providing access to the same source control, work item tracking, build automation, and reporting features that Visual Studio customers have benefitted from.

    Below, you can see a TFS user story work item in Eclipse.  The story’s implementation is described by a set of child tasks that are linked to that story.  It also shows the Pending Changes view with two source files checked out, the Team Explorer view with a set of work item queries organized into folders and the Eclipse import wizard connecting to TFS to import Java source into the Package Explorer. 

    You can download the beta of Microsoft Visual Studio Team Explorer 2010 here, and as always you can provide feedback through the Microsoft Connect site.

    Namaste!

    WordPress Themes Hosted Exchange , Hosted CRM. Hosted Sharepoint Online backup dedikerad server