Denis Pitcher

Denis Pitcher's Tech Blog
posts - 18, comments - 66, trackbacks - 29

My Links

News

Archives

Thursday, November 03, 2011

Comparison extension method for unit testing

In trying to comparing complex objects to confirm a unit test, I thought rather than going through the hassle of trying to implement IComparable or overriding .Equals that perhaps reflection would be a better means.

A quick google search turned up some useful code that compares via reflection.

This was close to what I wanted but I thought it’d be better to have it available as an extension method and I needed it in vb.net (excuse the horror) so this is what I came up with:

    <System.Runtime.CompilerServices.Extension()> _
    Public Function Compare(Of T)(ByVal x As T, ByVal y As T) As Boolean
        Dim type As Type = GetType(T)
        Dim properties As PropertyInfo() = type.GetProperties()
        Dim fields As FieldInfo() = type.GetFields()
        Dim compareValue As Int16 = 0

        For Each [property] As PropertyInfo In properties
            Dim valx As IComparable = TryCast([property].GetValue(x, Nothing), IComparable)
            If valx Is Nothing Then
                Continue For
            End If
            Dim valy As Object = [property].GetValue(y, Nothing)
            compareValue = valx.CompareTo(valy)
            If compareValue <> 0 Then
                Return False
            End If
        Next
        For Each field As FieldInfo In fields
            Dim valx As IComparable = TryCast(field.GetValue(x), IComparable)
            If valx Is Nothing Then
                Continue For
            End If
            Dim valy As Object = field.GetValue(y)
            compareValue = valx.CompareTo(valy)
            If compareValue <> 0 Then
                Return False
            End If
        Next

        Return (compareValue = 0)
    End Function

 

Calling it then became a simple

Assert.IsTrue(ObjA.Compare(ObjB));

Posted On Thursday, November 03, 2011 3:40 PM | Feedback (0) |

Wednesday, September 30, 2009

WCF Best Practices: Generated of referenced WCF proxies?

 

The debate has risen of what the best practice is for WCF proxies, should they be generated using Visual Studio references pointing to a WSDL or should they be hand coded and shared alongside service and data contracts through libraries?

Now, admittedly of course using the WSDL option is the instant preference for WCF services that have the potential of facing non .net clients, but what about those who for all intents and purposes will likely forever be consumed by .net clients?

Yavor Georiev from Microsoft suggests on an MSDN forum

You should avoid this if practical in your case, since to maintain interoperability the service and client should only share their contracts in the form of  WSDL, and not the internals of the particular programming language (like classes and interfaces).

However Brian Noyes from IDesign (Colleague of Juval Lowy who wrote the book on WCF) suggests in a presentation on WCF Best Practices:

Hand-code or micro-code generate proxy classes for internal services

  • Less bloated code
  • Share service contract and data contracts through
    libraries
  • Explicit control over config file

Subsequently IDesign’s WCF Coding Standard written by Juval Lowy suggests under section 2. Essentials:

10. When using a tool such as Visual Studio 2008 to generate the proxy, do clean up the proxy.

11. Do not duplicate proxy code.  If two or more clients use the same contract, factor the proxy to a separate class library.

 

So, thus far it seems like the clear best practice is to generate the proxies via the WSDL if you intend to maintain interoperability but be sure to clean them up each time they’re generated.

If interoperability is not a concern then it is an option to share the contracts and proxy through a shared library, especially if more than one client uses the same contract.

Disagree?  Feel welcome to comment and share your sources and reasons as to why.

Posted On Wednesday, September 30, 2009 8:55 PM | Feedback (1) |

Wednesday, June 17, 2009

TFS Rollbacks: An easier way

After a couple painfull rollbacks of TFS checkins I dreaded doing so again with TFS Powertoys or individually checking out specific file versions one by one.

This time I found a much easier trick.  Open up the Team Explorer for source control, browse to the root directory of your project and do a get history.  This gives you the history going back of all files checked in under that directory.  Note the changeset you want and then do a get specific version of that directory.  Suddenly all of your files are back to that changeset version.  The only problem is that you still need to check out the files you want to update, but at least it saved a bit of hassle.

Posted On Wednesday, June 17, 2009 8:00 PM | Feedback (3) |

Wednesday, October 08, 2008

SOA Design Patterns

Just wanted to note what looks to be an interesting book on SOA related design patterns

http://www.soapatterns.org/default.asp

 

Unfortunately the book won't be released until later this month but it's written by the editor of a leading SOA magazine so it looks like it is worth checking out.

Posted On Wednesday, October 08, 2008 9:57 AM | Feedback (0) |

Tuesday, October 07, 2008

WCF Socket Connection aborted due to DBNull

I've been delving a fair bit into WCF lately and have been encountering enough gotchas that it is clear that it's time for me to resurrect my tech blog.  My first post: an errant WCF Socket Exception which looks like a timeout due to the message is actually an exception caused by DBNull.

 

image

You may have come across the above msg at some point in working with WCF.

The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:30'.

Oddly however, none of my binding config settings actually set a timeout of 30 seconds and even more oddly, the message appears almost instantly.

After a tremendous amount of hassle, it was only through some testing that I discovered that a database query in my data access service was returning an unexpected DBNull for a function which when called by my client caused it to abort the socket connection without giving me any details as to why.  On the service side it looked like everything was perfect while the client side blew up with what looked like a timeout.

Moral of the story?  If you get something that looks like a timeout, check the data source first.

Posted On Tuesday, October 07, 2008 11:54 AM | Feedback (2) |

Friday, May 11, 2007

Disappointment with OneNote

A few years back when OneNote first came out I gave it a try.  I was excited by it's features but it was lacking one major feature, the ability to link between pages in wiki style.

With the release of OneNote 2007, this was one of the promoted features and one that I most looked forward to.  Another feature I was looking forward to was the ability to integrate with Sharepoint to share documents.

Upon installing and trying OneNote, I was very pleased with it's interface and the ability to link documents with Sharepoint, up until I asked a colleague to try it out.   He visited sharepoint and tried to view a document which prompted him to download onenote.  This seemed quite bizarre that sharepoint, if integrated with Onenote, wouldn't have some kind of built in viewer so I went hunting for one.  It turns out that Microsoft has no intention of releasing a viewer for onenote and suggest that you download the trial.

To me, this seems incredibly rediculus as I was about to try to convince my entire organization to take on one-note and sharepoint for our document management and this one issue will likely be the stopping point for being able to convince anyone to take it on.

Why does Sharepoint not have an integrated ability to view OneNote files?  I know you can upload HTML from OneNote, but this is only one page at a time which seems pointless.

Also, why would MS intentionally not release a viewer?  

Might as well just stick with a traditional wiki because at least anyone with a web browser can view it.

Posted On Friday, May 11, 2007 8:06 AM | Feedback (3) |

Sunday, February 04, 2007

Wiki based source code editor?

Can you help me find:

A collaborative development platform that is based upon a wiki.   For example, classes are laid out in pages. Function references map as links when you write them and link to that function's location.   You can check in and out portions of the code and submit them for approval.  Changes are kept via versioning with the latest approved versions being group together as builds.  The entire project then being recompiled on a scheduled basis to create a release.

If this doesn't already exist, are you willing to help me build it?

Posted On Sunday, February 04, 2007 5:04 PM | Feedback (1) |

Wednesday, January 24, 2007

SQL Server Wish List

As I jump back into some SQL Server development, I've come across a couple things that I wish were features in SQL Server.

One is that when developing many stored procedures or functions, it has always been a pet peeve of mine that SQL Server basically lists every one together.  This is a bit cumbersome as if you are developing functions for a specific purpose, you are unable to group them together (except by schema, which is not what I'm looking for) so that it is easier to find them later.  A simple sub categorization based upon creating sub folders in the function folders would be an ideal and simple solution.

The other thought I'd like to express is the inability to create global variables.  There are times when one would like to be able to set global constants to be utilized in multiple procs/functions so that if they ever need to change you only have to change one spot rather then every sproc/function.  I'm uncertain as to why this design component was left out however I can at least make do with the workaround of creating a parameterless function to act as the constant by naming it and having it return the desired value, that way I only need to change the function to impact all sprocs/functions that call it.

Less then ideal, but it'll do.  Hopefully with the next upgrade, Microsoft will consider the usefulness of these suggestions.

Posted On Wednesday, January 24, 2007 2:59 PM | Feedback (3) |

Wednesday, January 03, 2007

UDF support in Excel 2003 with VSTO .net

I'm in the process of figuring out how to migrate an old VBA based Excel Add-in to VSTO .net

Quite unfortunately, UDF function support in Excel is critical for the add-in I'm updating and yet it is not supported in the present version of VSTO nor will it ever be with Excel 2003.

Thus, I'm stuck figuring out a means around the issue.

After a great deal of digging, I found a means to create VBA code from within .net and add it when the runtime loads.  A great summary of how to do this is available here:  http://blogs.msdn.com/pstubbs/archive/2004/12/31/344964.aspx

The issue, however, is just as Paul outlines being that you then have to deal with 2 different security models, both .net and VBA Macros.

I believe after much frustration I have overcome the hurdle of deploying my VSTO code with the correct security of being able to install and run the add-in.  What I am now left with, is how to overcome the security constraints related to dynamically loading VBA macros from within a VSTO addin.

Any tips, thoughts, suggestions would be greatly appreciated on good resources or solutions for configuring macro security from within VSTO.

Thanks

Posted On Wednesday, January 03, 2007 1:28 PM | Feedback (1) |

Wednesday, December 06, 2006

Visual Studio Tools for Office 2003???

I'm at one of those points where I want to jump up and down, scream, rant and rave all while shaking my fist at the sky cursing Microsoft.

All I'd like to do is something that I thought would be simple.  I came across a couple great articles on how to use Visual Studio Tools 2003 for Office to integrate .net with Office applications such as Excel. 

It took me an hour of hunting, however, to discover that apparently those tools are only downloadable via an MSDN subscription.  Thanks Microsoft, for not mentioning this on the Visual Studio Tools for Office website.

So what do I do?  Well I go to MSDN, and after another 45 min of searching, I still can't find where to download it from.

Could someone please save me from the misery that is Microsoft's incomptence at making things easy and please provide me with a link of where I could download this?

Brief update: 

      I finally found it.  I'd like to suggest to Microsoft, if they ever read this, that it is absolutely useless to have to look through every language version of a product when going through the subscriber details on the MSDN subscriber download site.  Here's a thought:  How about you provide a filter to select the language you want rather then sift through 500 results of every language known to man?

Another update:

      Now I'm having difficulties actually downloading it!  Every time I click on the link, that stupid gold confirmation bar comes up asking that I install Microsoft File Transfer Manager 5.0 ActiveX plugin, however, when I click install, it jumps away from the page and ends up doing nothing!  - I hate Microsoft sometimes.

      So, if it won't download without that plugin, and I've googled the plugin and can't find where to download it independently - now what do I do?

 

      

Posted On Wednesday, December 06, 2006 1:39 PM | Feedback (4) |

Monday, May 22, 2006

The SqlTransaction has completed; it is no longer usable

Ok, felt this bug was worth noting.

I'm maintaining some code that was originally written to utilize a sql connection code generator called bonebox.  I was notified of an error that occured where a few reports that were running were timing out.  Upon reviewing my log messages I discovered that the sql server appeared to be blocking during connection attempts.  (as a side note: I was informed later that another application I'm not responsible for was stuck and was eating up most of the processing power of our sql box)

So I proceeded to run an sp_who2 sproc on my sql database to watch the number of connections that were being made.  I noted that there were a rediculus number of connections, some 150 from just one copy of my application.  This seemed like an absolutely rediculus number of connections for a single instance of an application.

So, I proceeded to go through the code of the generator and I made a few changes.  Wherever a connection was implicitly opened, I closed it when it appeared the code would be finished with it.

I also changed some DataReader commands from

cmd.ExecuteReader(CommandBehavior.Default);

to

cmd.ExecuteReader(CommandBehavior.CloseConnection);

Primarily because a DataReader does not close connections when it's finished unless you add this parameter (apparently in my reading it was suggested that even when specified, it may not close it, but I did not encounter this in my efforts)

So, after re-runing my report and checking the sp_who2 sproc on my sql box, I happily noted that there were at most 3-4 connections now where there used to be 150. 

A job well done... or so I thought.

Shortly thereafter I was notified of an error that occured during the processing of a different part of the application that utilizes transactions to save a bulk of data.

The error that was thrown:

The SqlTransaction has completed; it is no longer usable

Googling and searching yielded little help on this issue as most of the suggestions I could find didn't relate to my problem.  Seeing that the only recent change I had made was the closing of connections, I assumed that this must be the cause of my error, I just didn't know where to go to solve it.

After much digging and putting a watch on the transaction as it passed through various methods, I noted that the IsolationLevel property of the transaction was displaying the following message after a few operations

IsolationLevel <error: an exception of type: {System.InvalidOperationException} occurred> System.Data.IsolationLevel

So after too much line by line debugging, I realised that the connection shouldn't be closed during the operation of a transaction or it probably would invalidate it, which would explain the transaction completed error.  So, I went back through my code and added checks to determine whether or not a transaction was in use, if so, I left the connection open, if not, I closed it.

Example:

if ( trans != null )
{

cmd = new SqlCommand("select Scope_Identity()", conn, trans);
reader = cmd.ExecuteReader(CommandBehavior.Default);

}
else
{

cmd = new SqlCommand("select Scope_Identity()", conn);
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

}

...  and at the end of the method when finished with the reader ...

reader.Close();

if (conn.State == ConnectionState.Open && trans == null)

conn.Close();

 

Finally, I set the connection to be closed when a transaction is committed to ensure that connections arn't left open and I run into pooling issues when I've got multiple users trying to use the application at once.

In summary, it's been a pain in the butt to track this one down and I'm hoping that I've now solved the issue.  I've of course noted it here incase anyone else runs into a similar error and needs to save themselves a few hours of banging their head on a desk

 

Posted On Monday, May 22, 2006 3:50 PM | Feedback (18) |

Wednesday, February 22, 2006

DataGridTextBoxColumn Formatting Bug?

I've been stuck for a while now on a problem where I'm trying to format columns in a datagrid using dynamic column styles (datagridcolumnstyles).

The issue was when I was using the DataGridTextBoxColumn.Format property with a value of “c00“ for formatting the column to display a $ at the beginning of numbers.  It was odd because the first 4 columns would format properly and the rest would revert to no formatting.  The odd thing was that the column styles were being set and I was even able to confirm that the format property was set to “c00“, it just wasn't being picked up.

I got fed up searching for a reason why in my own code that I could not find after stepping line by line through it in the debugger numerous times.

In the end I decided to extend the class and create my own to call rather then bothering to use the .format property at all.

source: http://support.microsoft.com/default.aspx?scid=kb;en-us;318581

Code: 

public class MoneyDataGridTextBoxColumn : DataGridTextBoxColumn

{

protected override object GetColumnValueAtRow( CurrencyManager cm, int RowNum )

{

// Get data from the underlying record and format for display.

//

object oVal = base.GetColumnValueAtRow( cm, RowNum );

if ( oVal == System.DBNull.Value )

return NullText;

else

{

try

{

decimal temp = Convert.ToDecimal(oVal); //(decimal)oVal;

return "$" + temp.ToString("0.00");

}

catch( Exception )

{

return NullText;

}

}

}

protected override bool Commit( CurrencyManager cm, int RowNum )

{

// Parse the data and write to underlying record.

//

HideEditBox();

DataGridTextBox box = (DataGridTextBox)TextBox;

decimal Value;

// Do not write data if not editing.

if ( box.IsInEditOrNavigateMode )

return true;

// Detect the null value string.

if ( TextBox.Text == NullText )

SetColumnValueAtRow(cm, RowNum, DBNull.Value);

else

{

try

{

if ( TextBox.Text.StartsWith( "$" ) )

Value = decimal.Parse( TextBox.Text.Substring( 0, TextBox.Text.Length - 1 ) );

else

Value = decimal.Parse( TextBox.Text );

// Write new value.

SetColumnValueAtRow(cm, RowNum, Value);

}

catch( Exception )

{

// Exit on error and display old "good" value.

return false;

}

}

// Let the DataGrid know that processing is completed.

this.EndEdit();

return true;

}

}

 

Keywords: DataGridColumnStyle, Format, DataGridTextBoxColumn, Bug

Posted On Wednesday, February 22, 2006 5:05 PM | Feedback (1) |

Wednesday, February 15, 2006

DataSet quick viewer

I've been kicking myself repeatedly trying to debug a crosstab class I'm creating, then I stumbled accross this dataset viewer that will help me immensly so I thought I'd make a note of it

Source for this post: http://weblogs.asp.net/rosherove/archive/2004/05/29/144419.aspx

Finally! someone came up with a way to view the contents of a Dataset object while debugging:
The Dataset QuickWatch project allows you to view the contents of a dataset just like the “visualizers” in Whidbey (well, almost. you select the expression, right click it and hit the “Dataset Quick Watch” menu. Same difference)
Sample Image - Article.gif

Posted On Wednesday, February 15, 2006 1:43 PM | Feedback (1) |

Saturday, January 14, 2006

Convert HTML to Wikipedia format

I've been working furiously lately to pull together a few projects of mine that I'm working on.

One thought I've had is to launch a copy of wikipedia locally so that I can consolodate all my ideas, projects and things I'm working on into one place. 

As part of this I've been hunting around to find a means to convert my HTML and Word files into wiki but it's been a pain googling it.  Even searching wikipedia didn't come up with anything.

I finally found a link and funny enough wikipedia had it on their site, it was just a pain to find.

So here it is:  wikipedia conversion - convert HTML to wikipedia.

 

Posted On Saturday, January 14, 2006 10:39 PM | Feedback (3) |

Tuesday, August 16, 2005

System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive.

System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive.

I've been trying to figure out what the cause of this problem is for a few days now and I've finally tracked down the error.

It's due to a bug in .net that closes the connection prior to it being finished.  I'm concerned about the performance issues involved in reconnecting, however I have written my code to keep most connections and data transfer small anyways, I'll have to keep an eye on the performance of this crappy bug.

A good reference for solving this issue is available at: http://p2p.wrox.com/topic.asp?TOPIC_ID=4858

Unfortunately the microsoft KB article that addressed the issue is no longer available.

As suggested I have added the following code to my reference.cs file (which needs to be done each time I update the webservice reference) to assign the keepalive value to false to allow the connection to be closed and reopened.

protected override WebRequest GetWebRequest(Uri uri)
        {
            HttpWebRequest webRequest = (HttpWebRequest) base.GetWebRequest(uri);

            webRequest.KeepAlive = false;
            webRequest.ProtocolVersion=HttpVersion.Version10;
            return webRequest;
        }

I have also added a reference to System.Net via a using statement to import the HttpWebRequest namespace.


Posted On Tuesday, August 16, 2005 2:31 PM | Feedback (62) |

Powered by: