Justin Toth's Blog

Justin is a web developer living in Maryland

301 Permanent Redirects in ASP.NET 3.5 & 4.0

clock February 15, 2010 23:23 by author Justin Toth

I've been going through an SEO phase recently and part of that was renaming the aspx files of my ASP.NET 3.5 site to reflect the keywords and phrases i was trying to target. For example, a page called Services.aspx that might target web development services would be renamed Web-Development-Services.aspx. I noticed after renaming the files that I was getting errors because the search engines still had my old page names cached and these pages no longer existed.

To stop the bleeding, I had the customErrors node in my web.config redirect to my home page (this is not a solution!) Next I recreated the old pages (such as Services.aspx) and left them empty. Then in the code-behind of each I added some code:

 

Response.Status = "301 Moved Permanently";

Response.AddHeader("Location", "http://mydomain.com/Web-Development-Services.aspx");

 

What does this do? When someone requests the old outdated url, it sends a 301 permanent redirect to the new url, which lets the search engine know to use the new page.

In .NET 4.0, there will be an even simpler way to do this:

 

Response.RedirectPermanent("~/Web-Development-Services.aspx");

 

Using one of these 301 permanent redirects methods you can easily keep users and search engines up to date on the structure of your site, even if you've renamed all of the pages for SEO purposes! 



Clean up your JavaScript Code with Dojo

clock December 19, 2009 19:39 by author Justin Toth

You may have heard of Dojo, the javascript toolkit found at http://www.dojotoolkit.org/. The difference between it and its competitors such as jQuery and Ext JS is that it's much more than a toolkit, it's a full-fledged javascript framework. It provides things such as object-oriented programming (who would've thought you'd ever be able to have class inheritance in javascript?!), template-based widgets (you can dynamically create widgets in javascript that have html templates rather than having to dynamically create the tr's and td's with DOM manipulation), and basic utility functionality.

I've been using the more complex features of dojo, such as OO and template-based widgets, for some years but I never bothered with the basic utility functionality until today. It's pretty cool what dojo lets you do and it makes me sad that I was writing manual javascript code for years to do the same things. Here are a few of the cooler things that dojo lets you do:

1. Finding and looping through DOM elements

dojo.forEach(
                dojo.query("#myDiv img"),
                function(element) {
                    dojo.attr(element, { src: "_images/test.png" });
                }
            );

You can see the use of 3 dojo functions here: dojo.forEach, dojo.query, and dojo.attr. This will loop through all img elements that are children of the element with id "myDiv" and set the src of each image. Dojo.query is very powerful and can let you easily select the element(s) that you want from the page or from a specific parent node.

2. Creating DOM elements

var imgArrow = dojo.create("img", { src: "_images/arrow.png", title: "my arrow!" }, divContainer);

This code creates an image, sets the src and title of it, and appends it to a div, all in 1 line of code!

3. Clearing DOM elements

 dojo.empty(divContainer);

Dojo.empty clears all child elements of the element inputted, no more grabbing all child elements, looping through them, and doing childNode.parentNode.removeChild(childNode).

I've barely scratched the surface of what you can do with dojo but you can go a long way with just these 3 concepts...



Developing Facebook Applications with ASP.NET MVC

clock July 26, 2009 14:00 by author Justin Toth

As Facebook continues to grow at a rapid pace, more and more businesses have been signing on developers to build custom Facebook applications using Facebook's API's so that they can gain exposure to the Facebook masses and the extraordinary amount of personal data that those users have stored within Facebook.

I recently was asked to build a Facebook application for a project. Naturally, I wanted to find a nice solution that would work with my technology set, mainly ASP.NET, not Facebook's standard language: PHP. I even considered building the app using Silverlight, but decided against it since Silverlight is still so new and hasn't been installed yet by so many users. Since we're in the .NET 3.5 era, I decided to go with ASP.NET MVC rather than the standard web forms version of ASP.NET.

The first thing to do is to find a .NET Facebook framework. Like most people, when I first started searching around, I found two choices: Facebook.NET and the Facebook Developer Toolkit.

The Facebook Developer Toolkit is probably the more popular of the two but it has some shortcomings. From my reading, I got the overwhelming impression that the code base was poorly written by the creator, Clarity Consulting. Furthermore, there is no built-in support for ASP.NET MVC so you have to figure out how to make them mesh yourself. Lastly, many of the methods aren't up to date to match the Facebook API methods so you're on your own to update them manually. The Facebook API's change frequently so it's very hard for a .NET Facebook Famework to keep up with those changes, and the FDT doesn't seem to do too good a job of that.

Facebook.NET was written by a well-respected MSFT employee, Nikhil Kothari, and thus, the code base is nice and clean. It provides for much more flexibility than the FDT, hence it'd be easier to make it work with ASP.NET MVC. However, Nikhil seems to have ditched the project, so it hasn't been updated in a couple of years. That means that its methods no longer match the Facebook API methods.

I wasn't satisfied with either of these solutions so I kept looking and was extremely happy when I found a new project called the .NET Facebook API Client, which is still in Alpha. This project is specifically designed for ASP.NET MVC and provides a Visual Studio 2008 template that sets everything up for you, such as Facebook authentication and using Facebook Connect. The code is nice and clean and is provided to you so that if you run into bugs (since it's an Alpha release), you can modify the code yourself to get it working. Here's the best part - they built a tool that will automatically update the methods when the Facebook API methods change, so it will always match the Facebook API, something that is sorely missing from the big two that I mentioned above.

With the .NET Facebook API Client, I was able to build my first ASP.NET MVC Facebook application without running into too many issues. You can find the link to the app below, which has you enter in your email address, mobile #, and carrier, and then lets you pick your favorite sports teams. It will send you a text message at the end of each game for the teams you picked with the final scores.

http://apps.facebook.com/sportsalert/



Silverlight 3 Released!

clock July 10, 2009 14:18 by author Justin Toth

Just as promised, Silverlight 3 has been released, actually 1 day earlier than the expected July 10th date. You can get the latest tools here.

For those of us who have been already playing with Silverlight 3 beta, there are some breaking changes. The most obvious one is that the System.Web.Silverlight assembly has been removed, meaning that the ASP.NET Silverlight control that we were using won't work anymore. Alternately, you need to set up your Silverlight app using an object and an iframe tag. The object tag shouldn't be new to anyone and was always an alternative to using the Silverlight control. The iframe will be used to handle browser history, which comes along with the new SL3 Navigation features.

To view a full list of the changes, go here:

http://docs.google.com/View?id=dnkk749_0czvc86gx



Sorting, paging, and filtering with Linq to SQL

clock June 19, 2009 22:56 by author Justin Toth

We get a requirement from a client where we need to make a grid. It starts out as a simple grid, but then the client calls for sorting, then paging, then in-grid filtering of the results. We've all had to code up a solution for this in the past... We didn't want to load all of the results into C# and then do the sorting, paging, and filtering, as this would be too much data to store in memory. So instead we write a sproc that handles this for us, like so:

if exists (select * from syscomments where id = object_id ('dbo.User_GetUsers'))
begin
drop proc dbo.User_GetUsers
end

go

create proc dbo.User_GetUsers
@FirstName varchar(50),
@LastName varchar(50),
@LoginName varchar(50),
@SortColumn varchar(50),
@SortDirection varchar(50),
@PageSize int,
@PageNumber int,
@TotalRecordCount int out
as

--create temp table to store results.
declare @Users table
(
 RowNum int identity(1,1),
 UserID int,
 FirstName varchar(50),
 LastName varchar(50),
 LoginName varchar(50)
)

--insert into temp table the sorted and filtered results (before paging.)
insert into @Users
(
 UserID,
 FirstName,
 LastName,
 LoginName
)
select
 UserID,
 FirstName,
 LastName,
 LoginName
from
dbo.User (nolock)
--search filters
where
(len(@FirstName) = 0 or upper(FirstName) like '%' + upper(@FirstName) + '%')
and (len(@LastName) = 0 or upper(LastName) like '%' + upper(@LastName) + '%')
and (len(@LoginName) = 0 or upper(LoginName) like '%' + upper(@LoginName) + '%')
--sorting
order by
case when @SortColumn = 'FirstName' and @SortDirection = 'ASC' then FirstName end asc,
case when @SortColumn = 'FirstName' and @SortDirection = 'DESC' then FirstName end desc,
case when @SortColumn = 'LastName' and @SortDirection = 'ASC' then LastName end asc,
case when @SortColumn = 'LastName' and @SortDirection = 'DESC' then LastName end desc,
case when @SortColumn = 'LoginName' and @SortDirection = 'ASC' then LoginName end asc,
case when @SortColumn = 'LoginName' and @SortDirection = 'DESC' then LoginName end desc

--get total record count.
set @TotalRecordCount = (select count(1) from @Users)

--figure out where to page.
declare @StartRowNum int
set @StartRowNum = ((@PageNumber - 1) * @PageSize) + 1
declare @EndRowNum int
set @EndRowNum = @StartRowNum + @PageSize

--get paged results from temp table.
select *
from @Users
where RowNum >= @StartRowNum
and RowNum < @EndRowNum
order by RowNum asc

go

This code worked great in the past, but we're in the 3.5 era and the 4.0 era is fast approaching, we can do better!! In comes Linq to SQL to the rescue.

First we need to do a little prep work. We're going to create a UserSearch object, which will store our search parameters. Next, we're going to create a UserView object, which will declare what we want to return for each user. Do we need to do this? No, however it's a good practice to only return what you need, especially since this is an ajax grid (did I mention that??) and we're going to convert the results to JSON to pass to it. Lastly, we need to create an extension method that will help us with sorting later on. It is beyond the scope of the article how this extension method works (in other words I don't know how it works yet!)

public class UserSearch
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string LoginName { get; set; }
    }

public class UserView
    {
        public int UserID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string LoginName { get; set; }
        public int TotalRecordCount { get; set; } 
    }

 public static class DynamicOrderBy
    {
        public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source,
            string sortColumn, string sortDirection) where TEntity : class
        {
            string command = sortDirection == "ASC" ? "OrderBy" : "OrderByDescending";
            var type = typeof(TEntity);
            var property = type.GetProperty(sortColumn);
            var parameter = Expression.Parameter(type, "p");
            var propertyAccess = Expression.MakeMemberAccess(parameter, property);
            var orderByExpression = Expression.Lambda(propertyAccess, parameter);
            var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType },
                                   source.Expression, Expression.Quote(orderByExpression));
            return source.Provider.CreateQuery<TEntity>(resultExpression);
        }
    }

Now that our prep work is done, it's time to write our method, which will handle sorting, paging, and filtering, and return the results as JSON for use in our ajax grid.

public string GetPageJSON(string sortColumn, string sortDirection, int pageNumber, int pageSize, UserSearch search)
        {
            var query = from u in db.User
                        select new UserView
                        {
                            UserID = u.UserID,
                            FirstName = u.FirstName,
                            LastName = u.LastName,
                            LoginName = u.LoginName
                        };
            //searching.
            if (search.FirstName.Length > 0) query = query.Where(u => u.FirstName.Contains(search.FirstName));
            if (search.LastName.Length > 0) query = query.Where(u => u.LastName.Contains(search.LastName));
            if (search.LoginName.Length > 0) query = query.Where(u => u.LoginName.Contains(search.LoginName));
            //sorting.
            query = query.OrderBy(sortColumn, sortDirection);
            //get total record count.
            int totalRecordCount = query.Count();
            //paging.
            query = query.Skip((pageNumber - 1) * pageSize).Take(pageSize);
            //set total record count.
            var list = query.ToList();
            if (list.Count > 0)
            {
                list[0].TotalRecordCount = totalRecordCount;
            }
            //return json.
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(list);
        }

Make sure you add a reference to System.Web.Extensions and then you can hit control + . on JavaScriptSerializer to get its namespace (System.Web.Script.Serialization). As you can see, we first declare what we want to return from our user table. Next we do our filtering with some simple where conditions. After that, we sort using our custom extension method. Next we get the total number of records so that we can let our pager know, then we get one page of data, using the nifty Linq to SQL Skip and Take methods. We then call .ToList() on our query, which for the first time, calls the database, runs the query, and returns the results. We then set our TotalRecordCount in our results and lastly serialize our results into JSON.

So that's it! Once the JSON has been passed into the javascript using whatever method you like, maybe a web service or ASP.NET Ajax Extensions pagemethods, you can then say:

var results = eval(json);

The results object will then contain the List of business objects, pretty nifty huh??



First Impressions of Visual Studio 2010 Beta 1

clock June 15, 2009 11:57 by author Justin Toth

I'm going to keep this short and sweet, here were my first impressions using Visual Studio 2010 Beta 1...

The Good:

In Silverlight 3, when using the UriMapper to rewrite navigation urls or styles on controls that require a reference (DataGrid, DatePicker, etc..) in App.xaml, the Visual Studio xaml designer still worked. 2008 had bugs that broke the designer views in these cases.

The UI seemed nice and clean, certainly an improvement over 2008.

The Bad:

When i first installed it then tried to run it, it crashed. Then after rebooting, it loaded my solution fine. First time building caused it to crash again.

About 50% of the times i built my project, it would say build failed, but wouldn't give any message of why in the output window. Without changing any code if I built again, it would work.

Every few minutes it would freeze and I'd have to end task.

Within a couple minutes of use it was taking up over 500mb of RAM. That's fine on my 4gb box but VM users beware.

After uninstalling it, no .NET programs worked anymore. They would give .NET 4 errors about missing dlls, even though they weren't apps built using .NET 4. After uninstalling all of the .NET 4 components and repairing the .NET 2 and .NET 3 installs, the .NET apps started working again. It also kept the ASP.NET State Service pointed to the .NET 4 directory, so I had to use sc delete and sc create to reset it to the .NET 2 directory.

Conclusion:

I wasn't able to get too in-depth into VS2010 due to how unstable the product was, but the improved Silverlight designer support was a plus. Needless to say, I won't be touching it again until a more stable build is released...



To have one's cake and eat it too...

clock June 11, 2009 22:42 by author Justin Toth

The past month or two I've been struggling with an architectural issue and haven't been able to find a good answer. The fact of the matter is, Silverlight, WCF, and the Entity Framework don't play nice together. Here's why...

You start out by adding your Entity Model to your WCF app or an assembly that WCF references. You expose your EF business objects from your WCF methods and consume them from your Silverlight app. The problem is that this will generate the EF business objects under each service proxy namespace rather than in one central namespace. Here's an example of this case:

Service Proxy Namespace Hell:

Let's say you have 2 ADO.NET Data Services - UserService and GeographicService.

There's an Add User form that has a combobox with all of the states. You call GeographicServiceProxy.GetStates(), which returns List<GeographicServiceProxy.State>. You bind the combobox to this list.

When Save is pressed, you construct a UserServiceProxy.User object which you'll then send to UserServiceProxy.Add(user). The problem is that you now can't set the UserServiceProxy.User.State property, as your dropdown contains GeographicServiceProxy.State objects. You'll get a build error if you try to assign directly between them and you end up having to manually set each property from one to the other, which doesn't work when we're talking about an entire application. Basically, all of your business objects are duplicated in the namespace of each service proxy and you can't directly assign between them due to the different namespaces, aka Service Proxy Namespace Hell.

The solution in a normal client environment (not Silverlight) would be to reference the project containing the business objects, then when adding the Service References, so long as you have "Reuse types in all referenced assemblies" selected, it won't generate the methods and will correctly have the business object types be of your referenced assembly types, such as MyNamespace.BusinessObjects.MyBusinessObject, rather than within the individual service proxy namespaces, such as MyNameSpace.Silverlight.Service1Proxy.MyBusinessObject.

Silverlight half-baked referencing:

However since Silverlight doesn't let you reference a non-Silverlight assembly, this doesn't fly. Let's say you try to get around this by creating a Silverlight class library and adding a link to the Entity Model (edmx) file. The Silverlight class library won't build unless you manually edit the project file and add references to .NET assemblies such as System and System.Data. Now you reference this Silverlight class library within your Silverlight app and you end up with build errors because you now have clashing Silverlight and non-Silverlight assemblies, such as .NET's "System" vs. Silverlight's "system". Dead end...

The alternative, and the method I'm currently using, is to create custom business objects that match the EF business objects. You can then expose these from your WCF service methods. Let's say you wanted to call a WCF Add(entity) method. You would pass in a custom business object, convert it property by property to an EF business object, then save it. If you wanted to call a WCF Get() method, you would use linq to get the EF business object, then property by property you'd convert it to a custom business object to return from the method. As you can see, this results in a lot of extra code being written and you now have opened up your WCF/EF code to having to deal with objects property by property, losing some of the beauty. Now that your WCF service methods are exposing custom business objects, you need your Silverlight application to reference the custom business objects. What you have to do is create a new Silverlight class library project, doing add existing items, selecting all of your business business object classes, and doing add as link (notice the down arrow next to the Add button.) Now you can reference this new Silverlight class library within your Silverlight application and add your service references, which will generate the proxy business objects within their correct namespace so long as you have set "Reuse types in all referenced assemblies".

Alternatives to WCF:

 So you say, why not try something else besides WCF to get around this issue? Certainly, you could. Let's say you put ADO.NET Data services within your WCF project. You'll still run into the same service proxy namespace issue. You could use RIA services, but then you're demoting your services code to running on an ASP.NET web app that is hosting the Silverlight app. Say goodbye to all remnants of SOA and supporting multiple UIs...

You can't have your cake and eat it too:

 So here's what I want...

1. To use the Entity Framework for data access and ONLY use its generated business objects, not having to write my own duplicate custom business objects.

2. To use WCF or ADO.NET Data Services so that I can support multiple UIs in the future and to be able to expose the Entity Framework entities from the services rather than having to convert between the EF entities and my custom business objects.

3. To use Silverlight for the UI without having my entities split up and duplicated in each generated service proxy namespace.

The key to resolving all of these issues is #3. If MSFT added support for referencing the WCF services project within the Silverlight app, then you could add your service references and they would generate the EF entities in their appropriate namespace. However, sadly, this isn't the case, and we're left with 3 technologies that are great on their own but don't end up playing nice together. I wish the teams for these different products worked closer together, because I can see the beauty in each of these technologies, yet together you end up having to make compromises...



WCF/Silverlight Exception Handling

clock June 10, 2009 16:09 by author Justin Toth

The past couple of days I've been struggling setting up proper exception handling in WCF and Silverlight. In WCF I wanted to handle exceptions in 1 place rather than having to try/catch in every single service method. I was able to accomplish this using behaviors and the IErrorHandler:

Here's the WCF code:

Services/Models/Constants.cs:

public class Constants
    {
        public const string FaultAction = "//ErrorHandler/FaultAction">http://ErrorHandler/FaultAction";
    }

 

Services/Interfaces/ICategoryService.cs: (sample WCF service interface)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using CouponJoe.Schemas;
using CouponJoe.Schemas.Results;

namespace CouponJoe.Services.Interfaces
{
    [ServiceContract]
    public interface ICategoryService
    {
        [OperationContract]
        [FaultContract(typeof(string), Action = Models.Constants.FaultAction)] 
        Category Add(Category category);
        [OperationContract]
        [FaultContract(typeof(string), Action = Models.Constants.FaultAction)] 
        Category Update(Category category);
        [OperationContract]
        [FaultContract(typeof(string), Action = Models.Constants.FaultAction)] 
        DeleteResult Delete(Category category);
        [OperationContract]
        [FaultContract(typeof(string), Action = Models.Constants.FaultAction)] 
        Category Get(int categoryId);
        [OperationContract]
        [FaultContract(typeof(string), Action = Models.Constants.FaultAction)] 
        Category GetByName(string categoryName);
        [OperationContract]
        [FaultContract(typeof(string), Action = Models.Constants.FaultAction)] 
        List<Category> Search();
    }
}

Services/Behaviors/ErrorHandler.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using CouponJoe.Services.Models;

namespace CouponJoe.Services.Behaviors
{
    public class ErrorHandler : ErrorHandlerBehavior, IErrorHandler, IServiceBehavior
    {

        public bool HandleError(Exception error)
        {
            //TODO: log exception.
            return true;
        }
        
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            string errorMessage = String.Empty;
            if (error.InnerException == null)
            {
                errorMessage = String.Format("{0}: {1}", error.GetType().FullName, error.Message);
               
            }
            else
            {
                errorMessage = String.Format("{0}: {1}", error.InnerException.GetType().FullName, error.InnerException.Message);
            }
            FaultException<string> faultException = new FaultException<string>(errorMessage, new FaultReason(errorMessage));
            MessageFault messageFault = faultException.CreateMessageFault();
            fault = Message.CreateMessage(version, messageFault, Models.Constants.FaultAction);
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            foreach(ChannelDispatcher channDisp in serviceHostBase.ChannelDispatchers)
            {
                channDisp.ErrorHandlers.Add(this);
            }
        }

        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> serviceEndPoints, BindingParameterCollection bindingParameters)
        {
            return;
        }

        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            //do nothing.
        }

    }
}

Services/Behaviors/ErrorHandlerBehavior.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Configuration;

namespace CouponJoe.Services.Behaviors
{
    public class ErrorHandlerBehavior : BehaviorExtensionElement
    {
        public override Type BehaviorType
        {
            get
            {
                return typeof(ErrorHandler);
            }
        }

        protected override object CreateBehavior()
        {
            return new ErrorHandler();
        }

    }
}

Services/Behaviors/SilverlightFaultBehavior.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

namespace CouponJoe.Services.Behaviors
{
    public class SilverlightFaultBehavior : BehaviorExtensionElement, IEndpointBehavior
    {

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            SilverlightFaultMessageInspector inspector = new SilverlightFaultMessageInspector();
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);
        }

        public class SilverlightFaultMessageInspector : IDispatchMessageInspector
        {
            public void BeforeSendReply(ref Message reply, object correlationState)
            {
                if (reply.IsFault)
                {
                    HttpResponseMessageProperty property = new HttpResponseMessageProperty();
                    // Here the response code is changed to 200.
                    property.StatusCode = System.Net.HttpStatusCode.OK;
                    reply.Properties[HttpResponseMessageProperty.Name] = property;
                }
            }

            public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
            {
                // Do nothing to the incoming message.
                return null;
            }
        }

        // The following methods are stubs and not relevant.

        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
        }

        public void Validate(ServiceEndpoint endpoint)
        {
        }

        public override System.Type BehaviorType
        {
            get { return typeof(SilverlightFaultBehavior); }
        }

        protected override object CreateBehavior()
        {
            return new SilverlightFaultBehavior();
        }

    }

}

Services/Web.config:


<system.serviceModel>
    <extensions>
      <behaviorExtensions>
        <add name="ExceptionHandlingBehavior"
             type="CouponJoe.Services.Behaviors.ErrorHandlerBehavior, CouponJoe.Services, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
        <add name="SilverlightFaultBehavior"
             type="CouponJoe.Services.Behaviors.SilverlightFaultBehavior, CouponJoe.Services, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
      </behaviorExtensions>
    </extensions>
    <bindings>
      <basicHttpBinding>
        <binding name="basicBinding">
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="CouponJoe.Services.ServiceBehavior" name="CouponJoe.Services.CategoryService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicBinding"
                  behaviorConfiguration="SilverlightFaultEndPointBehavior" contract="CouponJoe.Services.Interfaces.ICategoryService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="SilverlightFaultEndPointBehavior">
          <SilverlightFaultBehavior/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="CouponJoe.Services.ServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
          <ExceptionHandlingBehavior/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

We're doing 2 things here... First, we're adding an Exception Handling behavior into the WCF pipeline (using ErrorHandler.cs and ErrorHandlerBehavior.cs), which will pick up all Exceptions thrown in the WCF services. We can then package them up in FaultExceptions and send them down to the client. You'll see in the web.config how we plugged it in.

For a normal client this would be the end of it, but Silverlight is "special". Silverlight doesn't grab the true exception because when the service faults, it returns a message other than 200 ("OK"). So the second step is plugging in the Silverlight Fault behavior into the WCF pipeline, which modifies the message to still be 200 ("OK") even when an exception was thrown.

So now that we're getting a nice fault exception passed to SL, what do we do with it? If we're using SL2, the answer is "not much". SL2 has half-baked FaultException calsses that aren't much good. However, SL3 has resolved this. Yeah, but SL3 is beta, right? Yes it is, but there's a delivery date of July 10th so you may be able to rationalize upgrading.

After upgrading to SL3, you can then handle your exceptions globally in the code-behind of App.xaml:

private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            //what kind of exception have we caught?
            string errorMessage = String.Empty;
            if (e.ExceptionObject.InnerException != null && e.ExceptionObject.InnerException is FaultException)
            {//wcf exception.
                FaultException exc = e.ExceptionObject.InnerException as FaultException;
                errorMessage = exc.Reason.ToString();
            }
            else
            {//silverlight exception.
                errorMessage = e.ExceptionObject.Message;
                //TODO: log exception.
            }
            //handle exception so app doesn't crash.
            e.Handled = true;
            //show js error.
            Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
            //redirect to error page.
            Navigation.Navigate(Pages.ERROR, errorMessage);
        }

We have accomplished a few things here. You now have global exception handling in both WCF and Silverlight rather than having to add try/catch blocks around everything. You are receiving the true WCF error message from your Silverlight app rather thangeneric communication faults, which can really help debugging, as otherwise you'll most likely have to debug the service while running your Silverlight app in order to figure out what's going on. 

Note: please don't do this in a production app, this is only useful for debugging purposes...



Foreign Keys and Eager Loading in the Entity Framework

clock May 30, 2009 12:47 by author Justin Toth

Let's say that you create 2 database tables, a User table and a Company table. A user can be part of a company so the User table has a CompanyId foreign key. Then you go ahead and create your Entity Framework Model, which recognizes the foreign key and creates the relationship between the business objects. You create a registration form that allows the saving of a user, and you have a Company dropdown on there where the user can pick which company they belong to. When they click save, you want to not only create the User but set up the correct relation between that user and the selected company. If you're new to the Entity Framework, your first attempt will probably look something like this:

using (MyEntities dataContext = new MyEntities())
            {
                User user = new User();
  user.Company = new Company();
  user.Company.CompanyId = 1;//TODO: get selected company id
  dataContext.AddToUser(user);
  dataContext.SaveChanges();
            }

However this won't work, it'll most likely throw an exception about how you need to attach an existing key rather than trying to add a new one. The problem is you're trying to add a user but also are trying to add the company, when the company already exists. The solution is to add a reference to the company rather than a new company object:

using (MyEntities dataContext = new MyEntities())
            {
                User user = new User();
  user.CompanyReference.EntityKey = new EntityKey("MyEntities.Company", "CompanyId", 1);
  dataContext.AddToUser(user);
  dataContext.SaveChanges();
            }

This will correctly add the company reference to the user table.

Now let's say that you have a grid where you want to view a list of all users and which companies they belong to. Again, your first stab might look like this:

using (MyEntities dataContext = new MyEntities())
            {
                return dataContext.User.ToList();
            }

If you view sql profiler while running this, you'll see that it only grabs the record from the User table, it doesn't know to grab the associated Company record as well. To fix this, we use the Include statement to implement "eager loading", which will also load the company object related to the user:

using (MyEntities dataContext = new MyEntities())
            {
                return dataContext.User.Include("Company").ToList();
            }

This will fill the User.Company object and you're good to go...



Silverlight + WCF + Entity Framework

clock May 29, 2009 20:13 by author Justin Toth

For an app I'm building, I set up the following architecture:

 

Front-end:

Silverlight project

nUnit test project

Middle-tier:

WCF Services project

Schemas project

SchemasSL project

DataAccess project

Back-end:

Stored procedures / SQL Server database

 

Pretty standard stuff, however there's one odd ball in that list, the SchemasSL project. What is this for, you ask?? Try adding more than 1 WCF service reference to your Silverlight project and you'll then enter into what I call "WCF Service Proxy Namespace Hell", or WSPNH for short (it'll catch on, just give it a couple years...) Each service proxy will contain a set of your business objects, each inconveniently located in that service proxy's namespace. Try to cast Service1Proxy.BusinessObjectA to Service2Proxy.BusinessObjectA and then make yourself feel comfortable in WSPNH while the invalid cast build errors pop up.

The solution is to add a reference to your schemas in the Silverlight app and then configure your service references to reuse referenced assemblies by right-clicking on them and doing Configure Service Reference. Easy enough... not! When you try to add the Schemas reference to your Silverlight app, you'll get an error message about how you can't reference a non-Silverlight project in your Silverlight project. F#$%!! This is where SchemasSL comes in. This is simply a Silverlight class library that references all the business objects in the standard Schemas project as links. You can do this by adding existing items, selecting the schema classes, then hitting the down arrow next to the add button and doing "Add as Link".

Now that we've added a reference to our Schemas, we can go ahead and do Update Service References and now all our schemas in our Silverlight app conveniently are located in the Schemas namespace rather than being schismed in the separate service proxy namespaces. At this point you acknowledge that you've just done a little hack but everything is working so you can sleep tonight.

We're done here, this article is over...

Oh wait, I did mention the Entity Framework in the title, didn't I??

I decided that it'd be a good learning experience to try using the Entity Framework/Linq to Entities. Basically you can add new item -> ADO.NET Entity Date Model, point to a database, tell it to add all tables, and it'll auto-generate schemas for you as well as data access methods with a few clicks. It does much more than this, but that's what I planned on using. Below you can see what my entities looked like... It seems simple and fast and usually it is, but I had named all my tables with the convention TABLE_NAME and all my columns with the convention column_name, so all the entity schemas were generated in the same fashion, which looked nasty in C#. I ended up rewriting all the table and column names to conform to C# standards, not something everyone can do, but if you're ditching all your sprocs then it makes it easier.

With all this auto-generated Entity Framework model code, I no longer needed my Schemas project, my DataAccess project, or my stored procedures (you will want to keep some sprocs for complex logic probably but I didn't have any.) By the way, if you run profiler when calling these Entity Framework methods, you'll see that it generates not just dynamic sql, but dirty sql (dynamic sql outside of sprocs.) This made me throw up a little in my mouth but then I read a bunch of articles where it seems that the sproc performance benefits that I had always believed were there may not be vs. dynamic sql. This seems to be due to the fact that dynamic sql can figure out the best execution pattern each run vs the default behavior of sprocs to figure it out only when they're created. If you want to use all sprocs with the Entity Framework you can do so, but for me, it seems the benefits (not having to write hundreds of sprocs and getting to smeer dirty sql in DBA's faces) by far outweigh the minuses (arguable performance gains, security enhancements that may or may not be applicable).

I then reworked my WCF services to work with the Entity Framework, an example service below:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using CouponJoe.Services.Models;
using System.Data;

namespace MyNameSpace.Services
{
    public class CategoryService : Interfaces.ICategoryService
    {
        public Category Add(Category category)
        {
            using (CouponEntities dataContext = new CouponEntities())
            {
                //set dates.
                category.CreateDate = DateTime.Now;
                category.ModifiedDate = DateTime.Now;
                //save category.
                dataContext.AddToCategory(category);
                dataContext.SaveChanges();
                //return category.
                return category;
            }
        }

        public Category Update(Category category)
        {
            using (CouponEntities dataContext = new CouponEntities())
            {
                //set date.
                category.ModifiedDate = DateTime.Now;
                //apply changes.
                EntityKey key = dataContext.CreateEntityKey("Category", category);
                object originalCategory;
                if (dataContext.TryGetObjectByKey(key, out originalCategory))
                {
                    dataContext.ApplyPropertyChanges(key.EntitySetName, category);
                }
                //save category.
                dataContext.SaveChanges();
                //return category.
                return category;
            }
        }

        public int Delete(Category category)
        {
            using (CouponEntities dataContext = new CouponEntities())
            {
                //delete category.
                dataContext.Attach(category);
                dataContext.DeleteObject(category);
                int numRowsAffected = dataContext.SaveChanges();
                if (numRowsAffected > 0)
                {//return deleted categoryid.
                    return category.CategoryId;
                }
                else
                {//delete didn't work.
                    return -1;
                }
            }
        }

        public Category Get(int categoryId)
        {
            using (CouponEntities dataContext = new CouponEntities())
            {
                //get category by id.
                IQueryable<Category> categoryQuery =
                    from c in dataContext.Category
                    where c.CategoryId == categoryId
                    select c;
                //return category.
                return categoryQuery.FirstOrDefault();
            }
        }

        public Category GetByName(string categoryName)
        {
            using (CouponEntities dataContext = new CouponEntities())
            {
                //get category by name.
                IQueryable<Category> categoryQuery =
                    from c in dataContext.Category
                    where c.CategoryName == categoryName
                    select c;
                //return category.
                return categoryQuery.FirstOrDefault();
            }
        }

        public List<Category> Search()
        {
            using (CouponEntities dataContext = new CouponEntities())
            {
                //return categorys.
                return dataContext.Category.ToList();
            }
        }

    }
}

You can see some fun stuff going on with data access and linq but that's not why we're here. First thing I did was try out the new WCF service methods by running some nunit test cases that I had written and worked with the old code. I removed the reference to the Schemas project in my test project, added a reference to the Services project, then updated the service references (to get the services to use my new Entity Framework business schemas rather than my old custom schemas). This worked and I got every test case passing. At this point I thought I was money....

The next step was to actually use the new WCF service methods in my Silverlight app... and this is where we hit a brick wall... You want to add a reference to your new entity framework schemas to your Silverlight project. You can't add a reference directly to your WCF services project because it's not a Silverlight project. I tried using the same hack as I did before, linking to the Entity Framework Model file (ModelName.edmx) from my SchemasSL project then referencing this in my Silverlight app. Unfortunately, you'll get hundreds of build errors in your SchemasSL project about missing references, including System.Data. Sadly you can't add a reference to it, as it's not a Silverlight reference!! I almost gave up at this point but decided to give something else a try, updating the SchemasSL.csproj file in notepad, and adding the references directly in there to get around the Visual Studio validation.

Here is what I added to the references block of mine:

<Reference Include="mscorlib, Version=2.0.50727.3053, Culture=neutral, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll</HintPath>
    </Reference>
    <Reference Include="System, Version=2.0.50727.3053, Culture=neutral, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll</HintPath>
    </Reference>
    <Reference Include="System.Core, Version=2.0.50727.3053, Culture=neutral, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>c:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Core.dll</HintPath>
    </Reference>
    <Reference Include="System.Data, Version=2.0.50727.3053, Culture=neutral, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll</HintPath>
    </Reference>
    <Reference Include="System.Data.Entity, Version=2.0.50727.3053, Culture=neutral, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>c:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.Entity.dll</HintPath>
    </Reference>
    <Reference Include="System.Xml, Version=2.0.50727.3053, Culture=neutral, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll</HintPath>
    </Reference>

All of these references were required by the Entity Framework generated model classes, and I had to go through one by one until I finally got the SchemasSL project building. I was burnt out at this point but felt like I had finally gotten where I needed to be, that this was going to work. I referenced the SchemasSL project in my Silverlight project, updated the service references, and voalla, everything worked.. Wait no, that was the happy ending I was hoping for.. Instead, the WCF service proxy classes pooped out (that's the technical term for it), they just didn't generate anything... All of the expected classes for ServiceClients and Async Method calls were just absent from the proxy class. Here's an example proxy class:

 

 namespace MyNameSpace.SL.CarrierServiceProxy {
    using System.Runtime.Serialization;
   
   
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
    [System.Runtime.Serialization.DataContractAttribute(Name="StructuralObject", Namespace="//schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses">http://schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses", IsReference=true)]
    [System.Runtime.Serialization.KnownTypeAttribute(typeof(CouponJoe.SL.CarrierServiceProxy.EntityObject))]
    public partial class StructuralObject {
    }
   
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
    public class EntityObject {
    }
}

If I went into Configure Service Reference, selected Reuse types in specified referenced assemblies, and checked all except my SchemasSL project, and then it generated the proxy class ok, except as expected it created the schemas under the service proxy namespace. Yell  That made it clear that even though I tricked it into allowing my non-Silverlight references in my Silverlight class library, when generating the proxies it must care about that and that's what caused it to fail. Of course it doesn't give any error messages though in the error or output windows.

So that's where I'm at, still no solution to get this working... Seems like a simple thing to want to use Silverlight, WCF, and the Entity Framework. I mean, 1 company designed all 3, didn't it? Shouldn't they play nice with each other? I went through all this pain and still it isn't working, what gives???

UPDATE:

I removed the reference to my SchemasSL silverlight class library in my Silverlight app, regenerated the service references (so that they'd generate correctly), then manually removed the extra schemas classes from each reference. This isn't something I'd want to do every time I update or add a new service reference but I had come so far that I wanted to follow through and see if I could get this working. After cleaning up the service proxy classes, I ended up getting hundreds of build errors in my Silverlight app about how there are conflicting references. This occurs because my SchemasSL silverlight class library has references to "System" (.NET's System project), whereas my Silverlight app has a reference to "system" (Silverlight's subset System project). This was a clear sign that there was nothing left to do but turn around and go back...

I revived my custom Schemas project and modified my WCF services to expose only those custom schemas rather than the Entity Framework schemas. So for example, when calling an Add method, it would convert the custom schema business object to an Entity Framework schema then save it. When calling a get method, it would use linq to get an Entity Framework schema object, then would conver to a custom schema business object to be returned from the method. Then I could go back to my old hack of linking my customer schema classes to SchemasSL and referencing that within my Silverlight app.

This worked but isn't as nice and clean as I was hoping for, as you end up having two sets of business objects, 1 within your custom schema project and 1 within the generated Entity Framework model code. So it seems at least for now you should expose custom schema objects from your WCF methods and leave Silverlight apps ignorant that the Entity Framework exists, but one can dream for improvements on this in the future...



About the author

Justin

Justin is a senior .NET developer who has been working with .NET since 2003. His personal website is located at http://tothsolutions.com.

Sign in