Showing posts with label development. Show all posts
Showing posts with label development. Show all posts

Wednesday, March 6, 2013

Conversion Operators Pros and Cons

C# enables programmers to declare conversions on classes so they can be converted to and/or from other types. These conversions can be explicit or implicit.

Below is an example from Microsoft:
class SampleClass
{
    public static explicit operator SampleClass(int i)
    {
        SampleClass temp = new SampleClass();
        // code to convert from int to SampleClass...

        return temp;
    }
}
Conversion operators are a great way of simplifying business logic, however they have some important limitations. One of these is that the operator may only have one parameter (the source type). This means that the only values available when the target type is initialized are those provided by the source type and dependency injection cannot be used. It's also worth noting that these conversions will not chain automatically. Declaring conversions from A->B and B->C does not provide a way to directly convert A->C.

This is all fine in theory, but what I find useful in these types of articles are real world examples, so here it is.

We're using Microsoft Service Bus for Windows to pass events between an e-commerce solution based on nopCommerce and a custom back office application. We needed some basic objects to pass relevant information through the bus and did not want to be too tightly coupled to the nopCommerce domain objects. My initial solution was to create classes and implement conversion operators to cast objects from nopCommerce to their POCO counterparts.

In the example below, you can see an implicit conversion operator for the Order class which uses the Shipment conversion operator.
public static implicit operator Order(Core.Domain.Orders.Order o)
{
  return new Order
  {
    OrderId = o.Id,
    Shipments = o.Shipments.Select(x => (Shipment)x)
  };
}
Since we needed to add more information to our Order object than was contained in the version from nopCommerce, I got rid of the conversion operator and created a separate conversion class with the following method:
public Order ToOrder(Core.Domain.Orders.Order o)
{
  return new Order
  {
    OrderId = o.Id,
    Shipments = o.Shipments.Select(ToShipment).ToList()
  };
}
The method contents are nearly identical, however we are now free to inject any dependencies we like in the conversion class constructor and add parameters to the conversion method.

No matter which approach you choose, these are excellent ways to simplify conversion and consolidate code used for creating related types. If you have any suggestions or feedback on this article, please leave a comment below or contact me directly.

Thursday, February 7, 2013

Building E-commerce Sites with MVC

For those of us who have spent most of our careers building business applications, the prospect of creating an e-commerce storefront can be quite daunting. Not only do you have to deal with calculating tax, estimating shipping and accepting payments, but employees need a way to manage products, discounts and marketing content. Thankfully, there's an open source e-commerce solution written in Microsoft ASP.NET MVC named nopCommerce that provides all this functionality and much more.

I was so impressed by both the functionality and the underlying architecture that I've created a presentation which I believe will serve as a great introduction to MVC as well as a tutorial on developing custom storefronts using nopCommerce.

We start off with a brief overview of basic MVC concepts accompanied by examples within the nopCommerce code. This includes strongly typed Razor views, HTML helpers, jQuery ajax calls, and fluent validation.

Once everyone understands how the website works, we dive into the infrastructure by introducing WCF services, using a generic repository with Entity Framework (EF4) and LINQ, as well as Dependency Injection (DI) with Automapper.

If you'd like to schedule this talk for your local user group, either request me through INETA or contact me directly.

UPDATE 7/13/2013
Thanks to the CodeStock crew and everyone who packed the room for my talk. Y'all had some excellent questions and I invite anyone with additional questions to comment below or contact me directly. Also, don't forget to provide feedback so I can improve the talk for next time.

Click here to view the presentation slides.

Tuesday, October 23, 2012

Three Tips for Recruiters

The longer I work in the software development community, the more recognition I get from recruiters as someone who can help them find candidates and the more colleagues that approach me asking for career advice. I love helping good people on both sides of the equation, but there are a few things I expect from recruiters.

Be Candid

When I speak with a recruiter who is unwilling to share information about the client for fear they will be circumvented or will not provide a general range for the salary/rate, it says to me that they do not trust their own value and consider the candidate an adversary.

Experienced recruiters bring more to the table than a job description. They, or someone they work with, have a relationship with the client company and a reputation of bringing them solid candidates. A resume presented by such a recruiter may be given more credibility and often goes to the top of the interview list.

In my experience, providing a general range of possible compensation for a position is a win-win. It gives a potential candidate the information they need to decide if the opportunity is worth pursuing and keeps from wasting anyone's time.

Avoid Random Referral Solicitation

I can't count how many times some random recruiter has asked me to help them expand their network by recommending them to my colleagues or, even worse, asked for me to give them contact information for possible candidates. There is a short list of recruiters which I provide when someone I know is looking for a gig and these are people who I've known for years and have a solid reputation for taking care of their candidates. It baffles me that someone would expect me to recommend them when I cannot vouch for their character and abilities.

That said, I encourage recruiters to email me job openings that fit my niche as I may come across someone who would be a good fit. While I appreciate having these on hand in case a colleague expresses a need, I do not actively seek candidates for these positions unless there is significant motivation for me to do so. Motivation comes in many forms, but the most straightforward is a referral fee. If a recruiter who I do not have a relationship with expects someone else to spend time and energy helping them fill a position, they should expect to offer compensation in the same way that I would share part of my billable rate should I need help from another software developer who is not getting paid for the work.

Get Involved

Having served as Treasurer, Vice President, President and now Board Member for the Nashville .NET User Group, I often encourage others to drop by and find a way to participate in the community. It can be an important tool for software developers, but is absolutely vital for a recruiter.

Imagine taking all the juiciest most healthy fish in a lake and putting them in a swimming pool. Wouldn't that be a great opportunity for a fisherman to make a great catch? User group meetings are where the best and brightest gather and recruiters are welcome at most of them, so long as they respect the meeting and are not overbearing. Even if the recruiter doesn't speak to anyone about opportunities during the meeting, they have a connection to reference next time they call.

Attending community events is not just about networking. The bulk of a technical presentation might be over a recruiter's head, but over time they can pick up meaning behind the buzz words and witness individual and group reactions. Understanding these reactions can help identify the right candidates for a position and what motivations particular candidates might respond to.

There's a wealth of non-technical education that takes place as well. By watching how people interact one can learn quickly who people in the community respect and how they interact. Seeing how someone interacts with their peers can be a great indicator for how they might fit into a team.

Chances are, any recruiters who are taking the time to read this article are already on the right path. Hopefully these tips will help provide direction to someone I will, one day, have the pleasure of working with.

If you have any additional tips or thoughts on this topic, please feel free to leave a comment below.

Thursday, September 20, 2012

New Talk - Going Solo

I'm working on a new talk for Bar Camp Nashville and have never had so much fun putting together a presentation. The title of my talk is, "Going Solo - How to Train Your Wookiee" and am going with a Star Wars theme. Here's what I've got so far:

Description: When you started you were but the learner, now you are the master. You can make the Kessel Run in less than twelve parsecs, but you're getting tired of Greedo and Jabba demanding a cut. If you dream of being your own man, join us in discussing how to choose and outfit your ship to embark on the quest for freedom.

Topics:
  • Opening Introduction - "I'm Gaines Kergosien, I'm here to rescue you."
  • Getting Rich - “Wealth...more than you can imagine.”, “I don’t know. I can imagine quite a bit.”
  • Possible Pitfalls - "I've got a bad feeling about this."
  • You Can Do It - "I find your lack of faith disturbing."
  • Marketing Yourself - "The Force is strong with this one."
  • Creating a Company - "Aren't you a little short for a stormtrooper?"
  • Contractor Agreements - "Let’s just say we’d like to avoid any imperial entanglements."
  • Managing Finances - "Into the garbage chute, flyboy!"
  • Paying Taxes - "The Phantom Menace"
  • Tax Deductions - "These aren't the taxes you're looking for."
  • Working Remotely - "You're all clear, kid! Now lets blow this thing and go home!"
  • Subcontractors - "Help me Obi-Wan Kenobi. You’re my only hope."

Special thanks to Scott Walters and Philip Wilson for helping brainstorm ideas for the talk.

UPDATE:
The schedule has been finalized and we'll be in the Cadillac Ranch Poker room at 3:45pm on October 20th.

UPDATE 2:
Here's a quick preview of a few title slides from the presentation:

UPDATE 3:
We'll be streaming live at http://www.livestream.com/barcampnashville5

Tuesday, September 18, 2012

.NET Testing Frameworks

Most of my testing experience has been with MSTest, NUnit and Selenium and I feel this is an area I need to explore in more depth, so I thought I'd put the question to my colleagues and readers: What testing frameworks do you prefer and why? Below are a few lists of some .NET oriented frameworks with some notes on what sets each of them apart from others. I welcome comments confirming, challenging or correcting these notes as well as suggestions of others I may have missed.

Unit Testing
  • MSUnit - Included with VS, Easy to implement
  • NUnit - Most common third party framework
  • xUnit - Extensible, lends itself to TDD/BDD
  • MbUnit - RowTest for parameterized testing

Acceptance Testing (web)
  • Selenium - Relies on CSS ID and class selectors
  • WatiN - Works best with IE

Tools

Mocking

Tuesday, September 11, 2012

Great MVVM, WPF, SOA and EF4 Articles

I was asked to put together some links to articles that would help our IT department ramp up on some of the patterns and technologies we're using. By the time I was done with the email, I realized it might be of use to others outside our organization so part three of my MVVM with WPF series was born. There are many approaches and I highly recommend researching beyond this handful of articles, but for anyone not yet familiar with these concepts I hope they help.



The Model-View-ViewModel (MVVM) pattern helps to cleanly separate the business and presentation logic of an application from its user interface (UI). This separation is key for testability, maintenance and scalability.

Here’s an introduction to MVVM which illustrates how it leverages WPF data binding and commands.

The main difference between what we’re proposing and how they define MVVM in the previous articles is, by using a convention-based framework such as Caliburn.Micro and events/commands to wire up the View and ViewModel, they are completely decoupled allowing for better testability and future scalability. The Caliburn.Micro wiki has a good introduction to the functionality it provides.

This article gives a good introduction to Attribute Based Validation which allows us to keep validation logic down in the business layer and entities where it can then bubble up and be reflected in the UI.

If there’s interest in going deeper, here’s an article on using a Service Oriented Architecture (SOA) to decouple service providers from consumers allowing for greater reuse and insulating the application from core business logic.

Finally, a  series of articles outlining the use of a Generic Repository with Entity Framework 4 (EF4) to reduce the amount of plumbing that must be written and maintained for data access.



See also:
MVVM with WPF Series Part 1. Disconnected WPF Applications
MVVM with WPF Series Part 2. WPF MVVM with WinForms Controls

Thursday, August 9, 2012

WPF MVVM with WinForms Controls

This is the second part of my series on using MVVM with WPF. In the first article I discussed architecting disconnected applications and how MVVM was a great fit for WPF smart clients as well as Silverlight web clients. Now we move on to the process of refactoring an old Windows Forms application to use this new architecture.

The main concern with changing an underlying technology is the initial investment in rewriting code. To help mitigate this issue, WPF has provided a WindowsFormsHost element that allows us to host WinForms controls inside of a WPF Page. Obviously this limits how effectively we can leverage other features provided by WPF, however with a few workarounds it's a viable solution to avoid having to completely rewrite those old WinForms controls.

How easy is it to implement the WindowsFormsHost?
<WindowsFormsHost><wfh:WinFormsUserControl x:Name="LegacyUserControl" /></WindowsFormsHost>

Okay, it's only slightly more complicated than that. You will need to add add a reference to WindowsFormIntegration and possibly System.Windows.Forms (if it is not already referenced).

Now the question comes to how we interact with this control from our ViewModel since we can't use WPF bindings in our WinForms control. We can bridge this gap by adding events to our WinForms user control.


Then we wire up the events to our DataContext in our WPF Page code-behind.


While I generally prefer to avoid using the code-behind, we also don't want our ViewModel to be aware of the internal workings of our View.

The end result is our Windows Forms control interacts with elements in our WPF Page.

demonstration

Download Demo Source Code

Tuesday, July 24, 2012

Disconnected WPF Applications

I was recently tasked with presenting a plan to turn an existing WinForms program into an enterprise level application. They wanted to stick with a Windows client, but since each form would already need significant rework to extract the business logic, I suggested moving to WPF using the Model-View-ViewModel (MVVM) presentation pattern.

MVVM is basically a type of Model-View-Presenter (MVP) pattern that makes use of declarative bindings. State and logic are stored in the Presenter (ViewModel) which presents an abstract view of the UI with no knowledge of what View will implement it.

With the Presentation Layer taken care of, it was time to address the heart of the Application. The immediate need was for a smart client, however the solution was still very young and continually changing so it seemed a Service Oriented Architecture (SOA) would provide the most flexability and reuse. The question was how a disconnected client would use services.

Microsoft used to offer an application block for this specific purpose. The Disconnected Service Agent Application Block helped maintain a queue of web service requests while working disconnected (offline), then submit them to the server when it became available. Unfortunately, it is no longer being maintained and I have not found a suggested replacement. My guess is that they would encourage use of Sync Framework, which is designed to synchronize databases and files, but can use custom providers as well.

We're using Sync Framework to replicate data down to the client for offline use, but to utilize SOA and keep business logic/validation on the server we need a way of queuing web service calls and resolving any conflicts that occur. I'm currently in the process of researching whether a Sync Framework custom provider would be a good fit or if the old disconnected service agent application block would be a good starting point.

The existing relies very heavily on SQL stored procedures. Fortunately, Entity Framework (EF4) supports calling the existing stored procedures so they wont all have to be rewritten immediately. The plan is to gradually move business logic up into the application layer and use entity model. I've also added a generic repository to allow mocking.

I welcome feedback and suggestions. If you've tinkered with custom providers for Sync Framework or have suggestions for how to best queue and resolve service calls I'd love to hear from you, either by leaving a comment below or on twitter (@gainesk).

Tuesday, May 8, 2012

Testing the Untestable with VS2012 Fakes

One of the new features included with Visual Studio 2012 is the Fakes Framework which offers the ability to detour code at runtime and isolate functionality for true unit testing, regardless of whether the code was written with testing in mind.

I began speaking on Fakes back when it was a beta product from Microsoft Research called Moles. While the core functionality remains the same, Microsoft has streamlined the implementation and now calls the detour mechanism a shim rather than a mole.

If you have attended this or another of my talks at a user group or conference, please take a moment to share your feedback on SpeakerRate.

The PowerPoint is available on SlideShare and below are links to the code demonstrated in the presentation.

Demos
Y2K Checker (simple introduction)
DateTime Audit (avoiding non-deterministic tests)
File Reader (shimming file system access)
Repository (stubbing interfaces)

Resources
Visual Studio 2011
Fakes MSDN Documentation

Thursday, February 9, 2012

Microsoft PEX and Moles

Microsoft Research is currently beta testing a couple new frameworks that can make unit testing your code a breeze. Pex is a testing tool that analyzes code and generates unit tests. Moles is a framework that isolates code with dependencies on other application layers or frameworks. With just a few mouse clicks, you can generate suites of tests against code that previously may have been difficult or impossible to test.

Tonight I'll be giving a presentation on these technologies at the Nashville .NET User Group. For anyone who can't make it you can watch and discuss it in my Google Hangout. I'm hoping to post a video of the presentation to this blog within the next couple weeks. I'll also be giving a similar presentation and Code PaLOUsa on March 17th. Below are links to the demo solutions and Prezi used in the presentation.

Presentation on Prezi
Using Moles to Mock DateTime (Y2KBug.zip)
Using Moles to Stub Interfaces (MolesDemo.zip)
Using PEX to Generate Parameterized Unit Tests (PEXDemo.zip, PEXDemo-Result.zip)

Friday, November 11, 2011

5 Steps to the Six Figure Developer

What makes someone a six figure developer? Of course you need to have skills, but beyond the technical what can you do to become a rock star?

5. Attending user group and conferences sets you apart. The majority of developers aren't willing to invest their free time in their career. The more you attend user group meetings and regional conferences the more you'll find the same people and get to know each other. By surrounding yourself with other developers who are passionate about their craft and excited about new technologies you'll find yourself rising to a new level.

4. Blogging is a great resume. Anyone can list a bunch of companies and dates on a document, but years of blog posts showing technologies you've tried, techniques you've developed and solutions you've found are worth their weight in gold. Don't over think it. If you find a solution to a problem, blog it. So what if someone else posted the same solution. Their post might not be there in six months or yours might come up in a search theirs didn't. If it has value to you then it will probably be of value to someone else.

3. Speakers are given respect. As soon as you stand up in front of a group and present a topic you're given a tremendous amount of respect as an authority. Not only are you showing confidence in yourself but you're able to communicate ideas and teach others. Speaking isn't easy. It takes a lot of preparation and practice. Make sure to run through your presentation in front of a mirror and for family/friends before giving it in public. Be careful with live demos, because even the most experienced presenter can get tripped up during a demo.

2. Getting published shows off skills. Whether you write an article for a magazine, create an open source solution or develop a mobile app on the market place, having published and publicly visible work shows you can get the job done. Many developers have side projects that they've been "working on", but the best ones have finished products available to the public or articles showcasing their experience.

1. If you don't know your own value, who will? Confidence is key and it's crucial to recognize your strengths, showcase them and be willing to promote yourself. If you're a modest person and uncomfortable bragging, just couple a strength with something you're trying to improve. For example, "I have over ten years of experience developing websites for large corporations, but I haven't had an opportunity to work with some of the newer standard yet and am looking forward to using them soon." This not only shows your strengths and talent, but also conveys that you recognize areas of weakness and work to improve them.

Tuesday, November 8, 2011

Senior Developer Training on a Budget

So you've been in the business for over ten years and the technologies continue to change. Now everyone is talking about HTML5 and JavaScript isn't just a way to validate data or show dialog boxes. You're expected to use CSS to style your website instead of those trusty tables and this stuff is complicated. You could probably go to a local user group meeting or a conference to see a one hour presentation on the topic, but lets face it, you're not going to become a web ninja in an hour. What you need is a college level class that will take you from intro to advanced.
I'm sure I'm not the only one who's felt this way. Software developers have to be self taught, to some extent, but many things can only be learned through experience or taught by someone who has that experience. This got me thinking that maybe we need an opportunity for continued education that's more affordable than auditing a college class and taught by someone who actually does it for a living.

We're still working on sponsorship to pay for the laptops, lining up professors and scheduling the facility, but if all goes we may be holding the first classes in January 2012. What topics/technologies would you like to attend?