Sunday, May 15, 2011

And one time, at Code Camp…

Yesterday, I was privileged to attend the 3rd annual Chicago Code Camp. It was a great opportunity to sit under some very bright professionals and soak in some knowledge, and I’m very thankful to the organizers and sponsors for putting a ton of time, effort, and money into a free community event. I’m cataloguing some of the highlights from the sessions I sat in on.

Test-Driven Development – Tips, Tools & Techniques – Keith Burnell

TDD is one of those things I know I should be doing, but every time I start I find myself hitting this wall of fake objects and can’t help feeling like I’ve made up a bunch of stuff and haven’t actually done anything real or worthwhile. I like opportunities like this to hear other’s successes and tutelage. Here’s a few takeaways:

  • Use a ReSharper template to create an Arrange…Act…Assert for unit tests
  • There should be no external dependencies tested. Disconnect the network cable, detach the DB.
  • A Dependency Injection framework would be really helpful in mocking out those external dependencies as it makes it easy to globally swap instances of an interface in the unit test project.
  • Should Assertion Library – A tool that makes Assert statements a bit more readable by via extension methods.
  • The ReSharper Test Runner is over 3x faster than the built-in Visual Studio runner.
  • When writing integration tests, use the TransactionScope to populate data for the test and then roll it back.

Thanks Keith for a copy of Roy Osherove’s The Art of Unit Testing!

Continuous Learning – Marc Temkin

As someone who loves to learn, I was very excited about this session. I consider myself strong in this category and was looking for some great method to absorb content faster and better. It came up quite a bit short of expectations as much of it was pretty elementary. There were a couple things I took away though:

  • Marc talked about evaluating books by looking at the table of contents, the index and one random page. This helps us get a good sampling of what its about instead of focusing too narrowly and sinking time into reading excerpts we find interesting, and missing what it’s all about.
  • This session really helped shape my decisions for the sessions I would visit the rest of the day. I decided to use this day to take opportunities I don’t normally otherwise get and to learn about things I’m interested in, but haven’t dug too deeply.

Code Generation with T4 and Visual Studio – Oleg Sych

This was one of those opportunities I don’t normally get. When I looked into T4 over a year ago, Oleg’s articles kept coming up over and over.

Code Generation Specific Tips

  • Couple tools: the T4 Editor from Tangible Engineering and the T4 Toolbox which is on codeplex.
  • When writing a template, start by hard-coding the template with specific values, then refactor to using the metadata from your data source.
  • For SQL, include the assembly Microsoft.SqlServer.Smo and the namespace Microsoft.SqlServer.Management.Smo.
  • Must be sure to call the Refresh() method in the Smo API or it won’t populate the tables by default.
  • PushIndent(“\t”) and PopIndent() can be used to address formatting the template
  • The @ include directive allows you to include some other template inside another template.
  • A cool trick when sharing templates across teams is to convert a template (say, your Delete stored procedures template) to a helper method, using the <#+…#> syntax. That way, the functions can be stored in source control and each of the teams can than use those functions via include directives to generate the specifics that they need.
  • T4 runs in the devenv.exe process, so in order to debug it, it is necessary to use a second instance of Visual Studio.

General Tips

  • Use the Debug –> Exceptions menu in Visual Studio to set the option to always break on CLR exceptions when debugging. This will ensure that the code breaks whenever an exceptions is encountered, even if it is caught and handled in the code.
  • Database Projects are really powerful. You maintain your Create scripts in the project and when you Deploy, it compares your script against the database you’re deploying to and generates and runs the Alter script for what has changed.

Messaging with nServiceBus – Lee Harold

nServiceBus was something I pretty much knew nothing about.

  • Definition of distributed – “Some other system can make yours stop working”
  • nServiceBus isn’t like an ESB with a central server. It is more like a queue helper.
  • It uses a Pub/Sub model where subscribers register their queues with a publisher.
  • It uses MSMQ by default, but there are adapters that support other queue implementations as well.
  • It serializes to XML by default, but it can serialize to a binary format as well
  • It has a Distributor which can be used to scale to multiple machines. This is on the subscriber end, and is a master/slave model. The master distributor pretty much only handles routing requests to its slaves.

High Performance 2D Graphics in Silverlight – Bill Reiss

I picked this session because there really wasn’t anything else I was interested in. This turned into one of the best sessions of the day. Bill is a Silverlight MVP and a former XNA MVP, so he has a ton of knowledge in this space, and it was very practical.

  • Drop Shadow effects are really poor for performance as they force redraws
  • In the <object> tag in the web page hosting the Silverlight control, there are several params that can aid in debugging:
    • enableRedrawRegions – Shows all the areas of the screen that are being redrawn. Does not work well with GPU acceleration.
    • enableFrameRateCounter – Shows the FPS
    • enableGpuAcceleration – By default, Silverlight relies only on the CPU. This will engage the GPU.
    • enableCacheVisualization – Show all the items on the page that have been cached
  • Use the CacheMode=”BitmapCache” to cache graphics and prevent them from being redrawn constantly. Requires GPU acceleration.
  • Property setters should be wrapped so that they are only set if the new value is different. This prevents IPropertyNotified events from triggering.
  • Also, don’t access dependent properties directly in your properties. For example, don’t just wrap, myTextBox.Text, actually use backing variables as it’s better performance.
  • Text in a ListBox control is vector based, so may want to consider bitmap caching the text instead for better performance. (WP7 built in some of these optimizations)
  • There is overhead when adding or removing elements to/from the visual tree. One trick is to load them all up, but use visibility or opacity to show or hide them.
  • A big part of performance is minimizing redrawing.
  • VS2010 SP1 includes a Silverlight Profiler. Red-Gate ANTS also is a good Silverlight profiler.

Links

Monday, October 25, 2010

WCF, SSL and an F5

Last week, I was asked to help troubleshoot a problem with one of our WCF services. It was an external service that was to be consumed by a vendor. It was necessary to use SSL and on our network we use an F5 Big-IP device for load balancing. The external DNS points to the F5 device which forwards the call on to the appropriate service on the internal server hosting the WCF service. Things get a little tricky with the F5 and SSL. Requests come in to the F5 over HTTPS. The HTTPS request is terminated at the F5 and the decrypted request is forwarded to the internal machine over plain HTTP. How does one configure the WCF service and client when the client needs to send the request over HTTPS, but the service is going to receive it as HTTP?

Here’s the solution I came up with: First, both client and server need to use a basicHttpBinding. On the server side, I set the security mode to “TransportCredentialOnly” for the binding, then set the endpoint address as “http://domain.com/MyService.svc”. On the client side, the security mode for the binding is set to “Transport” and then endpoint address is set to “https://domain.com/MyService.svc”. The key difference being the registration of the client endpoint as https, while the service endpoint listens on http.

The test harness we built was then able to successfully consume the WCF service. The next problem was that the vendor still needed access to the schemas. In order to generate the schema automatically, the httpGetEnabled attribute on the service behavior needs to be set to true. Problem is, if it is set, the auto-generated path to the schema is over http, which would get blocked at the F5 device because it is only expecting secure traffic. If I took the generated path, but substituted https for http I could resolve the WSDL. So, what I ended up doing was as a temporary solution was to download the auto-generated schemas. I updated the references within the WSDL and XSD files so that they all used https to resolve addresses related to our service, then published these files to a “Schema” directory on the web server where the service was running. I then turned off the httpGetEnabled attribute on the service behavior, enabled the httpsGetEnabled attribute and set the httpsGetUrl to the URI for the WSDL I had just uploaded to the “Schema” folder. I fired up Visual Studio and added the Service Reference without issue.

I would’ve liked to have been able to have been allocated to coming up with the permanent solution for the WSDL, but I was reassigned as the immediate need was resolved. I suggested looking into deriving a class from the WsdlExporter that could enforce https for any schema URI related to the service. I don’t know if it’ll work, but it seemed as good a place as any to start.

Friday, September 17, 2010

LINQ Queryable SharePoint Collection

Today I ran into the need to bind the items in a SharePoint list to an asp:ListView control. While it was possible to use the SPListItemCollection as the DataSource for the control, it was made complicated by a "Hyperlink or Picture" column I was using in the list. When returned, that column would return as a single value in the format "{URL}, {DisplayText}". If I wanted to use the SPListItemCollection, it meant my ASCX page would be cluttered with string parsing, instead of a nice, clean <%# Eval("Link") %>.

I decided I would use LINQ to build the collection to bind to my ListView. Doing such, would allow me to move all the string parsing out of the front-end and into my classes. The only problem is that SharePoint collections are not queryable. A quick Google search, took me to a blog post by Asfar Sadewa,
Direct Linq to SPListItemCollection. Then I thought, why not make this generic so that it can be applied to all SharePoint collections? Below is the result:

public class QueryableSharePointCollection<C, T> : List<T> where C : SPBaseCollection
{
public QueryableSharePointCollection(C sharepointCollection)
{
this.Clear();

foreach (T item in sharepointCollection)
{
this.Add(item);
}
}
}

Now I just have to instantiate a new QueryableSharePointCollection, specifying the collection type, and the type of the items in the collection, and I have a queryable collection derived from a SharePoint collection.

Wednesday, June 30, 2010

AppFabric of Our Lives

A couple weeks ago, I was assigned to a project creating the cross-cutting concerns in our new software architecture. Specifically, I was tasked with the caching aspect. As I searched for distributed caching solutions, I came across "Velocity", a Microsoft solution. As it turns out, Velocity is now a production release, part of the Windows Server AppFabric. I've spent the last few days setting up a virtual machine with AppFabric as my "cache cluster" and writing some tests against it. Here's some thoughts:

  • The server-side installation is very streamlined. Much of the configuration is done after the fact through Powershell cmdlets, which I actually really like.
  • When using Powershell to configure AppFabric, it must be run with elevated privileges, aka Run as Administrator. My account is a domain admin, but I kept receiving InvalidOperationException when I tried to use the Start-CacheCluster command.
  • I looked through the MSDN documentation on how to set the size of the cache, and came across this: http://msdn.microsoft.com/en-us/library/ee790935.aspx. The Powershell commands listed for Cache size, Low watermark and High watermark under the Host Settings header are actually incorrect in the article. The correct commands are Get-CacheHostConfig and Set-CacheHostConfig.
  • I played with adjusting the cache size and was actually able to adjust the size to more than the physical memory available on the machine. My guess is that it will just consume virtual memory after the physical memory is exhausted. The architects on my project were concerned with cost of physical hardware, so this may be an interesting compromise. I'll have to evaluate with some load testing.
    This is actually an incorrect assumption. Per Microsoft, you are allowed to configure the size past the physical memory in anticipation of growth, but AppFabric will throttle it back to the physical memory available.
  • I noticed quite a bit of overhead on an object's size in the cache. I was pulling back a 350kb object (according to Fiddler) and seeing the cache size increase 560kb when it was added. I plan to follow up on this to see if I can determine what makes up the difference.
    Per Microsoft, there should be about 500 bytes of overhead per object stored in the cache. I believe my results were due to the object being returned from our WCF service being significantly larger when hydrated as opposed to the serialized data coming across the wire.
  • Implementing caching in code is straightforward and intuitive with the AppFabric API.
  • Performance is pretty great. I was able to pull 150 of those 350kb objects from the cache in the time it took to pull the 151st object from the service (although, maybe that says more about our ESB).
First impression: Windows Server AppFabric is pretty killer. If you're looking for a distributed caching solution, it's definitely worth a look. Check it out!

Wednesday, June 23, 2010

Ke Nako

It's time. The slogan of the 2010 World Cup is fitting for this my first ever blog post. I've always enjoyed reading blogs. Lord knows how many times someone's blog post has solved a particularly difficult issue I've spent hours googling. So, why have I never blogged? I guess I've never felt like I had anything worth sharing with the world.

I had lunch with a coworker today and we had a discussion that changed my mind. He made reference to a post Scott Hanselman put up this week, Do They Deserve the Gift of Your Keystrokes. I read through that post and the couple other posts he linked, and I have to say I'm pretty much sold. The gist is that we have a finite number of keystrokes with which to communicate in our lifetime. How much of those will be wasted communicating useful information to only a few people through email? I often find myself disseminating the same instructions to different people over and over. Better to post it in a central place that I can direct people to while cataloging the cool stuff I'm learning.

I'm actually pretty fired up to join the community. I've had lots of interesting concepts to look into already this week: OData, aspect-oriented programming, and Windows Server AppFabric to name a few Hopefully, I'll have some posts soon with some details about these and more!

So as far as blogging goes: ke nako.

~Josh