Funkytools.com is Live

by mgordon 28. June 2009 10:18

I’ve been working for months on a Silverlight application for task management that draws from the Getting Things Done philosophy among others.  I’ve created a web site to host the application at http://www.funkytools.com.  If you get the chance and are so inclined, check it out.

Tags: ,

General | Silverlight

Access Role Provider from ASP.Net Ajax and Silverlight

by mgordon 19. June 2009 05:00

In an earlier postI detailed how to access the Membership provider’s services from Silverlight and ASP.Net Ajax.  This is great for logging users into your site, but what if you want to make only certain parts of the application available to these users based on their role in the system at the time they log in or just check the user’s role before allowing them to perform an action? 

I found a great post by Satheesh Babu that describes how to access the Role provider from within the browser. 

Tags:

.Net | ASP.Net | Silverlight

The Best Service Reference Strategy for Silverlight

by mgordon 12. June 2009 06:08

When first learning Silverlight, having often utilized the “Add Web Reference” functionality in Visual Studio in days gone by, I reached for the alluring “Add Service Reference” functionality when adding references to WCF services to my Silverlight projects. I encountered a few problems using this approach and began to search for a better way to reference WCF services.

Project Bloat

The first problem I noticed was the sheer number of files generated by Visual Studio when you add a service reference.  If you’re using source control (and you should be), any modification made to a service reference is going to delete several files and replace them with new ones.  When checking these changes into source control, it can sometimes be confusing trying to figure out how to get your source checked in in a valid state.

Reusing Referenced Assemblies

Second problem I found I was having was that I was often getting errors and warnings when adding or modifying a service reference.  These came in different flavors, but most all complained about the format of the WSDL being received from the service.  With some trial and error, I figured out that the problems were being caused by the default behavior of Visual Studio when adding a reference in respect to reusing types in referenced assemblies. When adding a service reference, the below dialog appears.

AddRef

If you click on the Advanced button, this dialog appears.

Advanced

By default, the “Reuse types in referenced assemblies” checkbox is checked and the “Reuse types in all referenced assemblies” radio button is selected.  If you’re having problems getting client proxies to generate for your services, try clearing the checkbox as this seemed to be the solution for me.

Location, Location, Location

The third problem I’ve had with adding references this way is probably the most important.  With the Add Web Reference I knew and loved, it was a fairly simple matter to modify the generated Reference.cs file to pull the URL for the web service endpoint from a configuration file.  But, when adding a service reference with visual studio, whatever endpoint you specify when adding the reference gets scattered through various of the generated files which makes manual modification extremely difficult.

When I’m working with a Silverlight project, I typically like to have all the services running locally while I’m developing to facilitate debugging and modification of the services which means that my service references need to be pointing to localhost.  Before I deploy, I have to go to each reference and reconfigure it to point to the production server which means that any modified version of my services have to already exist on the server and all this makes deployment a huge headache.  If my shop employed a full set of environments - dev, QA, staging, prod – I’m sure I’d go postal.

The Search for a Better Way

In thinking about the problem, I realized that what I needed was a simple way to generate a client proxy.  I could then build my address, binding and channel in code, pulling any of the necessary pieces of configuration from a config file.  My first thought was to create the proxy class using SvcUtil.exe.  I soon found, though, that the proxies generated by this tool are incompatible with Silverlight.  I then found out about a tool called SlSvcUtil.exe that generates proxies specifically for Silverlight.  Unfortunately, this tool is supposed to ship with Silverlight 3 and I’m still working in version 2.

For now, I’ve found two alternatives.  First is a bit of a hack, but still a fairly easy way to generate proxies that I found here.  Basically, this blog post suggests using the “Add Service Reference” functionality in Visual Studio to generate a reference.cs, saving that class and then deleting the service reference.  I also found an article by David Betz, here, that takes you through an excellent explanation of the details of the inner workings of WCF with Silverlight and suggests writing proxies by hand.

It’s good to have choices and I’m sure I can find circumstances where each approach will be beneficial.

Tags:

.Net | ASP.Net | Silverlight | WCF

Windows 7, Silverlight and the Unrecognized Element Exception

by mgordon 12. June 2009 04:22

I recently rebuilt my development laptop with Windows 7 and have been developing on it.  I have an existing Silverlight application that I have been deploying to a Windows Server 2003 machine and encountered some odd behavior after making modifications to in on the Windows 7 box and deploying it to the server.  The application ran fine on the development box, but after deploying to Windows 2003, any time the application made a call to a WCF service, an exception was raised declaring that an unrecognized element had been encountered.  After looking through several of the XML files in the solution, I happened upon the problem.

When looking at the ServiceReferences.ClientConfig file, I found the bindings defined there looked like this:

<binding name="BasicHttpBinding_Processing" maxBufferSize="2147483647"
    maxReceivedMessageSize="2147483647">
    <security>
        <transport>
            <extendedProtectionPolicy policyEnforcement="Never" />
        </transport>
    </security>
</binding>

The security element and everything within it was added when I modified one of the service references in my Silverlight project.  Removing all occurrences of these tags solves the problem.  These tags are not added under the same circumstances when developing on Vista or XP.

I’m still not sure why these tags were added.  I’m running .Net 3.5 SP1 on both my development machine and the server.

Tags:

.Net | ASP.Net | Silverlight | WCF

Accessing the Membership Provider from Silverlight

by mgordon 13. May 2009 04:50

In a particular Silverlight application, I felt it would be common for a user to have the application open for long periods, but not necessarily be interacting with it all the time.  This meant that there was always a chance the user’s session would time out.  Since the application uses the Membership and Role providers, nasty errors were being raised from web service calls depending on data from these providers if the session was not available.

To handle this situation, I tested for a valid session in my services and raised a custom exception if it wasn’t available.  Then, using the ideas in my last post I trapped that exception in my Silverlight application and showed a login box to the user so they could log back into the application and re-establish a valid session.

The next piece of this puzzle to solve was how to gain access to the Membership Provider from the Silverlight application to log the user back in.  Turns out there are two ways to go and both are equally valid for an Ajax application as well as Silverlight, though one is clearly more suitable for Ajax than Silverlight.

ASP.Net Ajax

The first solution is to use functionality built into the ASP.Net Ajax framework.  There is a javascript object in the framework, Sys.Services.AuthenticationService, that provides the needed functionality.  So, if you have all the necessary parts of the Ajax framework set up, in JavaScript you can say

var ssa = Sys.Services.AuthenticationService;

ssa.login(username,
              password,
              isPersistent,
              customInfo,
              redirectUrl,
              onLoginComplete,
              onError);

Of course you pass the username and password.  IsPersistent is a bool value indicating whether or not the user wants to be “remembered” by the application.  CustomInfo can be null as can the redirectUrl.  Of course, if you would like the user to be redirected to a certain Url after a successful log in, you’d specify that Url. The last two values are pointers to the methods to call when the login has completed or has errored out.  If you’re calling this from a web page it’s straight forward and from Silverlight, you’d need to wrap this code in a JavaScript function, and then call it from Silverlight like this.

Exposing Authentication as Web Service

Brad Abrams has an excellent tutorial on how to expose the needed functionality as a web service, here.  This was the approach I ended up using in my Silverlight application because it fit well with how the rest of the application was designed.   Once the functionality has been exposed as a web service, you could call this web service the same way you’d call any other from an Ajax application.

Tags:

.Net | Silverlight | WCF | ASP.Net

WCF Exceptions in Silverlight

by mgordon 6. May 2009 08:49

I’ve been working on a fairly substantial Silverlight 2 application and finally took on an aspect of it that I had been dreading and putting off for some time – exception handling – specifically handling exceptions being thrown from my WCF services.  I just knew this was going to be a bear.  Turns out, it wasn’t quite as bad as I had feared, but it was enough trouble that I thought a blog post sharing the experience would be a good thing.

The Problem

Silverlight doesn’t communicate directly with your web services, but rather it uses the browser API for this communication.  When calling a web service, if any exception occurs, the browser converts this into a generic 400 (Page not found) error and hands it back to Silverlight.  The result is that inside your Silverlight application, you know that an exception has occurred during your call, but have no way of knowing what it was.  This problem is supposed to be fixed in version 3.

The Research

This was certainly something I didn’t want to rush into solving so I did a bit of research on the Internet before jumping in.  Some we solving this by using out parameters on their services that contained the exception information which required checking the value of this parameter after each call.  I found a solution that was quite nice on CodeProject that used attributes on the service methods and contracts and a base class for the proxy on the client.  Since I’m still using Visual Studio generated proxies in my project, this one aspect of the solution made it unusable for my purposes.  In a discussion, here, I discovered that Microsoft’s Silverlight web service team had published a solution to the problem.  I checked it out and decided on this solution for my application.  A blog post about the solution can be found here and the code can be downloaded from code.msdn.microsoft.com.

The Code and Configuration

I found a few blog posts from folks who had implemented this solution, but none that were comprehensive and none that addressed its use with Visual Studio generated proxies.  Below, then, are the steps I took to get it all working in my application.

First, download the code the Silverlight web service team makes available and compile all the solutions.  You’ll need to set references to a few of the generated assemblies.

References

In the web project containing your WCF web services, set a reference to the assembly “SilverlightFaultBehavior.dll”.  Now, in your Silverlight project set references to the assemblies “SilverlightRawFaults.dll” and “SilverlightMessageInspector.dll”.

Code

If the web project containing your WCF web services doesn’t have a Global.asax file, add it and add the following code to it.  This code will cause any service requests that fail to return a 200 status code instead of 400.

 

protected void Application_EndRequest(object sender, EventArgs e)
{
    if (HttpContext.Current.Request.PhysicalPath.EndsWith(".svc", StringComparison.OrdinalIgnoreCase) &&
        HttpContext.Current.Response.StatusCode == 500 &&
        !HttpContext.Current.Request.Browser.Crawler &&
        HttpContext.Current.Request.Browser.EcmaScriptVersion.Major > 0)
    {
        // Set 200 if its a faulted service request
        HttpContext.Current.Response.StatusCode = 200;
    }
}
 

In any Silverlight class that makes a call to a WCF service, add the following (C#).

using Microsoft.Silverlight.Samples;
using SilverlightRawFaults;

At the point where you’re making the WCF call, you’ll be creating an instance of the proxy for that service.  Before making the call on that proxy, replace its binding by adding a line similar to this.

proxy.Endpoint.Binding = new BasicHttpMessageInspectorBinding(new SilverlightFaultMessageInspector());

This binding will ensure that the message inspector has a chance to look at the message returned from your call.

Finally, in the completed event for your service call, you’ll need to evaluate the Error property on the passed in event argument. 

if (e.Error != null && e.Error is RawFaultException)
{
    RawFaultException exception = (RawFaultException)e.Error;
    MessageBox.Show("Service says: " + exception.FaultMessage + Environment.NewLine +
        "Exception type: " + exception.FaultType + Environment.NewLine +
        "Stack trace: " + exception.StackTrace);
}
The Bug

After making the above modifications to my code, the value of the FaultMessage was not what I was expecting.  No matter what the exception was, this property always had the same generic value.  I found that there was a bug in the code provided by the Silverlight web service team and once it was corrected, all worked as expected.

Correcting the Bug

To correct the bug, open the downloaded solution called “SilverlightRawFaults”.  In the SilverlightRawFaults project, you’ll find a class called “BasicHttpMessageInspectorBinding”.  There is a property on this class called “FaultMessage” (oddly enough, the value that was incorrect).  Change this

public string FaultMessage 
{
    get { return Message; } 
}

to this

public string FaultMessage 
{
    get { return message; } 
}

Note that all I changed was the case of the “M” in “message”.  In this class, message is a member variable where Message is a property of the base class which is never set.  In the method RawFaultException sets message to the string containing the exception’s message, which is the value that should be returned.

Tags:

.Net | Silverlight | WCF

VisualTreeHelper Class in Silverlight

by mgordon 20. February 2009 08:37

It’s hard for me to believe I’d never encountered the situation before, but I was recently working on a part of a Silverlight application where I’d used a ListBox and specified an ItemTemplate within it containing a CheckBox and a TextBlock.  When a particular event fired, I wanted to iterate through all the ListBox Items, examine the Text property of the TextBlock and based on some simple logic, either check or uncheck the CheckBox.  My XAML for the ListBox looked like this:

<ListBox Margin="-5.057,34.225,0.116,0.121" Grid.Row="1" x:Name="lbRoles">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel HorizontalAlignment="Stretch" Orientation="Horizontal" >
                <CheckBox Checked="CheckBox_Checked"></CheckBox>
                <TextBlock Margin="5,0,0,0" Text="{Binding Path=RoleName}" FontWeight="Bold" 
Width="Auto" HorizontalAlignment="Stretch"
LineStackingStrategy="BlockLineHeight" LineHeight="15"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>

So, basically, I was binding the ListBox to a collection and populating the TextBlock’s Text property from the binding.  My first task was to figure out how to access the ListBoxItem’s since The ListBox’s Items property would return the collection it was bound to and not the generated Items. I did some research and came across a newsgroup thread, here that contains an example of using the VisualTreeHelper class

In that thread, there is method defined like so:

private void GetChildren(UIElement parent, Type targetType, ref List<UIElement> children)
{
    int count = VisualTreeHelper.GetChildrenCount(parent);
    if (count > 0)
    {
        for (int i = 0; i < count; i++)
        {
            UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i);
            if (child.GetType() == targetType)
            {
                children.Add(child);
            }
            GetChildren(child, targetType, ref children);
        }
    }
}


You’ll notice that the method requires you to specify a type of control you’re interested in and also that it uses recursion to walk through every control in the visual tree beneath the specified parent.  I quickly found there is a vast hierarchy of controls created for the ListBox beyond what you’ll see in your XAML so it makes sense to recurse the tree of controls and only return what you’re needing.  I added this method to my class and used it for the above described problem like this:

List<UIElement> items = new List<UIElement>();
GetChildren(lbRoles, typeof(ListBoxItem), ref items);

foreach (ListBoxItem item in items)
{
    List<UIElement> children = new List<UIElement>();
    GetChildren(item, typeof(CheckBox), ref children);
    CheckBox cb = (CheckBox)children[0];

    children.Clear();
    GetChildren(item, typeof(TextBlock), ref children);
    TextBlock block = (TextBlock)children[0];

    if (_currentUserRoles.Contains(block.Text))
    {
        cb.IsChecked = true;
    }
    else
    {
        cb.IsChecked = false;
    }
}

So, using VisualTreeHelper and the helper method, I’m able to iterate through all the ListBoxItems and within each, to get a reference to the CheckBox and TextBlock within it.

Tags:

Silverlight | .Net

Using The ASP.Net Membership, Role And Profile Providers

by mgordon 17. February 2009 06:25

I’ve used these providers quite a bit over the past few years with good success.  As a simple overview, the Membership provider offers functionality that allows you to authenticate users against a store of users, the Role provider lets you authorize users to perform actions on your site based on roles they have been assigned and the Profile provider allows the saving of additional user details.  By using these providers, you can relieve yourself of having to roll your own functionality for these purposes.  I have found the Scott Mitchell’s tutorial located here to be an invaluable resource, but I have also picked up some tricks along the way.  Below, I’ll explain in a brief way how to set these providers up to use SQL Server as the data store. 

aspnet_regsql

First of all, we’ll need a place to store our information.  A utility is provided with the 2.0 version of the framework called aspnet_regsql.exe that will create all the required database objects for you.  The first decision you need to make is whether this information will live in your application’s database or in a separate database.  If your intention is to use the same user base across several applications, I’d elect to create a separate database for this information, otherwise I’d place the objects along side my application data.

Run the utility and you’ll be presented with the following screen.

regsql_screen1

Click Next> to continue the wizard.

regsql_screen2

Select the top radio button since we’re adding the database objects, not removing them.  Click Next>.

regsql_screen3

Select the SQL Server to install the objects to, credentials to authenticate (NOTE: The credentials used must have rights to create tables, views, stored procedures, etc on the specified database) and database.  If the database already exists, the objects will be created in it.  If the database specified does NOT exist, it will be created and then the objects will be created in it.  Click Next>.

regsql_screen4

This screen gives you an opportunity to review your choices.  If the information is correct, click Next>, otherwise click <Previous and correct your choices.  Clicking Next, here, creates the objects in the specified database.  Objects for all providers are created in the database.  You select the ones you wish to incorporate into your application by specifying them in the web.config file.  Let’s look at how to set up the providers.

Setting Up The Providers

The first thing we’ll need to do, is tell the providers where to find their data.  We do this by specifying a connection string in web.config.

<connectionStrings>
    <add name="Connection" connectionString="Data Source=ProviderDatabase; 
initial catalog=ProviderDB;
uid=user; password=pass"/> </connectionStrings>

All the providers we specify in web.config will reference this connection string section.

Now, we need to start configuring our providers.  We so this in the <system.web> section of the web.config file.

<roleManager enabled="true">
  <providers>
    <remove name="AspNetSqlRoleProvider"/>
    <add connectionStringName="Connection" applicationName="/MyWebApp" 
name="AspNetSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider,
System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
"/> <remove name="AspNetWindowsTokenRoleProvider"/> <add applicationName="/MyWebApp" name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider,
System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
"/> </providers> </roleManager> <profile> <providers> <remove name="AspNetSqlProfileProvider"/> <add name="AspNetSqlProfileProvider" connectionStringName="Connection"
applicationName="/MyWebApp"
type="System.Web.Profile.SqlProfileProvider, System.Web,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
"/> </providers> </profile> <membership defaultProvider="CustomizedProvider"> <providers> <clear/> <add name="CustomizedProvider" type="System.Web.Security.SqlMembershipProvider"
connectionStringName="Connection" applicationName="/MyWebApp"
minRequiredPasswordLength="5" minRequiredNonalphanumericCharacters="0"
enablePasswordRetrieval="false" enablePasswordReset="true"
requiresUniqueEmail="true" maxInvalidPasswordAttempts="4"
passwordAttemptWindow="10" requiresQuestionAndAnswer="false"/> </providers> </membership> <authentication mode="Forms"> <forms loginUrl="Login.aspx"/> </authentication> <authorization> <deny users="?"/> </authorization>

In the above, I’m specifying that I want to use the Role, Profile and Membership providers.  Notice the use of <remove> and <clear> tags.  The way the config files work is that they start at the machine level (machine.config) and get settings from there.  Then the web.config for the root web site is combined with that and so on down the hierarchy until the level at which your application sits.  There is a chance that a conflicting configuration will exist at some level above your site that will prevent the providers from working properly.  The <remove> and <clear> tags remove any existing settings so our providers remain as the only ones defined.

Next, notice how the each of the providers requires an attribute, connectionstringname.  This should always be the name of the connection string section that points to the database where your provider objects were created.  In our case, above, we created a connection string section named “Connection”, so that’s the section we specify to each of the providers.  Each provider also requires an attribute of applicationName.  Two things to remember, here.  First, this needs to be the actual name of your site and the second is to always preface this name with a forward slash if the application is sitting somewhere below the root of the site.  Since it’s possible for you to use the same provider database for multiple sites, the site name is used by the providers to determine which set of settings apply.  If you forget the forward slash for a site below the root, you’ll find that you get duplicate application records in your database…one with and one without a slash for the application name.

The Membership provider allows quite a lot of configuration.  The example, above, specifies many of the allowable settings but not all.  I highly recommend you look at the documentation to see all that can be specified.

Since we are going to use the Membership provider to log our users into the site, we need to set up forms authentication.  This is being done in the authentication and authorization tags.  Here, we’re saying we’re not allowing anyone to access the site unless they have logged in and if they have not yet logged in, we redirect them to the Login.aspx page.  On this page, you can simply drag on the login control from the toolbox.  No further setup is required.  The control is smart enough to get all it needs from the web.config file.  When the user logs in, the Membership provider will automatically be used and the user will be authenticated against the database.

Since we specified the Login.aspx page as the login page, users automatically get access to it without having to be logged in.  What if we wanted to use some of the other controls provided with ASP.Net to manage our account like password recovery or changing passwords?  We can do this by creating the pages for the purpose at hand and dragging the appropriate control onto it.  All controls of this type will know how to use the provider automatically.  However, if a user should be able to access the page without having logged in, first (password recovery, for example), we’ll need to allow for this.

As we have configured the site, users can only access Login.aspx without having logged in and all other content is inaccessible to non-authenticated users.  We need to make an exception of the pages in question so the rules don’t apply to them.  To do this, we create a <location/> section in web.config. Just below the <system.web/> section, add the following.

<location path="RecoverPassword.aspx">
  <system.web>
    <authorization>
      <allow users="*"/>
    </authorization>
  </system.web>
</location>

This section, in effect, says, “For this one page, allow all users".”

Tags:

.Net | Productivity | Sql Server 2005

ActiveX Killbits Problem with Reporting Services Printing

by mgordon 13. February 2009 08:01

We just found and corrected a problem with printing from the reporting services web interface.  When the user clicked the print button, they received a popup message saying ""Unable to load client print control”.  As we found out, the problem was created when the users’ desktops installed a hotfix from Microsoft, KB956391.  We had two choices upon finding this out; we could remove the patch from every workstation or install a subsequent hotfix to Sql Server.  We opted for the latter and installed the hotfix located here.  Printing seems to work perfectly, now.

Tags:

Database | Sql Server 2005

Silverlight, WCF and Domain Names

by mgordon 14. January 2009 11:33

As I learn more about WCF, especially as it’s consumed by Silverlight, the better equipped I am to identify and solve problems.  This is what I keep telling myself as a justification for the time I spend and angst I feel sometimes as I feel my way through my first significant Silverlight application.

I am far enough along that I wanted to add a deployment step to by build process which would copy all the requisite application files to a web server I have running at home.  My main goal was to iteratively deploy the application, as it progressed, so some folks whose opinions matter to me could look at and play with the application and give me feedback.

When I created the Visual Studio solution for my application, I elected to have VS create a web application for me and my .xap file and WCF services are both hosted in that application.  So, as I develop, I’m typically working in a mode where I’m running the web application in the development web server so I can make service changes on the fly.  This all worked fine in regard to being able to communicate with my services from the Silverlight application.

I realized, after deploying, that my Silverlight application would need to talk to services running on my server instead of locahost, so before checking in the code each time, I changed my service references to point to services located there.  More specifically, to point to a domain I have set up for that server.  I checked in, the build deployed the application, I tested and found no joy at all.  As I investigated, I discovered that when I set my service references to point to my domain (http://www.domain.com/MyService.svc) what was actually being recorded in web.config and the artifacts that were created by adding the reference was http://machineName/MyService.svc.  After a good bit of research and thinking about the problem, I found the solution.

The root of the problem has nothing to do with Silverlight or WCF.  It’s actually a web site configuration issue that can be corrected by going to the Internet Information Services MMC Snap-In, and drilling down to your web site.  Note that if IIS is listening on only one port, this will be the “Default Web Site”.  In IIS 6 and before, you’ll want to go to the “Web Site” tab and click the “Advanced” button.  You should see a window like the one below.

WebSiteConfig 

Notice that this site is listening on port 80 and has no Host Header Name and so the default value is used which is the name of the machine IIS is running on.  To correct the problem, select the one row and click the edit button.  Then, fill in the Host Header Name such that it matches your domain like www.domain.com and click OK.

For IIS 7, select the web site in the tree view, select the “IPv4 Address and Domain” icon and then click the “Bindings” link on the right hand side.  Select the record for port 80 and click the Edit button.

websettings

Enter your host name, as above, and click the OK button and then the Close button.

After making this change, your service references should be scoped to your domain instead of to the machine name.

Tags:

.Net | Silverlight | WCF

Powered by BlogEngine.NET 1.5.0.7
Theme by Extensive SEO