advanced web statistics

So I'm Zuning Now

I've had a Zune for a little while now and am just getting around to the social side of things.  I'm a Microsoft geekboy for life so that's why I didn't get an iPod.

Peep  my uber-cool Zune username and slick Zune Card gadget on the left.

Feel free to add me to your social if you're a Zuner as well. :)

kick it on DotNetKicks.com

Using Converters for Conditional Silverlight Databinding

Yesterday I posed a question about conditional syntax and how one would accomplish this in xaml / silverlight pages & controls.  There were no responses and I'm attributing that to the fact that it is a Friday.  Anyway, after a day of much next-level blog-reading and trial-and-error I have come up with a solution that might not be the most elegant but it works.

I'm going to use a converter utility to provide this functionality.  This will be a class that implements IValueConverter.  This is is an interface that allows one to apply custom logic to a binding which is pretty much what I wanted to do in the first place.

If you are familiar with Scott Guthrie's 8-part series on Silverlight (which is fairly outdated btw with the new release of Beta 2) I will be building on the Digg example from that as that is the most pertinent "Hello World"'ey example I can think of.

So anyone familiar with Digg will know that there is a little box on the left of a story that displays how many diggs a story has.

Digg Example

That screenshot is from the example I built awhile ago following Scott's tutorial.  See how even if a story has 1 or 2 the text below still says "diggs" ?  With the example I will show you can customize that to where if a story has more than 1 digg it will read "diggs" or else it will simply read "digg".  It sounds like a very trivial task (and it kind of is) but not anywhere near as trivial as with ASP.NET.

First add a class file to your SilverlightUI class library and name it something like NumberOfDiggsConverter.cs (what I did).

Here's my class.  It's very important to implement the IValueConverter interface.

using System;
using System.Windows.Data;
using System.Globalization;

namespace SilverlightSandbox.Converters
{
   public class NumberOfDiggsConverter : IValueConverter
   
{
      public object Convert(object value, 
                              Type targetType, 
                              object parameter, 
                              CultureInfo culture)
      {
         return System.Convert.ToInt32(value) > 1 ? "diggs" : "digg";
      }

      public object ConvertBack(object value, 
                                 Type targetType, 
                                 object parameter, 
                                 CultureInfo culture)
      {
         throw new NotImplementedException();
      }
   }

Easy enough.  Notice I didn't check the value parameter for null or anything fancy.  Again, just a quick example and if you use something like this in production you might want to think about something a little better.

Now that we have our converter class we should register it and use it within our xaml user control.

Here is what my xaml looks like.

BEFORE REGISTERING CONVERTER

<UserControl x:Class="SilverlightSandbox.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">  

AFTER REGISTERING CONVERTER

<UserControl x:Class="SilverlightSandbox.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Converters="clr-namespace:SilverlightSandbox.Converters"> 

Now create a UserControl.Resources section. I added mine at the top of my page right before my main grid.

<UserControl.Resources>
   
<Converters:NumberOfDiggsConverter x:Key="DiggConverter" />
</UserControl.Resources> 

The next, and final, step is to actually implement this.  In our case we will set the text property of the digg block to the NumberOfDiggs property of my Digg object.  I'll show the before and after syntax of the # of diggs text block.

BEFORE

<TextBlock Text="diggs" /> 

AFTER

<TextBlock Text="{Binding Diggs, Converter={StaticResource DiggConverter}}" /> 

Here's the final result:

Easy.

kick it on DotNetKicks.com

Is There A Conditional Syntax for Silverlight UI Databinding?

I'm working on a Silverlight 2 project currently and am running into sort of a wall when it comes to databinding.  Without going into too much detail let's take into the consideration that I have the following objects.

List<Foo> list;
Repeater repeaterFoo;

My repeaterFoo's DataSource property is the list above.  Let's say depending on a certain property of Foo that I want to display a 1 or a 2 in my UI.  That's a pretty basic requirement right?

Here's how I would do this in ASP.NET:

<asp:Repeater ID="repeaterFoo" runat="server">
   <ItemTemplate>
      
<%# string.IsNullOrEmpty(Eval("Name").ToString()) ? "1" : "2" %>
   </ItemTemplate>
</
asp:Repeater> 

Now, for the sake of argument (and proof of concept); let's pretend that this example is 100% useful.  How would I accomplish this in Silverlight 2 with it's funky { Binding PropertyName } syntax?

I'm not expecting any simple answer after seeing the dog-and-pony show that is formatting a date / currency in a Grid.

Don't get me wrong, I absolutely love Silverlight so far, it's just kind of frustrating trying to get used to the little things that were oh-so-easy in ASP.NET!

Thanks in advance.

UPDATE
I figured this out. New entry to come soon.

Hint: It relates to the dog-and-pony show I alluded to earlier :(

kick it on DotNetKicks.com

Outlook Doesn't Respond After Latest Windows Update

Just installed a bunch of Windows Updates for my laptop and now I can't send / receive e-mail with Outlook.  After about a minute or so it NOT RESPONDING's out.  It was mostly updates dealing with Office 2007 so I'm guessing something went south.  Needless to say I am uninstalling all of them and turning off automatic updates.

The only difference between now and last night at midnight when I went to bed was that I could send / receive e-mail then and updates were installed in the meantime.

WTF Microsoft?

UPDATE
Restored my system to the point right before installing the updates (thankfully this restore point is automatically created) and my Outlook works as it did before.

I think it's safe to say there was something iffy about this update as it relates to my computer. Weird.

kick it on DotNetKicks.com

LINQ to SQL and Using Multiple Connection Strings

So I found something pretty interesting today in regards to LINQ and LINQ-to-SQL classes.  I was setting up a staging server to deploy a new 3.5 web application.  I then realized, "Oh crap, different connection string!".  This should be easy as all I should have to do is modify the app.config and update the connectionString accordingly. WRONG!

The connection string is actually compiled into the code. That sucks. Here's what I see in Reflector:

[SpecialSetting(SpecialSetting.ConnectionString), ApplicationScopedSetting, DebuggerNonUserCode, DefaultSettingValue("Data Source=(local);Initial Catalog=FooDB;User ID=;Password=")]
public string FooDBConnectionString
{
   get
   {
      return (string) this["FooDBConnectionString"];
   }


Gross.  I thought of a work-around that could work.  This code is in the Settings.Designer.cs class so I could do something like:

public string FooDBConnectionString
{
#if DEBUG
   get { return ((string)(this["FooDBConnectionStringDev"])); }
#else
   
get { return ((string)(this["FooDBConnectionStringProduction"])); }
#endif
}

This way the appropriate connection string could be compiled into the code depending on whether or not the configuration for the project is set to Debug or Release.  The thing about this solution is that you would have to write this code each and every time you regenerate your LINQ-to-SQL class file(s).  Very inefficient. *NOTE* For this to even work you have to add another connection string in your Settings file. No thanks.

The REAL way to solve this:

  1. Create a LINQ-to-SQL dbml file with an initial connection string
  2. Right-click dbml surface
  3. Click 'Properties'
  4. Expand the 'Connection' node
  5. Select 'None' for Connection String
  6. Select 'True' for Application Settings (don't know if this is completely necessary)
  7. Create a partial class for 'YourDataContextHere'
  8. Within this partial class create a parameterless constructor for 'YourDataContextHere'
  9. Set your base connection string accordingly a la:

public FooDB() : base(ConfigurationManager.ConnectionStrings["FooDB"].ConnectionString, mappingSource)
{
   // anything else

Just make sure you have ConnectionStrings node in your app/web configuration files and that you have the specified key in there or this won't work :D

Easy. Now you can throw a different connection string in your Business Layer's configuration file and be good to go.

Thanks to Jon Gallant and David Klein for the initial posts.

kick it on DotNetKicks.com

Elegant Way of Executing a Stored Procedure using LINQ?

I was working in a project today and I was trying to create a generic way of using a DataContext class to execute a stored procedure.  Of course there's the way of dragging a stored procedure onto the designer, etc... but I'm not interested in this at the moment.  TBQH, I haven't even been doing the ORM mapping in this manner lately after using the System.Data.Linq.Mapping namespace to map a POCO (Plain 'Ole CLR Object) to an actual SQL table (as well as using ColumnAttribute's to map the properties to columns.  This is extremely helpful for larger 2.0 projects that were recently converted to 3.5.   Some might argue that this isn't how LINQ was supposed to be used or that it makes it more complicated.   First of all, I don't think that there is any right or wrong way to use LINQ.  Secondly, I find it can be a pain to have to remove the table from the designer, reconnect via Server Explorer, refresh the database, re-drag onto designer over-and-over when making changes to tables, views, procedures, etc...  This is also problematic if you don't have access to a production database from your dev environment.  Most web servers I experience don't have Visual Studio 2008 installed so it's not like I can quickly generate a newer set of LINQ-to-SQL classes.  If a table column name changes, I simply refactor the corresponding property in my library and I'm good to go.

[Table(Name = "dbo.FooTable")]
public class Foo
{
   #region Table Columns / Properties

   [Column]
   public long FooId { get; set; }

   [Column]
   public string FooName { get; set; }

   [Column]
   public string FooDescription { get; set; }

   #endregion Table Columns / Properties

Easy.

public class Database<TDataContext, TEntity>
{
   // ...   
}

Take the previous data access helper class.  Let's say I want to create just a generic function to execute a stored procedure against my database.  Let's call it "ExecuteCommand".

public static void ExecuteCommand(string command, object[] parameters)
{
   if (string.IsNullOrEmpty(command))
      throw new ArgumentNullException("command");

   using (var database = new TDataContext())
      database.ExecuteCommand(command, parameters);

Basic.  The implementation is pretty mindless as well.

Database<MyDataContext, TFoo>.ExecuteCommand("CommandName", null); 

This sucks when you have parameters because I haven't found any documentation on how to execute a procedure elegantly using this approach.  It appears that the DataContext.ExecuteCommand approach is best-suited for on-the-fly dynamic SQL.... gross!  I also read (need to find the link again) that some super-sleuthing uncovered that parameter substitution is silently ignored.  (I'll have to check back on that)

I did find a way to implement using a stored procedure....

string command = string.Format("exec Command '{0}', {1}", "string", 1);
Database<MyDataContext, TFoo>.ExecuteCommand(command, null); 

That is disgusting.  Not a huge fan.  What if you have a procedure that has 5, 10, 20 parameters? Ouch.  What if your input parameters contain ' 's? You would then have to replace all ' with a ''.

Any suggestions?  I'm hoping that there is a much more elegant / succinct way of doing this that I haven't found yet.  I've tried to "RTFM" as they say but a couple thousand pages of LINQ reference books and I've got nothing.

Here's a little 2.0 throwback of what I'm trying to accomplish.  Like I said before, there has to bge a more elegant way of doing this with the 3.5 Framework / LINQ / DataContext that doesn't involve dragging-and-dropping procedures onto the designer.

public static int ExecuteProcedure(List<SqlParameter> parameters, string command)
{
   try
   
{
      using (DBManager manager = ...)
      {
         manager.Open();
         manager.CreateParameters(parameters.Count);

         for (int i = 0; i < parameters.Count; ++i)
            manager.AddParameters(i, parameters[i].ParameterName, parameters[i].Value);

         return (int) manager.ExecuteScalar(CommandType.StoredProcedure, command);
      }
   }
   catch (SqlException)
   {
      return 0;
   }

Help me from the following please!!

StringBuilder query = new StringBuilder("exec Command ");
query.AppendFormat("{0},", foo.FooProperty1);
query.AppendFormat("'{0}',", foo.FooProperty2.Replace("'", "''"));
query.AppendFormat("'{0}',", foo.FooProperty3.Replace("'", "''"));
query.AppendFormat("'{0}',", foo.FooProperty4.Replace("'", "''"));
query.AppendFormat("'{0}',", foo.FooProperty5.Replace("'", "''"));
query.AppendFormat("'{0}',", foo.FooProperty6.Replace("'", "''"));
query.AppendFormat("'{0}'", foo.FooProperty7.Replace("'", "''"));

Database<MyDataContext, Foo>.ExecuteCommand(query.ToString(), null); 

kick it on DotNetKicks.com

SQL 2005 & Full-Text Indexing on Vista Ultimate

I tried to setup a database with full-text indexing today as part of an application I'm working on.  I followed instructions to a T and I received the following error:

Full-Text Indexing Error

Awesome.  The only difference I can think of is that the machine that this was successfully created on happened to be running Windows XP SP2.  I am running Vista Ultimate.

Naturally I started Googling the error only to find nothing really helpful.  It's all speculation.  I just downloaded a 284MB .msi for SQL Server 2005 SP2 since "you have to install SP2 if you are running Vista and you want SQL Server 2005 to work properly."

At this point I'll try anything.  If you have any suggestions, by all means...

UPDATE
I'm awesome.  Not really (yes) but through extensive Google-searching, next-level blogging and waving a dead chicken over my laptop I have finally resolved this.

The culprit was a NTLMSSP (NT LAN Manager Security Support Provider aka NAMBLA)service dependency.  TBQH, I don't really give a shit what it does, all I needed to know is that:

This service has been removed from Windows Vista and Windows Server 2008 in favor of the newer Kerberos authentication protocol.

So, a service is removed entirely from Windows Vista and Server 2008 and a dev team thought it would be a good idea to either a) take it out of the OS entirely or b) make SQL Server 2005 depend on it. That makes perfect sense.

All kidding aside, get to your registry settings by way of regedit.exe or Start -> Run -> regedit and look for:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\msftesql

Remove NTLMSSP and reboot. Easy.  Thanks Tanzim and some dba-type from a Google Groups thread!

kick it on DotNetKicks.com

Visual Studio Find and Replace Wish List

Today I was working on a project that I wasn't all too familiar with.  Instead of asking everyone that I work with who was online at the time I decided to try to figure out on my own by a series of "Go To Definition", "Find Usages" and "Quick Find"'s.

Find & Replace

It would be nice if the "Look in:" selection was a little more detailed than a DropDownList.  Maybe a series of CheckBoxes with nested CheckBoxLists.

I don't know, just thinking out loud.  I'd even be happy with a "Every project in the solution except for the current one" ListItem.

kick it on DotNetKicks.com

Silverlight Beta 2 and Lack of WatermarkedTextBox

Maybe someone can help me troubleshoot this.  I started to follow Scott Guthrie's 8-part series on getting started with Silverlight but hit kind of a wall.  His example used a WatermarkedTextBox which I was unable to add.  I took some horrible screenshots to show how I went about trying to add to my form.

You can clearly see that this is in my Visual Studio 2008 Toolbox.

step 1

Now a horrible attempt to convey dragging and dropping onto my form.  When I typed it out in the designer as Scott did it doesn't work either.  This was my second option as I am usually not a fan of wizard dropping.

step 2

When I drop at that spot I am greeted with this gem:

step 3

Any takers?  I ended up creating my own watermarked-textbox by writing some C# code to handle some of the regular-textbox events.  I'd ultimately like to use these snazzy new features since I figure that's why they are there in the first place :D

UPDATE
I'm having issues with the StackPanel as well when creating a template for a ListBox. It's the same FORMATETC structure deal :(

kick it on DotNetKicks.com

Why Hello There Silverlight!

Silverlight is bad ass! I didn't bother with version 1 because I was under the impression that it was highly premature (aka kludgy).  Coding in C# was more appealing than a bunch of JavaScript.  Anyway, so I downloaded and installed the latest and within minutes I was able to create an application that loaded dynamic data from various interweb API's.  The UI was even kind of decent ;)

One thing doesn't seem right.  In downloading and installing the latest version (which meant uninstalling the previous version) all the examples written prior to this new version don't work anymore.  I get taken to the "Install Silverlight" landing page and see the following:

The site that you visited was built for an earlier, beta version of Silverlight - not the current one. Please contact the site owner to let them know that they must upgrade to the latest release of Silverlight 2. Let us know if the site is not updated shortly so we can try to assist in upgrading the site to the latest Silverlight technology.

Hmmm.  That's kind of scary.  It makes it sound like you are s-o-l if you develop an extensive application with silverlight 2 and all of a sudden a new version is released.  It also sounds as if Microsoft might strong-arm you to upgrade your application quickly!

Silverlight Install Screenshot

I see myself spending a decent amount of time sandboxing and learning the ins and outs of this newer technology.  I was so impressed that I even added a new Silverlight category :D

kick it on DotNetKicks.com

<< Newer Entries Older Entries >>