Blog Moved

My blog has moved!

https://kmack.azurewebsites.net

Sunday, December 14, 2014

Microsoft and Startups!

Hello All, let's start with the apologies for a lack of updates.  In short, lately I've been busy at my day job, having thanksgiving with the family, and dealing with some health issues in the family.  Combine that with the end of the semester, and you have a Kevin who disappears off the face of the earth.  But I'm back and ready to pick up where I left off.

OK so with my last byte I gave you the pitch for what azure is and why it matters.  Specifically I talked about how it works for small business by minimizing costs and maintaining a low overhead for maximum results.  I'm not trying to be a microsoft sales person here, but I can honestly say that based on what I've seen Azure has a lot to offer, especially in the realm of small business, and Microsoft noticed. 

Well, I'm going to deviate from that a bit, mainly based on some things that I discussed with my students.  Many of you know that I'm an adjunct professor, and the fall 2014 semester just ended.  Right before the final, I give my "Advanced Topics" class, which is always a lot of fun.  I usually take the last class, and make it optional.  With the intent to discuss topics that aren't within the scope of the class to show them more things that those who are interested might find useful.

So this class I covered the following topics:

  • Visual Studio Online
  • ASP.NET MVC 5
  • Microsoft Azure Platform as a Service
  • jQuery
  • BizSpark
Well a lot of the interest that usually comes this class is the number of people who are interested in beginning a startup.  People who have some genius idea of their own.  So I started by talking about the resources that are out there for people who want to try their hand at a startup.  Microsoft has made an incredible amount of resources available to startups, and I wanted to talk about some here.
  • BizSpark:  The biggest offering Microsoft makes for startups is BizSpark.  BizSpark is a program where you can sign up and for 3 years you get almost everything that microsoft has to offer for free.  That includes ultimate versions of everything.  This is a fantastic offering.  And definitely one I advise people to take advantage of, but if that wasn't enough, you get 3 years of $300 / month Azure credits, for free.  Talk about a huge offering.  Can be found here.
  • Visual Studio Community Edition:  A new offering from Microsoft, is a more beefed up version of VS for free.  So even after your BizSpark runs out, there are other options available.  Can be found here.
  • Azure:  As I've said before Azure makes it possible to get your major idea out there quickly and with stability.  Can be found here.
  • Visual Studio Online:  Arguably the most important thing in a Software Companies arsenal is Source control, its the backup of work, the tracking of items, the sharing of work around teams. Well Microsoft now made this officially free.  You can now utilize TFS, with the ALM tools and source control for free. 
More and more recently segments of the .net framework have gone Open-Source, allowing for more availability of tools out there to build with.  Making it an exciting time to be a developer with an idea.  

Sunday, November 9, 2014

Web Apps now come in Small Business

Hello All, time for another MackByte...haha see what I did there.  For this post I wanted to take a minute to talk about Microsoft Azure, something that I've been working with a lot recently.  And while I've been working with the platform, I've really been impressed with all the capabilities it provides.  But what occurred to me is how much one particular group isn't aware of it.  And that group is small business.

In my current position the vast majority of the work I do relates to the medium sized to the large size applications.  That being said, one thing that has become increasingly clear to me, many of these businesses implement medium to larger applications as a way to automate processes, maintain consistency, and enforce business rules.  All towards the goal of cutting costs, and the almighty dollar.

Now it does occur to me that larger companies are not the only ones to experience the types of issues that these applications are built to resolve.  In many cases small businesses are just as likely to fall prey to this issue.  The biggest difference is that smaller businesses don't have the kind of money to lose to bad processes and inefficiencies.

But in many cases, small businesses never consider the option of utilizing web applications, or different software tools to minimize these types of issues.  And also in my experience they tend to avoid it for the following reasons:
  • Cost of Development:  Let's face it development work isn't cheap.  Many developers skills come at a pretty penny.  Honestly, finding someone who knows enough to build a solid application can be a difficult process.
  • Cost of Infrastructure:  Another barrier to entry for the IT solutions game is definitely the cost of hosting an application.  To by space to host a server, and a database, can costs $1,000's of dollars a month.  Money that many small businesses just can't afford to tie up given the risk. 
  • Lack of Technical Knowledge:  Finding someone to manage those servers on going, is ridiculously expensive.  
  • Licensing:  Let's face it, SQL Licensing and Windows Server licensing is not cheap.  I once worked with someone who used to say "When someone says the word 'Licensing', the price just skyrocketed."  
Well for Small Business, there is Microsoft Azure, which provides many fantastic services on the cheapallow I'm not trying to give azure free press.  But honestly, the fact is that small business can't afford infrastrucure.  Till you buy and license a server and pay for someone o maintain it, your talking probably 6 figures at least.  But with azure they make it possible for the infrastructure and backups to all handled for as low as $20 a month.  Seriously.  Then you can contract someone to do the work at a very affordable rate.  I'll be doing more posts on azure soon, especially since I am going for my MCSD: Azure.  But this is sort of my opening salvo on the topic.

Thursday, October 30, 2014

Staying Current

One topic I've written about before is this idea of staying current.  Don't believe me, see the following articles (here and here).  This industry is an industry that is constantly moving.  And I do mean constantly, and I think sometimes people on the outside looking in are unaware just how quickly it moves.  This is an industry where the tools, techniques and practices are changing daily, and if you don't make a consistent effort to keep up, you won't and you'll fall behind.  And once you start falling behind, its pretty easy to keep falling.

So what can you do?  I mean there's a lot of stuff out there, and sitting and reading through articles you find via google will only get you so far.  So what options are out there.  Well there are a wealth of resources out there.  I don't pretend to know them all but here's a list of some of the ones I use:


  • CodeProject:  A fantastic site with a great community (and I'm not just saying that cause I'm a contributor).  I say that because you receive a lot of updates and their articles are written by actual developers and then have an active community.
  • PluralSight:  A fantastic site with a HUGE library of training videos and courses.  They provide a bunch of topics everything from .net to beyond and provide new courses all the time.  It is a pay service, but it is well worth the money.
  • Microsoft Virtual Academy:  A great Microsoft supported site that provides a wealth of training videos including videos series around the MCSD.
  • Channel 9:  Another Microsoft Sponsored site that supports a large amount of Microsoft products.  They have regular shows beyond the virtual academy including videos about new releases.  
  • .NET Rocks:  A fantastic podcast where they cover the latest trends in the .NET and technology world.  Overall one of the best podcasts I've found for technology and the software industry.  
  • Gone Mobile:  A great podcast that covers topics relating to mobile application development using technologies such as Xamarin.  
  • Hanselminutes:  A great podcast by Technologist Scott Hanselman, who works for the Azure team for Microsoft.  
  • Central PA .net User Group:  User groups like this are a great way to meet and network with over developers and find out the kinds of things they are working on and resources they are using.  
These are just a few of the many resources I recommend, and options out there for a variety of even more resources.  Staying current is honestly the best habit you can get into to have along and prosperous career in this field.  The best way to learn in this field is by doing.  And the best way to do that is personal projects.  Now I know that sometimes its hard to come up with a personal project.  That's when I recommend sites like Code Chef, which is a great site that will give you problems to solve.  

Saturday, October 25, 2014

Angular.js and Recommendations

Also, while I'm at it, I did want to put a post out here about another technologies I've been researching for personal projects.  I've been researching client side frameworks for a new project I've been working on for my own company.  And in the process of doing so, I've been looking at building a SPA application.  Now there are lots of great frameworks out there for building SPA applications, and in my case this is something I have not had much of an opportunity to pursue in my professional life, so I'm definitely doing so in some personal projects.

In the process of researching Angular, I came across a great podcast of .NET Rocks, specifically with Dan Wahlin, where he talks Javascript and Angular, and he references a youtube series that he put together.  And it really is fantastic and I definitely recommend it to all that are interested.  And best of all it takes a little over an hour to complete all parts.

#1.  Part1
#2.  Part 2
#3. Part 3
#4. Part 4
#5. Part 5
#6. Part 6
#7. Part 7

Busy week and Azure

Hello All, so its been a really crazy week, as I ended up spending the majority of my week getting odd jobs done around the house, and ripping the carpet out of the first floor of our house.  And as my sister-in-law put it "strangely therapeutic", in an odd sort of way.

But more than that, I had a really good week professionally.  Outside of the normal good stuff at work, I also got to enjoy two fun new distractions.  The first being the that I attended our .NET User Group here in Central PA.  And this month the meeting was an open discussion forum.  A chance for developers to come and talk about a variety of topics and solicit feedback from other developers within the group, and discuss best practices.

It was really enlightening to hear the thoughts and feelings of developers around the area, and the different approaches they all use.  We had some interesting discussions about where the industry is headed and overall best practices.  I enjoyed it a lot more than I thought I would overall.

The other was that I actually got to talk to someone who was looking to make a career change, and we got to discuss the industry from an outsiders perspective.  And got to sort of compare notes and identify things he can do to help facilitate the career change and set himself up for success.  It gave me a lot of ideas for a potential post in the future here that I'm still putting together...more on that later.

But I wanted to post this week about some ideas and discuss a few keys points.  I've been doing a lot of research into Azure lately, and I gotta admit that it is something really fantastic to work with.  So far my experience with it has been quite exceptional.  And I wanted to share some courses I've taken on plural site that I found particularly helpful if you are looking to expand into Azure.

Introduction to Windows Azure Infrastructure as a Service by Vishwas Lele

Windows Azure Storage In-Depth by Alan Smith

Windows Azure Websites by Matt Milner

Windows Azure Service Bus by Scott Seely

SQL Azure by Scott Seely

Fundamentals of Azure Cloud Services and Storage by Matt Milner

Sunday, October 12, 2014

Making SaveChanges Work for You

Ok, so this update is going to be a short one, mainly cause I am in the process of researching for a longer blog post on Microsoft Azure, and a process article on implementing scrum into a young development team.

But those are topics for future articles, and will be released shortly, but I wanted to take a second to talk Entity Framework.  Entity Framework is a powerful tool, for creating and working with a data access layer of an application.  It allows developers to quickly and efficiently craft a data layer, and work with it through the use of tools like LINQ.

In my experience though, Entity Framework does have one drawback, and that's it does it's job a little too well.  And that's that it makes things a little too easy on many developers, and as a result this tool tends to be under-utilized.  In my experience developers tend to create their database, drop it into Entity Framework, and then start building a "Data" layer on top of it.  Which essentially is completely counter-productive.

One perfect example, is the idea of "Audit" fields.  Many of us have built the same audit fields into every table.  Things like "DateAdded", "AddedBy", "DateModified", and "ModifiedBy".  We build fields like these are standard practice to help identify and track data changes.  This can definitely help to keep data integrity.

I can't tell you how many times, I've worked on applications, where I see things like repositories that are built, on top of entity framework...say that there are 10 repositories, and every single one of them has an "Insert" method, and they all have logic to populate the "DateAdded", and "AddedBy".

Instead, what I'm advising is that "Entity Framework" doesn't have to be a "black box".  A good example is the use of these audit fields, and utilize "SaveChanges".

By overriding "SaveChanges", we have the ability to build this auditing functionality directly into entity framework.

The following code is from a personal project of mine.  And it outlines the process of leveraging entity framework to provide a single point for this operation instead of replicating it everywhere.

By utilizing an interface like the following:

public interface IEntity
    {
        DateTime CreatedDate { get; set; }
        string CreatedBy { get; set; }
        DateTime? ModifiedDate { get; set; }
        string ModifiedBy { get; set; }
    }
By implementing the above interface, on all data tables that have those fields.  It will then make it easier to identify them whenever needed.
public partial class TaskEntities
    {
        public override int SaveChanges()
        {
            var auditable = ChangeTracker.Entries<IEntity>().ToList();
            if (!auditable.Any()) return base.SaveChanges();

            foreach (var dbEntry in auditable)
            {
                switch (dbEntry.State)
                {
                    case System.Data.Entity.EntityState.Added:
                        dbEntry.Entity.CreatedDate = DateTime.Now;
                        dbEntry.Entity.CreatedBy = HttpContext.Current.User.Identity.Name;
                        break;
                    case System.Data.Entity.EntityState.Modified:
                        if (String.IsNullOrEmpty(dbEntry.Entity.CreatedBy))
                        {
                            dbEntry.Entity.CreatedDate = DateTime.Now;
                            dbEntry.Entity.CreatedBy = HttpContext.Current.User.Identity.Name;
                        }
                        dbEntry.Entity.ModifiedDate = DateTime.Now;
                        dbEntry.Entity.ModifiedBy = HttpContext.Current.User.Identity.Name;        
                        break;
                }
            }

            return base.SaveChanges();
        }
    }
In the above code, the web application checks all objects that are being saved and if they implement the IEntity interface, it populates the appropriate fields.  What this does is guarentee that the data layer handles this type of operation and prevents the developers from having to build extra logic to accomodate this requirement.  It also ensures that any new tables added can have this logic immediately added without extra knowledge or work on behalf of the developer.

This is only a single example of how we can extend Entity Framework further to better accomodate this type of work, without building redundant data layers on top of it.

Friday, September 19, 2014

Software and Science of Deduction

I'm a huge mystery buff.  Plain and simple, I love them all.  I read mystery novels, watch police procedural, you name it.  There's something truly awesome about figuring out and solving some puzzle that no one else could solve.

It's surprising how many people I know who work in software development that are the same way.  I joke with my students all the time that I love what I do because I get to solve puzzles all day.  What we do isn't that much different than what many of pop culture's greatest detectives do, we figure out and trace a problem, determine the cause and act accordingly.  

Now, I know usually Sherlock Holmes is trying to find a murderer, and lives hang in the balance.  If you don't think that's our job...then you clearly have never gotten a phone call when a production enterprise system crashes.  We may not be solving a murder, but I'm pretty sure we are working to prevent one.
Elementary Dear Watson
That being said, whether its in academia, or in a professional setting, it really does surprise me how many programmers, both junior and even senior developers who don't really know how to debug or trace down a problem correctly.  It just surprises me how many people run into an error and throw their hands up.

Here's a word of advice, if you want to go far in this industry...don't do that.

The reason I say that is a simple one.  Many of the senior developers and mid level developers I know are very busy.  They work in a situation where they have everyone wanting a piece of them.  Now I'm not saying that to sound egotistical, its just a fact.  The more you distinguish yourself in this industry the more people will want your time, just like any career.
Must find this key!
So honestly the best way to earn respect in this industry is to tackle your own problems and learn to debug.  Honestly learning to debug is the most important skill any developer can have.  It allows you to quickly identify problems, and impress your colleagues with quick and efficient solutions.

So here are my tips for learning to debug better.

Tip #1.)  Nothing beats boots on the ground.  (Know what tools you have in the tool box)

This is a pet peeve of mine, and its something that honestly isn't that difficult but continues to be an issue with many developers of all levels.  Visual Studio is a very robust IDE, and it provides many tools for helping to debug errors.  At the lowest level there are breakpoints.  But even after that there are traces, logging, the immediate window, etc.  All of these tools are designed to help you get a better picture of what's going on.

Learn to use these tools, honestly.  It will pay dividends quickly.  Knowing how to use the tools that can give you a complete picture of what is going on in your application is the best way to determine the cause of a problem.  That and I can't tell you how many times I've had this conversation:

Developer:  I've gotten this error..."{Usually a screenshot of the message, or just reading it to me}".
Me:  Ok, and what did you find when you stepped into the code?
Developer:  {Blank stare}

Honestly, this is infuriating.  There more frustrating, because while I or any other Senior Developer is receiving this blank stare, here's what we hear.

Developer:  I've done absolutely no work to figure out this problem...why aren't you handing me the answer....Give me the answer, I can't work for this.

Now I'm exaggerating a bit, but honestly its frustrating, because we do feel like you are expecting all answers to be given to you.  Know the tools and do your research.

Tip #2.)  Take a good hard look at your victim (Read the error message, and I mean REALLY read it.)

This seems like a no brainer, but again you'd be surprised how many times I've been brought a runtime error, where it blatantly says the cause in the message.  Usually this is because the developer who ran into the error just saw it and brought it to my attention.  When you get an error, don't look at it as something preventing you from doing your job.  Runtime or Syntax errors aren't roadblocks to you doing your job that a Senior Developer or Manager needs to remove.  THEY ARE PART OF YOUR JOB!  Honestly look at them as a learning opportunity.  A chance to see why what you were doing doesn't work.  Or a chance to get a little better handle on the .net framework, or the platform your working with.

Tip #3.)  Check the Scene for clues

Much like Sherlock Holmes, when you arrive at the scene, you've already got a wealth of tools are your disposal, and you've already taken a good long hard look at your victim, so now its time to leverage the most important tool in your arsenal...Your mind.

Start looking around the part of the application that is failing to determine the cause of the error. Start asking yourself questions and looking around the offending line of code for potential reasons for failure.  For example, I would look for some of the following cases:


  • Are there any recent changes to the code?  Is this a case where it was working up and until today and now it started failing...if so, then it was something in the changed code.
  • What does the stack trace say?  The stack trace is like your own personal footprint trail, follow it to see how things failed.
  • Are there any bad practices at play?  Cases of not checking for null values, or failure to follow coding standards?  Usually these can be signs that code was rushed, meaning there could be a problem.  

These are just some of the questions that can be asked, but this gives you a good idea of the types of questions you need to ask.  Because they will help to guide you to your solutions.

Tip #4.) Identify suspects

At this point you should have some idea what's going on, or what the error at least relates to.  Compile a list of the possible reasons for the error, and identify what the offending line of code is.  Before you can fix the problem, you need to identify the problem.  And honestly know what that problem is can bring you a long way to solving it.

Tip #5.) Consult other devs

Now I know this seems kinda backward, especially given the lecture I just gave about not wasting time.  But here's the difference.  At this stage of the game you at least have something, if you are really running into a wall, there is nothing wrong with soliciting opinions from other developers.  In fact this is a great idea, I just argue that you should know what your talking about when you have this conversation.

Also when you feel like you want to play this card, be smart about it.  Ask other people at your level in the project, before you start moving upward.  If your a junior developer, then ask other juniors before you go bother the project lead.  Odds are the project lead will see you doing this, and then by the time you get to him / her, they will be more willing to help you, as they feel like you exhausted options before you came to them.

Tip #6.) When all else fails, pray for a miracle.

When all else fails, offer it up to the google and bing gods.  I kid but in all seriousness, there are two constants in this industry.  1.) all programmers love to solve problems.  2.) Those same programmers love to brag about how they solved problems.

Look at this blog or any other and you'll see why, no question.

Those are my tips to bringing in the art of deduction into software development.  If nothing else, I hope this gave you some ideas, and trust me when I say the debugging process is a great way to learn, and a fantastic way to impress people as you work through this industry.

Thursday, September 4, 2014

2 out of 3: Exam 70-486

Hello All, so the past week has been particularly busy, but as I sit here tonight, while working through one of the most chaotic weeks since my daughter was born.  I wanted to take a second and have the followup to a previous post about the MCSD exams.

For those of you who know me, you know that I've been taking the MCSD exams, and today I took one step forward by completing the second exam, 70-486.

This exam was about utilizing ASP.NET MVC, and developing scalable web applications.  I did pass this exam, and am already beginning to study for the next exam, 70-487.

As far as resources, I used the following:

  • Blogged by Chris Study Guide:  This study guide has been assembled by a bunch of contributors and I found it very useful overall and highly recommend reviewing it.
  • Exam Ref 70-486:  Developing ASP.NET MVC Applications:  This book does a good job of outlining everything at a high level.  I found this book to be a good reference to review and study with.
  • MVC Applications Jump Start:  This video series I thought was great for showing the specifics of how some of these concepts are applied.  The book mentioned above is great at laying out the theory, this is good at showing the application.  
This test was definitely different because of the case studies.  These are presented as a scenario, with full requirements and then questions about how to implement those requirements.  Overall that's about it, but I will be posting more about the content of the exam moving forward.

Sunday, August 24, 2014

Setting the Standard and Practice Makes Perfect

Hello all, and I'm back again with another update, and honestly, this is a pretty timely topic for me.  We've all heard the term Coding Standards, and at many firms I've deal with they tend to be just some document sitting in a directory on the intranet collecting virtual dust.  But I want to discuss this particular idea and how this is a commonly underutilized tool for many senior developers, and something that is not being given enough weight by junior developers.

By definition, Coding Standards and Practices are a set of rules, and guidelines for developing code.  They are a formal document defining what programmers are allowed to do, and what they aren't allowed to do when writing their applications.  These standards should be enforced using tools like formal code reviews.  Honestly, when you say it out loud, this sounds absolutely essential, but in practice I find that these kinds of documents tend to fall by the wayside.  The benefits of coding standards should be fairly obvious, and I'm not going to list them here.  What I'm going to discuss is how to keep them current and make them work for you as a Senior Developer.

Step #1.)  Make sure they stay current.
The biggest reason I've found historically that these kinds of documents aren't used is because the last time they were updated was roughly 5 years ago, which in this industry might as well be a lifetime.  So what can you do?  If you're like most developers, you hear keep these documents current and think...oh god no, not paperwork.  Programmers have an aversion to paperwork like vampires do to sunlight.  The secret to this is pretty simple.  Keep the document light.  First and foremost, no one wants to keep a 50+ page document updated, and worse yet no junior developer wants to read it.  So do both sides a favor, and keep them simple and short.  Keep everything to the point!  Focus on the absolute most important standards only.

Step #2.) Ditch the master document.
Another way to help with #1, and keep your jr developers attention is to not keep one master document.  This is a huge waste of effort, it makes for having that long document, and your trying to create a one size fits all standard, which is never going to work.  Instead I propose that you create documents either by domain (web, mobile, service, database), or by technology (MVC, JS, Knockout.js, Angular.js, etc).  This will make the updating process easier, and it allows Developers to pick which standards to use on their projects, and they are not overloaded.  Also given that your standards are more targeted, the more likely they will be followed, and the better the quality of the standards.

Step #3.) Regularly meet with other senior developers to discuss the standards. 
Set up a regular meeting with other senior developers to discuss and deliberate about the standards, identifying standards that need updated, and standards that need to be retired.  This will allow for a constant updating of this document and minimize the amount of time spent by everyone on updating.  At the end of the meeting, each separate senior developer should have to update some of the standards documents.

Step #4.)  Bring a copy of relevant standards to code reviews.
If you bring them, then you will be more likely to use them.  The fact that the document is in front of you, will make you think about it more, and enforce it more.  The more you enforce it, the better the habits of your junior developers will become.

There will likely be more on this topic soon, but I wanted to post these thoughts right away.  Please feel free to discuss as I would love to start a dialog about this.

Tuesday, August 12, 2014

Exam 70-480

Hello All, I'm back.  As for the quick update, things have been particularly busy right now for the entire Mack Family.  We've been in a state of constant flux lately, both personally and professionally for a little while now.  And its been a little rough on everyone.  Professionally, I've been busy working on several projects.  I continue to work with Xamarin, on one of my companies first mobile applications to be deployed to the app store, right now specifically for iPhone and iPad.  Aside from that project, I've been doing a lot of work with SSIS lately.

For those who don't know what that is, it stands for SQL Server Integration Services.  And its a tool that allows you to build packages to help import and transform data to be added to a SQL database.  It is built to utilize tools to help import and work with large volumes of data.  Definitely possibility for a future blog post, and I probably will.

Outside of that, I've been gearing up for a new semester which starts in a week.  I am about to kick off my 7th semester teaching a course called "Development Fundamentals".  And I have to tell you, its definitely something I look forward to.  There's something really fun about helping people who are starting out in this field, find the passion that I and so many of my colleagues see in it.

But anyway, I digress.  The reason for this post, today I took the first of three exams designed to obtain my MCSD (Microsoft Certified Solutions Developer).  I've made the decision to finally pursue mine, and will be doing it in a very short timeframe.  I passed my exam today, with a pretty good score, and the exam rated me as strong in all skill categories.  I wanted to pass along the resources I had found that helped me to study for exam.

The following were resources I used:

  • Programming in HTML5 with Javascript and CSS3 training guide:  This book can be found on Amazon here. I found this book to be very helpful, and it covered about 90% of the material on the test.
  • Microsoft Virtual Academy:  I found a video course taught by Mike Palermo and Jeremy Foster that prepares you for this exam.  I found that the parts that the book missed, they covered here.
  • PluralSight:  Another great source is this plural sight course, found here.
  • Blogged by Chris Study Guide:  Another great post, this one outlines a lot of the different topics that are covered in the exam.  Found here.
I'm planning on doing more posts as I study for the second exam.  More on it then.  

Monday, August 4, 2014

Lack of Updates and Attention to Detail

Hello All, I know its been a while since my last post.  And I felt that I should at least post something up here for those who have been following along with my updates to this blog.

As for the lack of updates, the reason is actually pretty simple, I've been on vacation, and much like most of us in a professional setting.  There was a lot of work preparing for vacation, and then the actual week of being on vacation.

My wife, and the Munchkin had a great vacation, and I completely enjoyed my time but am excited to get back to work.  I have actually been working on a few new articles, all of which should start to be available as soon as the weekend.  So watch this space for those updates.  Specifically I got one technical, and one that's more like the philosophy articles I've done so far ("How to be a dinosaur" and "Taking the Romance Out of Software Development").

Thank you all for the continued support and feedback.

But I do have simple advice for anyone out there who is a junior developers out there.  And to me honestly, this is one of those things that I wouldn't think are necessary to point out.  But everyone out there wants to Steve Jobs, they want to walk into a meeting wearing bravado on their sleeve and being the smartest guy in the room.

Be honest, we all want that, we've all seen "The Social Network" and want to be Jesse Eisenberg, but again this is a distorted dream, that many junior developers fall prey to.  The truth is that the smartest guy in the room, usually isn't the one who walks in and ignores everyone else's opinion, and he isn't the guy who always gets his way.

The truth is that the smartest guy in the room, is the one sitting in the back, holding a notebook.  You've probably seen him, he's the guy who's setting up the meeting, or encouraging everyone to speak.  Truth be told he probably seems to many junior developers as a fly on the wall.  But my advice to anyone new to this field is to watch this person, and try to become him.

Solicits Opinions of Others:

There is a concept discussed in terms of Web Application Development called Collective Intelligence.  This is hardly a new concept, and its something that many of the most profitable websites / web apps have fully embraced.  Collective Intelligence is the idea that by having everyone involved in a process that we are smarter as a group than we are as individuals.  Its the age old "Two heads are better than one".  The idea that by working together and discussing ideas freely, a better solution will present itself.

Encourages Everyone to Speak:

Margaret Heffernan is a business woman and writer, and recently said "For Good Ideas, and True Innovation, you need human interaction, conflict, argument, and debate."  And she's absolutely right, the best ideas come from discussion, and the process of soliciting opinions only works when everyone is given the opportunity to free express an idea.  Truth be told, even a half baked idea can lead to a major innovation.

Think Before You Speak:

I know, this one sounds counter to the one above.  Just because everyone should be able to share ideas doesn't mean that you need to throw anything out there that comes to mind.  What I mainly mean by this, is before you give a knee jerk reaction to ideas that are thrown out to the room, think about it.  Weigh the benefits and the drawbacks, think about options for mitigating those drawbacks, and whenever you are ready contribute to the discussion in a meaningful way.

Take Notes:

The most important advice I can give, is take notes in these meetings.  Identify action items and make notes of the items discussed.  The more detailed notes you can take, the better you can walk away from the meeting with knowledge that can effect change and enable you to accomplish more.

If you follow these steps, you'll find that you get more out of these meetings and become a better member of the team.  Your peers and supervisors will take notice, and you will find you enjoy your job and the process more.

Monday, July 21, 2014

The Littlest IoC that Could

Hello All, I'm back again.  I know that updates have been more than a little sparse, but I'm doing my best to try and keep up with everything.  I'm definitely still trying to get a handle on this blogging thing.

So I did want to get a post out, and am going to be working on getting more posts out soon but in the mean time I thought I'd post about something that I've been working with a lot, and that's TinyIoC.

As many developers already know the idea of Dependency Injection and Inversion of Control has really taken the development world by storm over the past few years.  And to anyone who has worked with it at all, it really shouldn't be that surprising.  The basic idea of Dependency Injection is a relatively simple one.  We decouple our code by using interfaces and a construct called a "Container" to swap out those interfaces for a concrete class.

I'm not going to go into a lot of detail about Dependency Injection, that's a whole big blog post for another time.  But the real strength is that we can have our classes exists 100% detached from one another, and then use these containers to swap out interfaces for the appropriate classes.

There are lots of reasons that this idea can be beneficial.  For one, it makes unit testing a WHOLE lot easier.  Because now we can swap in test versions of the classes that are being used within a class and focus on testing only one unit at a time.  Another benefit is that it makes our code a whole lot more maintainable, cause if we need to build a new class we can, and just point the container at it instead of the old class and the container takes care of the rest.

But what I wanted to talk about in this blog post was Dependency Injection with regard to PCLs.  Right now I've been doing a lot of work with Xamarin, mainly to build applications in a professional, and a personal setting.  And it really is a powerful tool, and it shouldn't be all that surprising that if you want to build an app that is any bigger than a calculator...that you would want some form of dependency injection involved.

But there's the problem, see for you to be able to implement a DI container, in a Xamarin application (for iOS, Android, or Windows Phone), then it has to be PCL Compliant.

For those who aren't aware, PCLs or Portable Class Libraries, utilize a subset of the .net framework to allow us as developers to build reusable class libraries to utilize in our applications.  But because its only a subset of the .net framework.  Sometimes the dependencies that are required just plain aren't available to us in a mobile setting.

In the case of most of the larger containers out there.  For example Castle Windsor, Unity, Ninject, etc.  They are not PCL compliant.  But after a lot of researching and discussion with other devs, I found a great open source product that fills this need.  It's called TinyIoC.

You can find it on GitHub here.

While it may not be as powerful as some of its more robust cousins, it is great for using Constructor Injection, or even manually resolving interfaces within code.

So for those interested, I recommend checking it out.  Watch this space...later this week I'll be discussing how to use TinyIoC in an iOS application as well as how to leverage a bootstrap class to handle injection of dependencies at the PCL and then native application level.

Tuesday, July 15, 2014

Taking the Romance Out of Software Development

This is an article I've been wanting to write for a while, and its mainly to voice some observations that I've had in my ten years in the software development industry.  In my time, so far in this industry I have been truly lucky enough to have worked on some really fun and exciting projects, and also worked as an adjunct professor for a local university.  

Part of my job is assisting in the intern program, as well as helping many junior developers who have just gotten their foot in the door, and are learning to stand on their own. Now, in all of that, I've gotten lots of questions, and honestly a lot of times its the same two questions.  The first question is the one most people think of, "How do I get a job in software development?", and that's the question most of my students ask, given that many of them are reaching the end of their tenure at college. The other question is usually the one I get from Junior Developers after they've gotten the all important first job.  "How do i succeed in this field?"  I've seen many developers come and go, and I've worked with a lot of people I've come to admire in this industry, and the ironic part is that the answer to both questions is the same, and its rarely what you would expect.  

Most of my students or junior developers, all have a specific answer in mind when this question is being asked.  They are expecting to hear, "If you learn C#, you'll succeed." or "If you master Angular.js, you'll be making 6 figures in no time."  But the sad part is that the answer to this in my experience isn't that easily quantifiable.  In my experience the course of your career starts with your definition of success.  An old saying is that if you want to start something, you should always have an end in mind.  

This advice is absolutely timeless, in the sense that anything you do...you should have a goal in mind, something you are hoping to accomplish.  So the first thing you need to do, is define success for you.  

For me it falls into three categories...Am I employed?  Do I enjoy my job?  Am I being paid what I think I'm worth?

If the answers to those questions are all yes than I can consider myself successful.  The important part here is that you set your own measures of success and make them measurable.  Now I know those seem like pretty generic questions, and most people are probably looking at this with a "Come on, your kidding", look about now.

Unfortunately movies and even colleges define success as working for Google or being the next Zuckerberg.  But honestly that's a very romantic view of the industry, and it sets many up for failure.  It's the same thing where everyone who picks up a guitar isn't going to be the next Jimmy Hendricks. 

So instead let's focus on what's attainable.  For some of you it might be getting a job at Google.  Becoming a manager at your current job, or being self employed.  I prefer to think in these almost abstract concepts to help me stay focus on what's important to me.

Now, I know what your thinking, "How does this answer those questions?" the truth is that passion is worth its weight in gold for this industry.  There are lots of people out there who can write code, and punch a clock.  And in the eyes of many employers, they have training programs where they can teach people with any degree of knowledge how to program the way they want them to.  But someone with passion is a rare find.  People with passion take it upon themselves to learn this stuff on their off hours, and make staying current a priority, and who bring those insights into their own work.  This provides more value, these are also the people who take the most pride in their work, and will do whatever it takes to do the best job they can.  

These people are the race horses of our industry, and honestly they are the most sought after.  They make the highest salaries, they get the most respect, they get attention from companies like Microsoft and Google, and love their jobs.  

So you say, well that's great, but how do I become that person, I'm just a fresh out of school, junior developer. The answer is learn as much as you can whenever you can.  If you make it a priority to read up on this stuff on your own time, work on your own personal projects, challenge yourself to do things better or find better solutions to problems, and before you know it you'll find yourself evolving into a passionate developer.  And honestly in my experience the rest will fall into place for you.  

Now that being said, I don't want to mislead you, this is not easy, its long hours, hard work, and can be frustrating.  When your sitting up at night, while others are going to the bar, banging your head against why a grid won't load.  You'll be ready to scream, but honestly the pay off is huge.  And in my experience that satisfaction you get when you figure it out is amazing.  

Now I'm not saying being a shut-in nerd, but what I am saying is take pride in what you do, and work to better yourself at any turn.  

Now saying those are your goals is only part of the process.  The next step is to make those goals work for you.  Cause what's the point in having the goals if you aren't going to ever do anything to get there.

The first thing you really need to do is make those goals a part of your daily life.  You need to focus on using these goals to shape your decisions.


So with every question or opportunity, you need to ask yourself, in my case, "Am I enjoying this?", "Will this help me be paid what I'm worth, by being worth more?" or "Is this challenging, or how can I make it challenging?"  If you use this method to keep your eye on the price, you will find yourself evolving into a passionate developer.  

Monday, June 23, 2014

Philly CC 2014 : City of Coding Love

What a great weekend!  I'm finally back, but those of you who follow me on twitter already know that this weekend I spent it in Philadelphia, at the Philly.net Code Camp.

So to start, this code camp has grown a lot of the past few years, and its a credit to the staff of the usergroup that this is the case.  Every year that I've come to this event, and this is my third, it has continued to grow and grow and grow.  Well this year was the biggest I've seen yet.

I personally love these events, and its not just for the networking.  But to me, going is all about the mindset.  The best part is to go and sit with people who are also trying to learn.  The atmosphere itself supports that fact.  No one is here to belittle anyone or try to be an elitist.  The atmosphere is much more of a "Hey isn't this awesome...".

I also like these events because its a chance to get a quick view of new technologies and identify things you want to learn as you move forward.  Like for me, I got to see Xamarin.Forms, something I knew nothing about, and I now have enough knowledge to pursue it more.

First the venue, the Code Camp was held at the Valley Forge Resort and Casino, and honestly this venue itself was pretty great.  A great hotel, with great restaurants and lots to do when you aren't at the sessions.  The code camp floor itself was OK, the first day suffered from a lot of audio issues, with presenters having to talk over one another.  But most of these seem to be mitigated by the second day.  So I have no doubt these issues will be resolved by next year.

This time around, my wife came with me, and I can tell you she definitely took advantage of all the casino / resort had to offer, while her husband went to sessions and engaged his inner programming nerd.

As for sessions, here's a quick summary of the ones I attended.  These are just my high level thoughts, most of these people have lots of information online on these topics they presented, and if you want more detailed information let me know.

Azure and OnPremise Hybrid Approach:  Brady Gaster (found here)
This was a great presentation, mainly focused on using Azure for your website, but mixing it in with local services and local databases.  If you work in a professional capacity this is a great topic to discuss.  In my experience the biggest problem with the cloud is that clients are reluctant to allow their data to be handled by some third party.  So instead you can create WCF services with end points hosted in Azure, that call to local installations of the web services.  This allows you to leverage Azure Service Bus to relay and pass those messages down to the WCF service.

AngularJS:  Beyond Introduction: Tom Snyder (found here)
This was a a pretty good presentation, honestly I got to this one late.  But Angular is a huge topic and this was great introduction to the terminology and how to best understand how it works.  To me the most interesting part of this is that I was unaware that Angular implements dependency injection.  The fact that Javascript code can utilize dependency injection is fantastic and interesting.  I'm a pretty big noob when it comes to Angular but this definitely was a good starting point and sparked an interest to install new.

Xamarin Part 1 & 2: James Montemagno (found here), Greg Sheckles (found here), Brent Schooley (found here).
This was a great session, and one I was looking forward to.  Many of you who follow me on Twitter, know that I've been working pretty heavily with Xamarin lately and I gotta say that I'm very impressed with it.  Overall it works great, yes the UI has some bugs, but it definitely helps to make mobile development a whole heck of a lot easier.  Seriously, I've written Java apps in the past, and Eclipse is a bit of a nightmare.  Especially when you are coming from being used to the Visual Studio IDE.

SignalR: Chris Gomez
SignalR is a technology that I have been playing around with on my own, and I have to admit that I love what I see.  To me SignalR is the next step in the pursuit of RIA, and really allows for some cool features with regard to how the client and server communicate, eliminating the postback.

iBeacon and Xamarin: James Montemagno (found here)
Another really interesting talk with some ideas for how to leverage the new support for iBeacon with iOS 7.1.  Again another new emergent technology that has a lot of potential.

Overall, it was a great experience.  I have to admit that I enjoyed the whole event and had a great time.  Given the chance you should definitely attend in the future.

Tuesday, May 6, 2014

How to become a dinosaur!

So this past week I was talking to a few new hires at our office.  People who this is really their first step out into not only development but their first step into a professional career.  And it's always refreshing to see how much optimism these people have.  Showing up every day grinning like idiots.  They haven't been beaten down by deadlines and unreasonable clients.  But are just filled to the brim with optimism and sunshine.

Those poor bastards...just kidding.

While I was talking to one of them he asked me what I like about my job.  And I told him.  "I solve puzzles all day.". And that's true an I like what I do but as our conversation went on he began to ask me how do you keep up with it all.

And it occurred to me, we all know that guy.  The guy who has been in the same job forever and is just pissed off every day.  His career is DOA cause he hasn't kept up with anything and he hates his job but doesn't have the option to leave it.

Its only a matter of time before there is a rewrite of his project and he's extinct. 

So what can we do in this ever changing landscape to stay current.  Here are some ideas based on my experience.  And I don't claim that these are the only options but this is what I would tell anyone new to the industry to keep in mind, or anyone who is looking to get out a rut.

#1.). There is no one right way to do things.

Albert Einstein once said "We can't solve our problems with the same level of thinking that created them."  So it stands to reason that if your working on an application, and are presented with a bug, you can't solve it by thinking the same as every other developer.  You need to think outside the box.  This is a pet peeve of mine, and you will find programmers out there who say that "this is the way its always be done," or "I've been doing this for so many years and that's just not possible".  

Another great quote comes from Steve Jobs.  

"Your time is limited, don’t waste it living someone else’s life. Don’t be trapped by dogma, which is living the result of other people’s thinking. Don’t let the noise of other opinions drown your own inner voice. And most important, have the courage to follow your heart and intuition, they somehow already know what you truly want to become. Everything else is secondary."

The really great solutions are the ones that come from thinking outside the box, and always searching for a better answer.  Just because something has been done one way for eternity, doesn't mean that its the only way.  The only way to find out if your ideas are worth anything is to suggest them.  Now, I'm not saying throw out half-baked ideas, but you should fully form and research your ideas and present them in the best way possible.

#2.).  Always be looking for a better way to do things.

With software development, not unlike many other industries, we deal in ideas, in solutions to problems and ways of thinking.  It's easy to get stuck in a rut of thinking about half baked solutions.  The most important thing is to always be looking for a new technology or tool.  I'm not going to lie to you but this takes a lot of effort.  There are lots of technologies out there, that serve a variety of purposes, and the only way you will know that something exists is if you keep looking.  

There are so many technologies out there, things like Node.js, jquery, Knockout.js, Angular.js, Web API.  

There's a perfect example, for the longest time we utilized web services, specifically WCF services as a way to make our application extendable.  And WCF is powerful and useful, to this day it continues to be used and is a great technologies.  

But, if you're utilizing services in jquery, or in other web technologies, WCF has a lot of overhead involved, that can be kind of a pain.  But a group of developers got together and said, "I know SOAP is this great XML protocol for sharing data, but can't HTTP do that already, with less overhead?"  And they were right, enter Web API, a new technology using Restful Services that makes it easier to share data with a wide variety of platforms.  

#3.). There a lots of ways to stay current.

Now that being said, there are lots of ways to stay current.  The internet is a wealth of resources that can help to keep you up on new technologies.  There are sites out there that can help you stay up to date, sites like CodeProject, 4GuysFromRolla, Channel9, and others.  These kinds of sites have articles submitted by developers discussing what they are working on, and there is no better way to keep up on the latest trends.

Another great way is to go to events, there are lots of user groups out there that can help you find out about new technologies and techniques that you never knew existed.  And many of them sponsor code camps, that are fantastic.  

Finally, social media is a great option, I absolutely recommend Twitter and Google+ as great resources.  

#4.). Keep options open by knowing enough to be dangerous.

Nobody has the time to be the best at everything and trying will just make you insane.  But what you can do is find out the basics about any new technologies you can.  The idea here is a simple one, if I know what something is, and the kind of situation its used for, then when you find yourself presented with that kind of problem, you can always learn more then.

#5.). Don't punch a clock

Look this industry is one that is constantly changing, the world is shifting in new and exciting directions everyday.  If you take a look online and see the names of some of the most successful people in this industry they all have one thing in common.  They all live for this stuff.  If you've decided that you only want to learn about this stuff and research new technologies and techniques between the hours of nine and five then prepare to be left behind.  

So there ya go, there are my top 5 tips to make sure that you don't end up being a dinosaur.  The one thing I always tell my students is you can't teach passion, and passion will take you far in this field.  

Friday, February 28, 2014

Web API, or Cutting out the middle man

Ok, so I’m back with another blog post.  Tonight I sit here, with the wife and the munchkin passed out and am taking this singular opportunity to catch up on the Blacklist and thinking about the latest blog post.  And then it hit me, Web API.

This past week I’ve been doing a lot of reading and research into Web API, and I have to say I’m impressed with how completely flexible it is, and the overall possibilities it opens up.

All of us as Web developers have been tasked whether we like it or not with working towards a common goal….RIA.  Or Rich Internet Applications.  The challenge is that despite the Web being a disconnected model, to make the user feel like its not. 

I have to admit that Web API, is a technology that quickly and simply allows us developers to work towards that by allowing a new way of sending data back and forth between the client and the server without needing a postback of the page, in any capacity.

In short, Web API functions a lot like Raymond Reddington, it transmit and utilizes information in a way that cuts through all the red tape.  In the show, thanks to underworld connections, Reddington is able to trade back and forth information without having to go through proper channels that the FBI has to. 

Reddington

My job is to deal in information…all kinds. 

But analogies aside, Web API utilizes a special type of controller to allow the ability to sending and receiving information. 

In MVC, the controller is used to route requests from the server to the client.  It traditionally is used to send requests to the server for specific views, and allowing the server to send back the appropriate view after performing any server side functions. 

In Web API, controllers function largely in the same way.  They allow calls too be made to the server, those requests are processed and responses are sent back.  The key difference is though that Web API does it without having to be weighed down by views and models and instead is primarily concerned with passing data.

Enough Theory though, let’s look at the code.

When you create a new project in Visual Studio 2013, thanks to Project Katana there is now only an “ASP.NET Web Application”.  When you do, you will receive the following prompt.

image

When your project is created, you are given the option, no matter what type of application you create to add “WebForms”, “MVC”, and / or “Web API”.  For this project We are going to select “MVC”, and “Web API”.

Now, if you look at your Solution Explorer, you will notice that several key folders and classes have been created for you.

image

First and foremost, I’m going to create a basic MVC Controller and view to display a page.  Below you will see our Home Controller.

   1:  public class HomeController : Controller
   2:      {
   3:          //
   4:          // GET: /Home/
   5:          public ActionResult Index()
   6:          {
   7:              return View();
   8:          }
   9:      }



Just a simple controller that is going to render a view, that’s it.  Nothing special, after all this blog post is about Web API not MVC.  I also will be creating a view for this “Index” action, called “Index.cshtml”.  Below is the view.


   1:  <!DOCTYPE html>
   2:   
   3:  <html>
   4:  <head>
   5:      <meta name="viewport" content="width=device-width" />
   6:      <title>Index</title>
   7:  </head>
   8:  <body>
   9:      <div> 
  10:      </div>
  11:  </body>
  12:  </html>



Ok, now for the fun part.  We are going to build an Web API controller that is going to add two numbers together.  I know ground breaking stuff, but for right now I’m just trying to show the basics, watch this space for more advanced later. 


To start, right click on “Controllers” and select “Add Controller”.  After doing so, you will be prompted with the following menu:


image


We are going to select a “Web API 2 Controller – Empty”.  Given that are creating a very basic Web API controller, this will suit our purposes.  But it’s worth noting that you do have the option to create Web API controllers that are already set up with Scaffolding for Entity Framework or Read / Write actions.


We are going to name our controller “MathController”, and set it up as follows:


   1:  public class MathController : ApiController
   2:      {
   3:          public int AddNumbers(int number1, int number2)
   4:          {
   5:              int answer = number1 + number2;
   6:              return answer;
   7:          }
   8:      }



We have a single action that is called “Get”, and allow for passing two numbers and returning an integer amount. 


Now, the next step is that one I find most people miss.  For Web API to work, we need to set up routing for this controller.  For MVC controllers we don’t need to do this because it is already done for us.  But because we have a lot more flexibility with Web API we need to tell the application how to handle it’s routing.


In the “App_Start” folder, you will see a file called “WebApiConfig.cs”.  By default, Visual Studio created the most basic routing I’ve ever seen.  We are going to add an additional route to this file so it looks like the following:


   1:  public static void Register(HttpConfiguration config)
   2:          {
   3:              // Web API configuration and services
   4:   
   5:              // Web API routes
   6:              config.MapHttpAttributeRoutes();
   7:   
   8:              config.Routes.MapHttpRoute(
   9:                  name: "DefaultApi",
  10:                  routeTemplate: "api/{controller}/{id}",
  11:                  defaults: new { id = RouteParameter.Optional }
  12:              );
  13:   
  14:              config.Routes.MapHttpRoute(
  15:   
  16:                  name: "MathApi",
  17:                  routeTemplate: "api/{controller}/{number1}/{number2}"
  18:                  );
  19:          }



Notice the placeholders we defined, denoting the controller and numbers needed.  The next step now is building the client side script to call it.  That script is shown below:


   1:  <script type="text/javascript">
   2:          function AddNumbers()
   3:          {
   4:              var num1 = $("#number1").val();
   5:              
   6:              var num2 = $("#number2").val();
   7:              
   8:              $.ajax({
   9:                  url: 'http://localhost:50008/api/math/' + num1 + '/' + num2,
  10:                  type: 'Get',
  11:                  dataType: 'json',
  12:                  success: function (data) {
  13:                      $("#divAnswer").html("The answer is " + data);
  14:                  }
  15:              });
  16:          }
  17:      </script>



Now, when you run this, you get the followiing:


image


Ok, so that’s well and great.  And Holy-No-Postback-Batman.


Batman66


Great Scott!


So, I know some of you are saying that you could just have easily built that into your MVC controller using a JSON response, and you’d be right.  The benefits of Web API controllers are really as follows in my experience:



  • Separation of Concerns:  We as programmers strive to separate our classes to have a singular concern, so that they are easier to manage, easier to follow, and easier to test and maintain.  Arguably by using the MVC controller for these types of requests you are mixing navigation concerns with Business / Data Concerns.  By separating your concerns you are making more testable code, and eliminating the possibility that changes to the navigation of your site affects how data is passed to the client.
  • More versatile:  Because we are using a custom controller we are not bound by the rules of how an MVC controller functions and can set this up to work differently.
  • Easy integration with other platforms:  Web API controllers are using HttpRequests to pass data, and all major platforms and languages can use those requests.  So by separating your logic to Web API, I can have my views, iPhone, iPad, and other platforms use the same services with minimal effort for installation. 

Well that’s it for me, like I said this was an intro blog post looking at web api, watch this space for more posts on thsis topic. 

Friday, February 21, 2014

Where’s my service…Service Locator Pattern

Design patterns are one thing that none of us can escape.  If you work in the software development industry and as a part of a team, then odds are that you have run into design patterns. 

When you boil it down, a design pattern is a approach to coding that solves a specific problem.  These patterns are great because they make it possible for other developers to immediately see our code and have some idea of the underlying architecture to it.

Today I'm going to be talking about a newer design pattern, one that I have been using a lot recently and offers several advantages to help decouple your code and build it in a way that separates layers and uses interfaces to remove dependencies...the service locator pattern.

 

What is a Service Locator Pattern Anyway?

A Service Locator pattern essentially when you boil it down is like a pharmacist.  Think about this, when you go to the pharmacist you take a prescription from the doctor of what you need, and you give it to the pharmacist, and based on that script they will give you back the drug on the script, or something that fits the same bill. 

A service locator utilizes an interface in the same way.  You tell it an interface that your interested in, and it returns a concrete class that implements that interface.

Below is an example of a service locator class, this class is usually implemented as a singleton, and serves as the only way that a concrete class can be called.

   1: public interface IServiceLocator
   2:     {
   3:         T GetService<T>();
   4:     }
   5:  
   6:     public class ServiceLocator : IServiceLocator
   7:     {
   8:         private IDictionary<object, object> services;
   9:  
  10:         public ServiceLocator()
  11:         {
  12:             services = new Dictionary<object, object>();
  13:  
  14:             //Add Interface to class references here for repositories
  15:             
  16:         }
  17:  
  18:         public T GetService<T>()
  19:         {
  20:             try
  21:             {
  22:                 return (T)services[typeof(T)];
  23:             }
  24:             catch (KeyNotFoundException)
  25:             {
  26:                 throw new ApplicationException("The requested service is not registered");
  27:             }
  28:         }
  29:     }

Specifically, a service locator operates on the principle of Inversion of Control.  Which is a development technique that over the past few years has gained a lot of traction.  You could do a whole article series on inversion of control, but can find a great article here.

For our purposes, Inversion of Control refers to the concept that instead of the class making the call deciding what it needs, it instead relies on a different construct to provide the concrete implementations of interfaces.

The key to the ServiceLocator class is that it maintains a dictionary listing of the interfaces and the matching classes that implement that interface.  This dictionary is loaded at line 14 above. 

 

Here’s an example:


Now, all of this is well and good but let’s look at some examples.  Let’s say we have an application that handles grading for a school.  And in that application we have the following code.



   1: public interface IGrade
   2:     {
   3:         int PointsPossible { get; set; }
   4:         int PointsEarned { get; set; }
   5:         decimal Percentage { get; set; }
   6:         string LetterGrade { get; set; }
   7:         void CalculateGrade();
   8:         string GradeType { get; set; }
   9:     }
  10:  
  11:     public class Assignment : IGrade
  12:     {
  13:         public int PointsPossible { get; set; }
  14:         public int PointsEarned { get; set; }
  15:         public decimal Percentage { get; set; }
  16:         public string LetterGrade { get; set; }
  17:         public string GradeType { get; set; }
  18:  
  19:         public Assignment()
  20:         {
  21:             GradeType = "Assignment";
  22:         }
  23:  
  24:         public void CalculateGrade()
  25:         {
  26:             Percentage = PointsEarned / PointsPossible;
  27:             if (Percentage >= 90)
  28:             {
  29:                 LetterGrade = "A";
  30:             }
  31:             else if (Percentage >= 80)
  32:             {
  33:                 LetterGrade = "B";
  34:             }
  35:             else if (Percentage >= 70)
  36:             {
  37:                 LetterGrade = "C";
  38:             }
  39:             else if (Percentage >= 60)
  40:             {
  41:                 LetterGrade = "D";
  42:             }
  43:             else
  44:             {
  45:                 LetterGrade = "F";
  46:             }
  47:         }
  48:     }

The IGrade interface, provides an generic version of what ever grade is made up of.  The Assignment class, implements those methods, in addition to providing functionality specific to an exam. 

In our service locator, the class would look as follows:



   1: public interface IServiceLocator
   2:     {
   3:         T GetService<T>();
   4:     }
   5:  
   6:     public class ServiceLocator : IServiceLocator
   7:     {
   8:         private IDictionary<object, object> services;
   9:  
  10:         public ServiceLocator()
  11:         {
  12:             services = new Dictionary<object, object>();
  13:  
  14:             //Add Interface to class references here for repositories
  15:             services.Add(typeof(IGrade), new Assignment());
  16:         }
  17:  
  18:         public T GetService<T>()
  19:         {
  20:             try
  21:             {
  22:                 return (T)services[typeof(T)];
  23:             }
  24:             catch (KeyNotFoundException)
  25:             {
  26:                 throw new ApplicationException("The requested service is not registered");
  27:             }
  28:         }
  29:     }

Notice that we added a single line showing the interface, adding to the dictionary an instance of the Interface, with the value being a new instance of the class. 

Now, let’s  say we have a page that allows us to add assignments, that save method would look like this.



   1: public void AddGrade(int pointsPossible, int pointsEarned)
   2:         {
   3:             IServiceLocator locator = new ServiceLocator();
   4:             IGrade grade = locator.GetService<IGrade>();
   5:  
   6:             grade.PointsEarned = pointsEarned;
   7:             grade.PointsPossible = pointsPossible;
   8:             grade.CalculateGrade();
   9:         }

Notice that our method makes no reference to the assignment class, or anything outside of the interface that it needs.  This allows us flexibility in that if I want to replace assignment, with Exam, I can do so within the service locator, and have it carry through the entire application. 

Why Do We Care?


The benefit of using this approach is that it makes your code more flexible and allows you to swap out old classes for new as requirements change.  This allows you to update your application in a way that minimizes the impact to the rest of the application.


Additionally, this can help with testability, because now using a Fakes Assembly, or just a different Service Locator, I can swap out my application classes for testing classes in my test project.


Service Locator is a valuable tool when applied appropriately and should be consider as a way to reduce dependencies and coupling in your applications.