Raj Kaimal

Using the Modal Popup Extender to build a popup search interface

This post and sample code demonstrates how to use the Modal Popup Extender (MPE) to display a popup search box, select a record from the popup, hide the popup and display details for the selected record on the page using AJAX.

We will be using the Northwind database and displaying a “Find Customer” popup. Once a Customer is selected from the search result list, we hide the MPE and refresh UpdatePanels on the page with information related to the Customer that was picked. Sample source code is attached at the bottom of the page.

popuppicker 

The events that occur as as follows:

When we click on the “Show Customer Picker” button, we have a popup appear with the help of an MPE. This MP has a UserControl with textboxes, a search button and a GridView inside an UpdatePanel. Performing a “Search” will cause only the contents of this UpdatePanel to get refreshed. To avoid the search GridView from binding when the popup is hidden (when an async postback occurs by some other button on the page), we keep track of the MP visibility (The technique for keeping track of the MPE visibility is described here). If the MP is hidden, we use the ObjectDataSourceSelectingEventArgs.Cancel method in the ObjectDataSource Selecting event to cancel the SQL call.

When we select an employee by clicking on the “Select” link, the Selecting event of the GridView is raised. We get the primary key of the selected customer by subscribing to this event. The MP is then hidden and a custom CustomerSelected event is raised.

The Page is subscribed to the CustomerSelected event and saves the selected customer primary key to Session (You could use other techniques instead of this). It then forces the UpdatePanels of other UserControls on the page to refresh themselves. These UpdatePanels have databound controls in them that get bound by making SQL calls using the customer PK stored in Session. The page ends up showing information about the selected customer (Customer Details, Last 10 orders, To 10 Orders) on the page without a full page refresh.

The sample website project shows you how to achieve this UI in three stages (three pages). The demo in Stage1 shows how the page is laid out without using AJAX – all postbacks result in a full page refresh. In Stage2, we add the UpdatePanels to perform partial page rendering. In Stage3, we add the MP that displays the “Find Customer” popup.

Don’t forget to add a reference to the Ajax Control ToolKit before building the project.

Source Code
Mirror

Posted by rajbk | 5 comment(s)

Check Modal Popup Extender visibility from code behind

AFAIK, the Modal Popup Extender  has no direct way to determine its visibility state from code behind. This post describes a workaround for that.

The idea here is to wire up handlers that the MPE fires just before it’s about to show the popup (showing event) and before it’s about to hide the popup (hiding event).

In the handlers, we set the property of a HiddenField webcontrol to either ‘1’ or ‘’. We then check the Value property of this HiddenField from code behind. If the MPE has a value of 1, we know the MPE is visible.

   1: Sys.Application.add_load(applicationLoadHandler);
   2:  
   3:  
   4: //Subscribe to the show and hide events of the modal popup.
   5: //Set a hidden field some value when visible and set to empty when hidden
   6: //This hidden field is used in code behind to determine the popup visibility.
   7: function applicationLoadHandler() {
   8:     var mpeEmployeeSearch = $find('mpeEmployeeSearch');
   9:     if (mpeEmployeeSearch) {
  10:         mpeEmployeeSearch.add_showing(employeeShowingHandler);
  11:         mpeEmployeeSearch.add_hiding(employeeHidingHandler);
  12:     }
  13: }
  14:  
  15: function employeeShowingHandler() {
  16:     $get('hfModalVisible').value = '1';
  17: }
  18:  
  19: function employeeHidingHandler() {
  20:     $get('hfModalVisible').value = '';
  21: }

The MPE in this case has been assigned a BehaviorID of mpeEmployeeSearch. The HiddenField WebControl has ID (rendered in HTML) of “hfModalVisible”.

Finally, we can check the MPE visibility from code behind like so:

   1: if (!string.IsNullOrEmpty(hfModalVisible.Value))
   2: {
   3:     //Do something
   4: }

Post a comment if you know of a better way.

Posted by rajbk | 1 comment(s)

Uploading an Excel file to SQL through an ASP.NET webform

The method below describes how to upload a file to a webserver and then import the file into SQL using either LinqToSQL or SQL Bulk Copy. The sample code only shows how to import xls and xlsx files but it could easily be extended to support csv files too.  Sample code is attached at the bottom.

fileupload

We will be uploading data from an Excel file containing columns CompanyName and Phone and loading that into the Northwind Shippers table.

We’ll start by uploading the file to the webserver. This is done with the help of the FileUpload web control. The FileUpload control has a SaveAs method which saves the contents of the file into the location that we specify. The file will be stored in a temp folder under App_Data since App_Data is not browsable directly by users.

Once we have successfully uploaded the file to the webserver, we use an OleDbConnection and an OleDbDataReader to read each row from the Excel file. The OleDb connection string varies by file extension. The connection strings are shown below:

Extension ConnectionString
xls Provider=Microsoft.Jet.OLEDB.4.0;Data Source=[FilePath];Extended Properties=”Excel 8.0;HDR=YES;IMEX=1”
xlsx Provider=Microsoft.ACE.OLEDB.12.0;Data Source=[FilePath];Extended Properties=Excel 12.0 Xml;HDR=YES;IMEX=1

HDR=Yes specifies that the first row of the data contains column names and not data
IMEX=1  specifies that the driver should always read the “intermixed” data columns as text.

The query we will be using with the connection is "SELECT CompanyName, Phone FROM [Sheet1$]". This assumes that we have an excel sheet called Sheet1 with header columns CompanyName and Phone.

Method 1: Using LINQ To SQL

Using the OleDBDataReader, we read each record and create a new Shipper object for each OleDbDataReader record as shown below. We add this object to the Shipper collection object that is associated with the Shipper table in the database using InsertOnSubmit and call SubmitChanges. This loads all the Excel records into the Shipper table.

Note: Since we are calling SubmitChanges without any Transaction defined, LINQ to SQL automatically starts a local transaction and uses it to execute the insert statements. When all insert statements successfully complete, LINQ to SQL commits the local transaction – nice:-) This occurs behind the scenes.

   1: //ref: http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader(VS.71).aspx
   2: using (var context = new NorthwindDataContext())
   3: {
   4:     using (var myConnection = new OleDbConnection(base.SourceConnectionString))
   5:     using (var myCommand = new OleDbCommand(query, myConnection))
   6:     {
   7:         myConnection.Open();
   8:         var myReader = myCommand.ExecuteReader();
   9:         while (myReader.Read())
  10:         {
  11:             context.Shippers.InsertOnSubmit(new Shipper()
  12:             {
  13:                 CompanyName = myReader.GetString(0),
  14:                 Phone = myReader.GetString(1)
  15:             });
  16:         }
  17:     }
  18:  
  19:     context.SubmitChanges();
  20: }

Method 2: Using SQL BulkCopy

With the BulkCopy method, we first have to define the Column Mappings since we will not be inserting data into the autogenerated ShipperID Primary Key column. The first column in the Excel file (CompanyName) has to be mapped to the second column in the Shipper table and the second column (Phone) has to be mapped to the third column in the Shipper table as shown below.

We read each record from the OleDbDataReader and using the BulkCopy WriteToServer overload that takes in an IDataReader (which the OleDbDataReader implements). The BulkCopy, using this method bulk loads the Shippers destination table with the data from the OleDbDatareader.

   1: //ref: http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader(VS.71).aspx
   2: //ref: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx
   3: using (var myConnection = new OleDbConnection(base.SourceConnectionString))
   4: using (var destinationConnection = new SqlConnection(destinationConnectionString))
   5: using (var bulkCopy = new SqlBulkCopy(destinationConnection))
   6: {
   7:     //Map first column in source to second column in sql table (skipping the ID column).
   8:     //Excel schema[CompanyName,Phone] Table schema[ShipperID, CompanyName, Phone]
   9:     bulkCopy.ColumnMappings.Add(0, 1);
  10:  
  11:     bulkCopy.ColumnMappings.Add(1, 2);
  12:     bulkCopy.DestinationTableName = "dbo.Shippers";
  13:  
  14:     using (var myCommand = new OleDbCommand(query, myConnection))
  15:     {
  16:         myConnection.Open();
  17:         destinationConnection.Open();
  18:  
  19:         var myReader = myCommand.ExecuteReader();
  20:         while (myReader.Read())
  21:         {
  22:             bulkCopy.WriteToServer(myReader);
  23:         }
  24:     }
  25: }

The BulkCopy object is much faster than LINQ to SQL. I am copying Pablo Castro’s newsgroup response:

  • No per-row statement execution. When you do multiple inserts without bulk-copy, each insert is a statement in itself (regardless of whether it's batched together with other statements). With bulk-copy, we don't incur the cost of executing a statement for each row, the whole copy operation is a single thing.
  • No multiple network round-trips. Once the bulk-insert operation is setup, we send rows from the client to the server continously, without going back-and-forth over the wire.
  • Server storage engine also can greatly optimize how rows are inserted when performing a bulk-copy operation. How much can be optimized depends a lot on the recovery model the tarder database is set to; in "simple" and "bulk logged" the overhead of logging is greatly reduced during bulk-copy operations, helping a lot with performance.

 

Sample Code
Mirror

Posted by rajbk | with no comments
Filed under: , , ,

Implementing Deeplinking in Silverlight

 

This article is now outdated. Silverlight 3 now has deeplinking built in. There might be other articles on this but this is the only one I could find on this topic:  http://programwith.net/2009/03/23/Silverlight3NdashDeepLinking.aspx


Version: Silverlight 2 Beta 2 / .NET 3.5 SP1

See source code links at the bottom of this post.

The following post is an attempt at implementing deep linking in Silverlight. Deeplinking allows users to use the browser back and forward buttons to switch between different “states” of the application and also allows bookmarking a certain state of the app.  It provides a great UX in scenarios like viewing a slide show, paging through a document etc.  IMHO, I think deeplinking should be baked into Silverlight by default.

To implement this, we use the System.Web.Extensions assembly in .NET 3.5 SP1 Beta which adds native support for navigating forward and backward through the browser history stack and also allows bookmaking. We will add some custom code to our Silverlight application and host it inside an aspx page so that it can take advantage of the new features of the assembly or more specifically the JavaScript code in this assembly.

As a quick refresher, in the context of an ASP.NET AJAX application, we add new entries to the browser history stack by calling Sys.Application.addHistoryPoint(state, title) where state is a StringDictionary  containing the state we wish to store and title is the page title.

The Sys.Application.navigate event is raised anytime the user clicks the browser back or forward button. To restore the state of the page, we subscribe to this event and call e.get_state() inside our event handler. You can read more on this topic here.

The idea here is to have our Silverlight application make a javascript call to addHistoryPoint anytime we wish to store the state of the application in the browser history. We then subscribe to the JavaScript Sys.Application.navigate event and change the state of our application when this event is raised.

We start by creating Silverlight application using Blend 2.5 June 2008 preview or VS 2008. In the App.cs class, we add a helper method for making the call to addHistoryPoint like so (FYI, HtmlPage.Window.Eval method performs the equivalent of making a JavaScript eval method call):

   1: /// <summary>
   2: /// Call to Sys.Application.addHistoryPoint
   3: /// </summary>
   4: public void AddHistoryPoint(string stateKey, string stateValue, string title)
   5: {
   6:     string addHistoryScript = "Sys.Application.addHistoryPoint({{ {0}:'{1}' }}, '{2}');";
   7:     HtmlPage.Window.Eval(string.Format(addHistoryScript, stateKey, stateValue, title));
   8: }

 


The next step is to subscribe to the JavaScript Sys.Application.navigate event from our Silverlight managed code. To make our managed code accessible through javascript, we have to register our class as a scriptable object and then make our method accessible by marking it with the Scriptable attribute, Read more on this topic here.

As shown below, HandleNavigate is marked as a scriptable member which exposes it to JavaScript.

   1: /// <summary>
   2: /// Events
   3: /// </summary>
   4: public event EventHandler<StateEventArgs> Navigate;
   5:  
   6: /// <summary>
   7: /// Handler for Sys.Application navigate event
   8: /// </summary>
   9: [ScriptableMember]
  10: public void HandleNavigate(ScriptObject state)
  11: {
  12:     if (Navigate != null)
  13:     {
  14:         Navigate(this, new StateEventArgs() { State = state });
  15:     }
  16: }

In the code below, we register our class as a scriptable object (Line 13). We also dynamically load a Javascript script block which creates a helper JavaScript function that subscribes to the navigate event. The helper function then makes a call to our silverlight HandleNavigate method (Line 17). The last method in the script block is a call to __navigateHandler which is for restoring the state of the page when the page loads for the first time or through a bookmark.

   1: private void OnStartup(object sender, StartupEventArgs e)
   2: {
   3:     // Load the main control here
   4:     this.RootVisual = new Page();
   5:     InitScripts();
   6: }
   7:  
   8: /// <summary>
   9: /// Register event hander through proxy method
  10: /// </summary>
  11: private void InitScripts()
  12: {
  13:     HtmlPage.RegisterScriptableObject("App", this);
  14:     string initScript = @"
  15:         var __navigateHandler = new Function('obj','args','document.getElementById(\'appId\').content.App.HandleNavigate(args.get_state())');
  16:         Sys.Application.add_navigate(__navigateHandler);
  17:         __navigateHandler(this, new Sys.HistoryEventArgs(Sys.Application._state));
  18:      ";
  19:     HtmlPage.Window.Eval(initScript);
  20: }

With this in place, we can subscribe to the Navigate event from any class and use the state information to make changes to the state of our application.

   1: App app = (App)Application.Current;
   2: app.Navigate += new EventHandler<StateEventArgs>(app_Navigate);
We call the AddHistoryPoint method to store the state of the app when needed as shown below.
   1: App app = (App)Application.Current;
   2: string pageTitle = (activeSlideIndex == -1) ? "Home" : "Slide " + activeSlideIndex;
   3: app.AddHistoryPoint("index", activeSlideIndex.ToString(), pageTitle);

The last step involved is to create an ASP.NET AJAX application, add a ScriptManager control, set the EnableSecureHistorState to false (so that our URL is human readable) and finally add a Silverlight control with the source set to the xap file.

   1: <asp:ScriptManager ID="ScriptManager1" runat="server" EnableHistory="true" EnableSecureHistoryState="False">
   2: </asp:ScriptManager>
   3: <div id="slcontent">
   4:     <asp:Silverlight ID="appId" runat="server" Source="~/ClientBin/SilverlightHistory.xap"
   5:         MinimumVersion="2.0.30523" Width="800" Height="600" BackColor="Black" />
   6: </div>


You can download the sample project here or here (This is experimental beta code - use at your own risk).
Things you can try:

  1. Clicking on the links in the right menu adds history points to the browser stack.
  2. You can use the browser back and forward buttons to walk the stack.
  3. You can bookmark a URL and return to it (example: localhost:9999/SilverlightHistory_Web/Default.aspx#index=2 will load the app with  the third slide visible)

Another topic that has been making headlines recently is RIA SEO. Here are three articles on that:

  1. Search for Rich Internet Applications
  2. SEO for Ajax and Silverlight Applications
  3. SWF searchability FAQ
  4. Improved Flash indexing

Comments are always welcome.

Posted by rajbk | 3 comment(s)

Loading an XML file in your Silverlight project into memory

Version : Silverlight 2 Beta 2

Reading an XML file in an XAP package can easily be done with the help of a helper class like so:

   1: public static class XmlHelper
   2: {
   3:     public static XElement LoadDocument(string fileName)
   4:     {
   5:         //No longer required in Silverlight 2 since
   6:         //XmlXapResolver has been added as the default resolver for XmlReader
   7:         //ref: http://msdn.microsoft.com/en-us/library/cc189007(vs.95).aspx
   8:         //XmlReaderSettings settings = new XmlReaderSettings();
   9:         //settings.XmlResolver = new XmlXapResolver();
  10:         //XmlReader reader = XmlReader.Create(fileName, settings);
  11:  
  12:         XmlReader reader = XmlReader.Create(fileName);
  13:         XElement element = XElement.Load(reader);
  14:         return element;
  15:     }
  16: }

Once you have the XElement object, you are free to manipulate it with LINQ to XML as shown below:

   1: public static List<Slide> LoadSlides()
   2: {
   3:     XElement element = XmlHelper.LoadDocument("Slides.xml");
   4:     var slides = from slide in element.Descendants("Slide")
   5:                  select new Slide {
   6:                     Title = (string)slide.Element("Title"),
   7:                     Text = (string)slide.Element("Text"),
   8:                     Image = (string)slide.Element("Image"),
   9:                  };
  10:     return slides.ToList();
  11: }

The method above returns a List<Slide> where the Slide class is defined like so:

   1: public class Slide
   2: {
   3:     public string Title { get; set; }
   4:     public string Text { get; set; }
   5:     public string Image { get; set; }
   6: }

and the contents of the XML file we are reading is:

   1: <?xml version="1.0" encoding="utf-8"?>
   2: <Slides>
   3:   <Slide>
   4:     <Title>Slide 1</Title>
   5:     <Text>Slide 1 Description</Text>
   6:     <Image>Slide1.jpg</Image>
   7:   </Slide>
   8:   <Slide>
   9:     <Title>Slide 2</Title>
  10:     <Text>Slide 2 Description</Text>
  11:     <Image>Slide2.jpg</Image>
  12:   </Slide>
  13: </Slides>

Note that the XML file should have its BuildAction set to "Content".

Posted by rajbk | 3 comment(s)
Filed under: , , ,

A four stroke engine in Silverlight

I decided to try out Expression Blend 2.5 beta by creating a four stroke engine animation. A screen capture is shown below:
engine

You can see a working demo here (Silverlight 2 plugin required)

Here are a few observations while working on this project.

  1. Writing XAML by hand is difficult :-) Expression Blend is your friend.
     
  2. To export Adobe Illustrator files to XAML, use the free plugin from Mike Swanson. I chose to use AI to create the vector art because I am familiar with AI and it has a lot more features than Expression Design. When importing the XAML into Blend, you might see error messages in Blend about invalid markup as a result of the translation. In most cases these errors can easily be fixed by editing the XAML markup (Blend gives you the line number of the error).
     
  3. For performing simple custom animations using a timer in your UI thread, use the DispatcherTimer class. The timer raises a Tick event at the end of the specified interval where you can update the UI. Note that the DispatcherTimer is single threaded and does not use the thread pool which could lead to a frozen UI if the Tick event handler takes too long to complete or if the thread is busy doing something else.
     
  4. To apply multiple transformations to an object, for example a RotateTransform and a ScaleTransform at the same time, use the TransformGroup class.
     
  5. Expression Blend,  AFAIK, does not allow you to edit your C# files. You edit them in VS 2008. Be prepared for a lot of switching back and forth between both applications. In addition, VS 2008 sometimes goes crazy and refuses to show you the XAML preview when you have a complex XAML document. Restarting VS or recompiling the project usually makes the problem go away. Probably because I am using a beta product.
     
  6. Animations can be created in expression blend using a timeline where you set keyframes that define the start and end points of the transform on an object. I chose, instead, to create the animations in code behind using C# using mathematical equations.

Overall, Expression Blend 2.5 beta was easy to work with. The UI could be improved a lot though. I plan to post feedback on Microsoft Connect soon.

You can download the VS 2008 project here or from the mirror here.

Posted by rajbk | 1 comment(s)
Filed under: , , ,

Connection strings in LINQ to SQL classes.

Version : VS 2008 RTW

When you have a team working on a project that contains a LINQ to SQL class (dbml), you might see the following message when trying to add a Table entity or stored procedure in a dbml created by a fellow developer:

The objects you are adding to the designer use a different data connection than the designer is currently using. Do you want to replace the connection used by the designer? 

The reason this happens is because the connection string in Server Explorer used to add the new stored procedure is different from what was originally used. In a team environment, this will occur if one developer checks in the dbml using one connection string and another developer checks out the dbml and tries to add a stored procedure or a table using a different connection string. Connection strings generally fall into one of the two shown below for SQL server:

Windows Authentication:

Data Source=.\sqlexpress;Initial Catalog=northwind;Integrated Security=True

SQL Authentication:

Data Source=.\sqlexpress;Initial Catalog=Northwind;Persist Security Info=True;User ID=northwind_web;Password=**

The connection string could easily vary by the type of authentication, the userid/password combination, instance name etc. This could become a source control nightmare with each developer checking in the dbml file with a connection string defined in their "Server Explorer". Therefore it is best, when possible, that all developers use the same connection string defined in "Server Explorer" when working with a dbml file for a given project.

This brings up the question of how to change connection string when the dbml class library is used in an ASP.net website. The solution is create a connection string in web.config with the same name as what is specified in app.config.

To understand why, we have to look at the class library dll. I have a sample project attached at the bottom of this post that contains a class library containing a dbml and the class library being referenced from an ASP.Net project. When the library gets built, a sealed class called Settings is generated internally. Here is the class with the help of reflector:

[CompilerGenerated, GeneratedCode("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")]
internal sealed class Settings : ApplicationSettingsBase
{
    // Fields
    private static Settings defaultInstance = ((Settings) SettingsBase.Synchronized(new Settings()));
 
    // Properties
    public static Settings Default
    {
        get
        {
            return defaultInstance;
        }
    }
 
    [ApplicationScopedSetting, SpecialSetting(SpecialSetting.ConnectionString), DefaultSettingValue(@"Data Source=.\sqlexpress;Initial Catalog=northwind;Integrated Security=True"), DebuggerNonUserCode]
    public string northwindConnectionString
    {
        get
        {
            return (string) this["northwindConnectionString"];
        }
    }
}


We see that the northwindConnectionString property has a DefaultSettingValue attribute containing the connection string. When Settings gets loaded at runtime, if it finds the same a connection string with name MyClassLibrary.Properties.Settings.northwindConnectionString in app.config or web.config, it will use that. If it does not find it, it reverts to the DefaultSettingValue. As long as our web.config has the same "name" as what the Settings class is looking for, that will get used in place of the default value.

What about the case where we want one connection string during development and another for production? In web.config, you can specify the configSource attribute in the connectionStrings section. This attribute specifies the fully qualified name and location of an external configuration file that contains the connectionStrings section. During development, you can have configSource point to the connectionString of your test server and when you are ready to deploy to staging or production, you can change the attribute to point to the appropriate external config file. You can also have this done automatically using Web Deployment Projects or MSBuild.

The sample project attached contains a class library with a connection string defined. This class library is used in an ASP.net website project containing a connection string in web.config with the same "name" as what was used in the class library thereby "overriding" the class library connection string value. The website project also has a configSource defined in web.config pointing to an external configuration file ConnectionStrings_Test.config. When deploying to production, the configSource will be set to point to ConnectionStrings_Prod.config which contains the production server connection string.

Comments are welcome. Thanks!

Posted by rajbk | 4 comment(s)
Filed under: , ,

LinqDataSource exceptions

Prerequisite: LinqDataSource & SqlDataSource Master/Details

When working with the LinqDataSource, you may get the exceptions listed below.

1. Operator '==' incompatible with operand types 'Int32' and 'Object'

The exception occurs because anytime a ControlParameter in the WhereParameters collection (IDictionary<string, object>) is null, it gets treated as type Object causing the LINQ dynamic expression parser comparison to fail. Consider the code snippet below:

    <asp:LinqDataSource ID="LinqDataSource2" runat="server" ContextTypeName="DataClassesDataContext"
        Select="new (OrderID, ProductID, UnitPrice, Quantity, Discount, Order)" TableName="Order_Details"
        Where="OrderID == @OrderID">
        <WhereParameters>
            <asp:ControlParameter ControlID="GridView1" Name="OrderID" PropertyName="SelectedValue"
                Type="Int32" />
        </WhereParameters>
    </asp:LinqDataSource>

This is part of the classic Master/Details scenario where the LinqDataSource fetches the Order Details based on the OrderID selected in the GridView1.

When the page loads the first time, the OrderID ControlParameter is equal to GridView1.SelectedValue.  GridView1.SelectedValue is null since no record has been selected in the GridView1 yet.  Unfortunately,  the LinqDataSource still attempts to fetch the data. The Linq expression parser treats the null  parameter as type Object and the comparison fails because it was expecting type Int32.

What we need here is a way to prevent the Select from occurring when any parameter is null.  The LinqDataSource, unlike the SqlDataSource, for some reason, does not have a CancelSelectOnNullParameter property. This property when set to true, will cancel the select when any parameter in the SelectParameters collection is null.

We can implement this by handling the Selecting event of the LinqDataSource and call the Cancel method when any WhereParameter is null like so:

    protected void LinqDataSource2_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        foreach (KeyValuePair<string, object> kvp in e.WhereParameters)
        {
            if (kvp.Value == null)
            {
                e.Cancel = true;
                return;
            }
        }
    }

 

2. Operator '==' incompatible with operand types 'Guid' and 'String'

This exception occurs in cases where a parameter in the WhereParameters collection is of type Guid.

    <asp:LinqDataSource ID="LinqDataSource2" runat="server" 
        ContextTypeName="DataClassesDataContext" 
        Select="new (DummyID, FirstName, LastName)" TableName="DummyTables" 
        Where="DummyID == @DummyID" onselecting="LinqDataSource2_Selecting">
        <WhereParameters>
            <asp:ControlParameter ControlID="GridView1" Name="DummyID" 
                PropertyName="SelectedValue" Type="Object" />
        </WhereParameters>
    </asp:LinqDataSource>

In the snippet above, you can see that the GridView1.SelectedValue is defined as a WhereParameter for the LinqDataSource. DummyID is the primary key of the data in GridView1 and is of type Guid. In the ControlParameter, its Type is set to Object because Guid is not available in the TypeCode enum. Unfortunately, this results in the linq expression parser treating the value as type String causing the comparison to fail.

According to the Dynamic Expression API, a flavor of which is used by the LinqDataSource internally, we can perform explicit conversions using the syntax type(expr) where type is a type name optionally followed by ? and expr is an expression. The expression language defines the following primitive types:

Object Boolean Char String SByte Byte
Int16 UInt16 Int32 UInt32 Int64 UInt64
Decimal Single Double DateTime TimeSpan Guid

The primitive types correspond to the similarly named types in the System namespace of the .NET Framework Base Class Library. You can also use the nullable form of a value type by writing a ? after the type name (ex: Where="Foo = Int32?(@Foo)").

Therefore, we can rewrite our where clause like so which gets rid of the exception.

    <asp:LinqDataSource ID="LinqDataSource2" runat="server" 
        ContextTypeName="DataClassesDataContext" 
        Select="new (DummyID, FirstName, LastName)" TableName="DummyTables" 
        Where="DummyID == Guid(@DummyID)" onselecting="LinqDataSource2_Selecting">
        <WhereParameters>
            <asp:ControlParameter ControlID="GridView1" Name="DummyID" 
                PropertyName="SelectedValue" Type="Object" />
        </WhereParameters>
    </asp:LinqDataSource>

IMO, both these exceptions and a couple of others could probably be avoided if the LinqDataSource had a CancelSelectOnNullParameter and if the  TypeCode enum had included the primitive types listed above and nullable value types.

Comments are always welcome!

Posted by rajbk | 6 comment(s)
Filed under: , ,

The .NET Framework 3.5 Commonly Used Types and Namespaces poster

Paul Andrew has posted a link to the .NET framework 3.5 commonly Used Types and Namespaces poster - cool stuff!

Download it here

 

Daniel Moth also has a good older post on the .NET 3.5 bits
 

Posted by rajbk | 1 comment(s)
Filed under: ,

Classic Menu UI in Office 2007

So my 65 year old neighbor called me yesterday because he was frustrated with the Office 2007 Ribbon on his brand new machine...

After googling around, I found a great add-in for Office 2007 by Patrick Schmid called the RibbonCustomizer. It comes in two versions - the free Starter Edition and the Professional edition. Both versions, in addition to customizing the Ribbon, give you a "Classic UI" tab which emulate the Office 2003 menus and toolbars.

As you can see from the screen captures, it does not replace the Ribbon UI but adds onto it, which, IMHO, lets the user work with a familiar UI and allows them to slowly transition into the new UI.

For a core product like the Office Suite, Microsoft should have provided this ability by default.

My neighbor couldn't be happier...

Posted by rajbk | 6 comment(s)
Filed under: , ,
More Posts Next page »