Category: Okategoriserade

How to change the SQL Replication Agent History Cleanup Job

How to change the SQL Replication Agent History Cleanup Job

Chris Skorlinski
Microsoft SQL Server Escalation Services

By default the SQL Replication Agent History cleanup job runs every 10 minutes and deletes any historical data older the 48 hours.  If you’re only running SQL Server Replication Agent a few times each day, you can reduce the frequency of this cleanup job and increase the retention period for historical data without impacting SQL Server Replication performance.  The additional data may be helpful with tracking down subscribers with slow synchronization times.

To adjust the SQL Replication Agent History cleanup job:

1) Right-click on the ‘Agent history clean up: distribution’ cleanup Job in SQL Server Agent and select Properties.

image

2) On the Schedules page, adjust the Job run frequency as needed.  For example, if you only synchronize your subscribers once a day, you can set the cleanup to also run once a day.

3) On the Steps page, click Edit to bring up the TSQL command.  You can increase the retention parameter to keep > 48 hours for Replication topologies which synchronize infrequently.  Don’t set this to high or so much historical data will be stored the distribution database performance is impacted.  If you need longer then say 1 week of data, consider moving the history data to an archived database.

 EXEC dbo.sp_MShistory_cleanup @history_retention = 48

The following posting below contains detailed information on the Merge session history tables along with scripts to pull out long running subscribers.

Windows Phone 7 Design Resources – UI Guide and Design Templates

With the Windows Phone Developer Tools in Beta and Windows Phone 7 in ,now is the time for you to build Windows Phone 7 apps in earnest. We have refreshed our developer documentation to help you build those apps, and we have two, new design-focused documents to help you make them look beautiful.

First up, the UI Design and Interaction Guide for Windows Phone 7 v2.0 has been updated from the ground up for beta. With additional information and a new layout we hope you will find more readable, this guide provides detailed information about UI elements and controls, UI system behaviors, and the interaction model for the touch interface based on the design system internally named Metro. Designers and developers should read this guide to learn about the dos and don’ts of UI implementations for their Windows Phone apps. We’ve made it easier to find specific guidance by putting it in bold in the right-hand column of each page.

Programming the Task Bar in Windows 7 with WPF 4 Article Series

Last week we published an article by VB MVP Alessandro Del Sole on how to utilize a cool Windows 7 Task Bar feature from WPF. Well this week we published another one on Jump Lists and Ale has promised to deliver even more! So yesterday we added a dedicated page to the Visual Basic Developer Center that has a list of articles, samples and resources for programming in WPF and Windows 7.

Programming the Task Bar in Windows 7 with WPF 4, Part One – Thumbnail ButtonsProgramming Windows 7 with WPF 4

Right now we have these articles for you to read, but check this page for more coming soon.

Programming the Task Bar in Windows 7 with WPF 4, Part One – Thumbnail Buttons
Learn how to create interactive thumbnail buttons for your applications that appear on the Windows 7 taskbar using Windows Presentation Foundation.

Programming the Task Bar in Windows 7 with WPF 4, Part Two – Jump Lists
Learn how to program the the Windows 7 Jump List which provides an enhanced user experience offering easy access to common tasks, recent files and custom items related to your applications.

Recap: TechEd 2010 in New Orleans – We’re Jazzed Ya’ll Were Here!

Wow! What a week! I remember the first time I saw a TechEd backpack was back in 2003, where the words “New Orleans” caught my eye. And after 7 years of waiting, my career-long dream came true of attending a Microsoft conference back home.

Earlier this month, TechEd returned to New Orleans for the first time since Hurricane Katrina, bringing 10,500 attendees to the area. And now considering the oil disaster in the gulf (I must admit I agree with The Daily Show that something is trying to kill N.O.), there was no better time for an economic boost for the city. TechEd even caught the attention of the major local newspaper (The Times-Picayune), describing cloud computing and the technical in-depth training TechEd provided. But Visual Studio 201? Opps! =D

The best part of TechEd for me was being a local among the locals. I’ve said for years that “Community is walking among the people”, but having this sense of Community^2 was incredible. I felt like I’ve known local attendees all my life, and for non-locals, I found myself with every conversation playing tour guide, making sure they had the most enjoyable TechEd experience possible. Fortunately, a local told me about http://www.nomenu.com/ which was a lifesaver in giving people French Quarter restaurant recommendations.

Highlights

Lowlights

  • N.O. was under a heat wave advisory for that week. Heat index was between 110-115(!) most days.
  • On Tuesday, there was a city-wide Internet outage for nearly 30 minutes. I never heard what caused outage.
  • The convention center food wasn’t quite Cajun. “Cajun meatloaf” just isn’t right. But, I said it was to encourage folks to support local merchants by eating at local shops across the street. =D
  • The effects of the Oil Spill were readily apparent. Just a few blocks away from TechEd was the annual Oyster Festival, where locals held a jazz funeral. Additionally, on that Thursday, a 134-year old Oyster bar closed .

GeekGive.org Habitat build

Last year at TechEd, MVP Steve Andrews, MVP Mark Rosenberg, INETA members and I chatted about what we could do to help New Orleans. We came up with a concept similar to GiveCamp, but instead of donating code, we’ll donate volunteer hours. Driven by Steve Andrews, he created GeekGive.org for conference attendees to volunteer their time at a local charity before the conference starts.

Demos not to miss next week at NAB: 3D video in Silverlight! 1080p H.264 running on a Netbook!

Yesterday we announced our news for NAB next week in Las Vegas. Today we wanted to point out some other cool experiences to check out in Las Vegas.   First we are showing the industry’s most exciting demo of live 3D HD streaming using IIS Smooth Streaming and Silverlight. Content is coming from Germany from TVN, encoded by an Inlet encoder and then delivered via Level 3.

There will be two technology previews shown. The first one will use the Silverlight player to decode the 3D content and dynamically apply anaglyph (red-cyan) transformations to the video. The video will play back on a conventional display using red-cyan glasses.   The 2nd demo will use Silverlight to play the video without transformation and output to a Panasonic 3D plasma display. THX Media Director was instrumental in making the 2nd demo possible. Here is a diagram of the demo flow:

Automatic Properties, Collection Initializers, and Implicit Line Continuation support with VB 2010

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

This is the eighteenth in a series of blog posts I’m doing on the upcoming VS 2010 and .NET 4 release.

A few days ago I blogged about two new language features coming with C# 4.0: optional parameters and named arguments

Today I’m going to post about a few of my favorite new features being added to VB with VS 2010: Auto-Implemented Properties, Collection Initializers, and Implicit Line Continuation support.

Auto-Implemented Properties

Prior to VB 2010, implementing properties within a class using VB required you to explicitly declare the property as well as implement a backing field variable to store its value. 

For example, the code below demonstrates how to implement a “Person” class using VB 2008 that exposes two public properties – “Name” and “Age”:

image 

While explicitly declaring properties like above provides maximum flexibility, I’ve always found writing this type of boiler-plate get/set code tedious when you are simply storing/retrieving the value from a field.  You can use VS code snippets to help automate the generation of it – but it still generates a lot of code that feels redundant.  C# 2008 introduced a cool new feature called automatic properties that helps cut down the code quite a bit for the common case where properties are simply backed by a field.  VB 2010 also now supports this same feature. 

Using the auto-implemented properties feature of VB 2010 we can now implement our Person class using just the code below:

image

When you declare an auto-implemented property, the VB compiler automatically creates a private field to store the property value as well as generates the associated Get/Set methods for you.  As you can see above – the code is much more concise and easier to read.

The syntax supports optionally initializing the properties with default values as well if you want to:

image

You can learn more about VB 2010’s automatic property support from this MSDN page.

Collection Initializers

VB 2010 also now supports using collection initializers to easily create a collection and populate it with an initial set of values.  You identify a collection initializer by declaring a collection variable and then use the From keyword followed by braces { } that contain the list of initial values to add to the collection. 

Below is a code example where I am using the new collection initializer feature to populate a “Friends” list of Person objects with two people, and then bind it to a GridView control to display on a page:

image

You can learn more about VB 2010’s collection initializer support from this MSDN page.

Implicit Line Continuation Support

Traditionally, when a statement in VB has been split up across multiple lines, you had to use a line-continuation underscore character (_) to indicate that the statement wasn’t complete. 

For example, with VB 2008 the below LINQ query needs to append a “_” at the end of each line to indicate that the query is not complete yet:

image

The VB 2010 compiler and code editor now adds support for what is called “implicit line continuation support” – which means that it is smarter about auto-detecting line continuation scenarios, and as a result no longer needs you to explicitly indicate that the statement continues in many, many scenarios.  This means that with VB 2010 we can now write the above code with no “_” at all:

image

The implicit line continuation feature also works well when editing XML Literals within VB (which is pretty cool).

You can learn more about VB 2010’s Implicit Line Continuation support and many of the scenarios it supports from this MSDN page (scroll down to the “Implicit Line Continuation” section to find details).

Summary

The above three VB language features are but a few of the new language and code editor features coming with VB 2010.  Visit this site to learn more about some of the other VB language features coming with the release. 

Also subscribe to the VB team’s blog to learn more and stay up-to-date with the posts they the team regularly publishes.

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.

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