Friday, November 6, 2009

Code: Windows Server 2008 R2 and Microsoft Message Queuing (MSMQ)

We’re nearing the end of a large development project in which we used MSMQ extensively.  All of our queues are private and transactional.  For the most part MSMQ works great and serves its purpose excellently.  Save one glaring issue: We have had serious issues trying to send messages to the queues from remote machines.  All of the machines are in the same domain (and location).  We’ve had the environment set up on 3 different machines (for various reasons).  The first two installs we seemed to be able to post to the queues, although it took many tries changing security permissions on the queues and changing connection string formats (TCP vs OS).  On this 3rd environment we have been totally unable to send messages to the queues from a remote machine.  The messages get eternally stuck on the sending machines outgoing queue.  In the end we believe it to be an issue with the security lockdown of Server 2008 R2.

To get around the issue we had to install MSMQ HTTP Support and send the messages over HTTP.  To do this IIS must be already installed.  Then go into Features and enable Message Queuing > Message Queing Services > HTTP Support.  This will install a MSMQ Virtual Directory/Application on the default web site.  After that we just needed to change the connection strings to below and now things work great.

Code Snippet
  1. FormatName:DIRECT=HTTP://$/transcodejobqueue

Monday, November 2, 2009

Code: C# Hide Properties When Returning to Web Service

The automatic serialization built into the .Net Framework makes life easy when creating web services because it allows you to just return an object (or list of objects) and the framework will handle generating the XML return structure.  In the case where you have a property on an object that you don’t want returned in your web service method, you can add an an XmlIgnoreAttribute attribute to the property.

Code Snippet
  1. public class ReportInfo
  2. {
  3.     public string Title;
  4.     public decimal p95;
  5.     public DateParts DateBreakDown;
  6.     public List<ReportBase> Data;
  7.     //don't show this in web services
  8.     [System.Xml.Serialization.XmlIgnoreAttribute]
  9.     public List<TranscodingReportData> TranscodingData;
  10. }

Friday, October 9, 2009

Code: Open Video Player Smooth Streaming ag_e_unable_to_play

If you are receiving the ag_e_unable_to_play or ag_e_network_error while attempting to do smooth streaming using the Silverlight Open Video Player (OVP) you may need to download AdaptiveEdge.xap.  This file does NOT come with the OVP download in the plugins directory.  I'm not sure why this is, especially since their own example.html references it!  I was able to view the source of and download the file from

Wednesday, October 7, 2009

Code: Develop Code in Unit Test Classes

I've never been good at getting myself to write unit tests, its just not fun to write code to test code.  However I've realized today that usually I end up writing console applications to test my business objects as I develop them, why not start with this code in a unit test?  That way if you don't come back later to more fully create your tests, at least you have something there.

Monday, October 5, 2009

Code: C# Escaping Curly Braces in String.Format

With the Format() method of String in C#, you use numbered braces to denote replacement positions.  If you want to display braces in your formatted text you need to escape them by entering the brace twice:

String.Format("{{ Go to {0} for help}}", "");

Thursday, October 1, 2009

Code: Silverlight Video Player Not Displaying In Firefox

I ran into an issue today where the Silverlight video player on my web page would display in IE and Opera but not Firefox or Chrome.  The issue is with how the browsers handle the height and width specifications on the object tag.  If the html item that contains the object tag does not have a height specified in pixels, then the object tag must.

So changing my code from

<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" 
width="100%" height="100%" id="slp">


<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" 
width="400px" height="400px" id="slp">

resolved the issue.

Tuesday, September 15, 2009

Code: Handling SQL Command Timeout Errors

Unfortunately there is not an exception object in .Net that corresponds directly to a command timeout.  However you can specifically handle one by checking the Number property on the exception.  The number for an SQL Exception happens to be –2 (Using reflection you can see the TdsEnum in System.Data.SqlClient).

catch (SqlException ex)
//Sql time out exception number is -2
if (ex.Number == -2)
//timeout exception, tell user to try changing params
lblTimeOut.Visible = true;
throw (ex);

Code: Setting Command Timeouts using Data Access Application Blocks

When doing database work in .Net you can set a timeout value in your connection string.  This timeout specifies the length of time (in seconds) to wait for a connection to the database server to be established.  If you want to specify a timeout value for your stored procedure in SQL command to complete, you need to set the time out on your command object.  If you are using Enterprise Library’s Data Access Application Blocks your code should look similar to below

Database db = DatabaseFactory.CreateDatabase("ConnectionStringName");
using (DbCommand cmd = db.GetStoredProcCommand("StoredProcedureName"))
    cmd.CommandTimeout = 60;
    int rowsAffected = db.ExecuteNonQuery(cmd);

Tuesday, September 8, 2009

Code: ASP.Net MVC Maintain Checkbox State

Below is a quick and dirty way to maintain a check box checked state during postbacks with MVC:

<%= Html.CheckBox("IsSecure", (Request.Form["IsSecure"] ?? string.Empty).Contains("true"))%>

Code: ASP.Net MVC SelectList / DropDownList Selected Item

I spent an hour on a strange issue on my MVC page the other day where MVC would not obey my SelectedItem assignment on a drop down list.  I originally thought the issue was how I was making the assignment in code, or the object I was using to do the binding, but it turns out that some built in MVC functionality was actually working against me.  If you name your ViewData key name the same name as your Html.DropDownList item, MVC will attempt to populate the selected value for you.  However I wanted to manually set the selected value so my solution was to change this:
<%= Html.DropDownList("Encoding", ViewData["Encoding"] as SelectList)%>

<%= Html.DropDownList("Encoding", ViewData["EncodingData"] as SelectList)%>

And in my controller I just needed to change the ViewData key name accordingly:
Dictionary<string, string> pushPull = new Dictionary<string, string>();
pushPull.Add("pull_encode", "Pull");
pushPull.Add("push_encode", "Push");
if (pushPullValue == "") pushPullValue = "pull_encode";
ViewData["EncodingData"] = new SelectList(pushPull, "Key", "Value", pushPullValue);

Friday, August 21, 2009

Code: TSQL Select unique data

SELECT   Top(5) *
FROM [Reports].[Reporting].[ReportTracking]
WHERE ReportTrackingId IN
SELECT MAX(ReportTrackingId)
FROM [Reports].[Reporting].[ReportTracking]
WHERE UserId = 41603
GROUP BY ReportName
ORDER BY ReportTrackingId DESC

The SQL above can be used as a basis when you need to select data from your database that needs to contain only unique values for a particular column.  The inner query will retrieve the newest primary keys based on your unique column and the outer query grabs the entire row for that primary key.

Thursday, August 20, 2009

Code: 'Type' was not expected. Use the XmlInclude or SoapInclude attribute

I received the following error today while developing a web service:

System.InvalidOperationException: The type <CLASSNAME> was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically. 

This error was thrown because I was attempting to return an inherited class as a web service response.  There are a couple ways around this issue.

1. (My fix) Return the base class instead of the inherited class (obviously not always an option)
2. Add XmlInclude attributes to your BASE class as such:

3.  Write your own serialization code.

Wednesday, August 19, 2009

Code: jQuery $ is not defined

If you're using jQuery and you encounter an error that says $ is not defined it means that you are attempting to call a jQuery method before the jQuery .js file has been referenced. Make sure that your <script src=".."> reference tags are BEFORE any jQuery methods. This can also occur if your url to the .js file is incorrect or if the file can't be accessed due to security permissions.

Tuesday, August 18, 2009

Code: Enabling 32 bit builds in IIS 7 64 bit

I ran into a new error today:

Could not load file or assembly 'ClientPortal' or one of its dependencies. An attempt was made to load a program with an incorrect format.

Turns out it was caused by referencing a 3rd party assembly built for 32 bit, on my 64 bit machine.  The fix was easy once I found it.  Just need to open IIS Manager, right click on the application pool that is hosting the web site, and click Advanced Settings.  Then change "Enable 32-Bit Applications" to True.


Monday, August 17, 2009

Code: Use CSS to hide items instead of jQuery's ready method

if you are using $(document).ready() to hide items, it can cause the items you hide in that method to be shown for a short time before the method is executed, causing a flicker on the users screen.  To avoid this use style="display: none;" to make your item hidden.  Using visiblity:none won't work, when you call .show() jQuery won't override the style.  If you need to call a JavaScript method to determine if the item should be visible or not, set the display to hidden and then call your JavaScript method.  Its better for items to be hidden and then pop in than to have them display and pop out.

Friday, August 14, 2009

Code: Use Firebug to Fix CSS Issues

Firebug came in handy today when I couldn't figure out why Firefox wasn't honoring my table padding markup, luckily the culprit was easy to track down with Firebug.  Just click the element selector button (highlighted in red in the picture), and click on your item.  All of the CSS classes that are currently being applied to it show up in the right column and you can scroll through and find the style sheet and class that is causing your issues.

Thursday, August 13, 2009

Code: SQL Dynamic Where Clause

Select ProductID, Name, Color, Size
From Production.Product
Where (Color = Coalesce(@Color, Color) or (@Color is null and Color is null))
And (
Size = Coalesce(@Size, Size) or (@Size is null and Size is null))

The SQL statement above works against the AdventureWorks database included with the SQL Server 2008 express download.  It’s not unreasonable to want your stored procedures to play well with your user interface, it makes the whole development process a little nicer.  So if you have a web page or windows form that has a handful of options a user can specify to filter data, using a dynamic where clause will prevent you from using string concatenation to build your query.  If you were to pass ‘blue’ into this query as the Color parameter and Null as the Size parameter, the query will return all Products with the color blue regardless of value (or null value) in the size column.

However the query can be simplified if your columns do not contain null values or if you don’t want data returned if it does contain a null value, just remove the or statements as seen below
Select ProductID, Name, Color, Size
From Production.Product
Where Color = Coalesce(@Color, Color)
Size = Coalesce(@Size, Size)

Similarly, if you want your query to match every parameter as passed in, retrieving null values only when you pass in a null for the parameter modify it like this
Select ProductID, Name, Color, Size
From Production.Product
Where (Color = @Color or (@Color is null and Color is null))
And (
Size = @Size or (@Size is null and Size is null))

Wednesday, August 12, 2009

Code: Prevent an asp:Button from doing a postback

<asp:Button ID="btnRunRecent" runat="server" Text="Generate" 
OnClientClick="RunMyMethod(); return false;" />

If you want to run a JavaScript method on a button click for a richer client experience you’ll need to add an attribute for OnClientClick to your asp:Button.  When it renders the actual html input tag to your web page it will add an onclick attribute and set your JavaScript to its value (onclick=”RunMyMethod(); return false;”)   Just place the name of your JavaScript method as the attribute value to allow the page to postback after running your script, if you don’t want the form to do a postback after finishing your script follow your method name with “return false;” as shown in the example.  If you don’t want any custom JavaScript function to run and just want to prevent the button from causing a postback just put “return false;” as the OnClientClick value.

Tuesday, August 11, 2009

Code: Use jQuery to Bind an Event Handler to a DropDownList

<script type="text/javascript">
function EnableControls() {
$(document).ready(function() {
$("select#<%=ddDateType.ClientID %>").change(EnableControls);

If you haven’t yet spent time to learn what jQuery can do for your site, then I highly recommend you do.  Its benefits may seem trivial at first glance, but once you start digging in, its flexibility is very useful.  When the page loads (client side load, not to be confused with the Page_Load server event), jQuery will tell the DropDownList "ddDateType" that it should call the javascript method "EnableControls" when the selected value changes.  This comes in handy if you need to show/hide other controls (there’s also a jQuery method for that) or do some AJAX work (there’s also a jQuery method for that).

Monday, August 10, 2009

Code: Parse Query String Outside of a Web Page

NameValueCollection queryString = HttpUtility.ParseQueryString(myQueryString);
string myId = queryString["myid"];

There are many reasons why a person would want to parse a query string outside of a web page. In order to accomplish this in C# .Net you can use the System.Web.HttpUtility.ParseQuerystring() method. One thing to note however is that you should not pass a full URL, it expects the query string only (everything starting with the "?").

Source: MSDN

Sunday, August 9, 2009

Code: Capitalize first letter of every word in a string

Microsoft.VisualBasic.Strings.StrConv(item.Name, Microsoft.VisualBasic.VbStrConv.ProperCase, 0);

The string class in C# has built in methods for making all characters in a string upper or lower case, but nothing to capitalize the first letter in every work. However there is a method in the Microsoft.Visualbasic namespace that will do the trick. Just add a reference to Microsoft.VisualBasic and use the code above.