Using the Microsoft Dynamics CRM Online Web API from your ASP.Net MVC website

August 30, 2016 Leave a comment

The MS Dynamics Web API has a lot of promise, allowing users to authenticate using OAuth2 then granting your application access to their CRM data.  Unfortunately, the documentation provided by Microsoft is misleading at best.

After bashing my head against the wall for about ten hours, I got a response back from an MS developer with the following working solution, which I’ve padded-out and am sharing here to hopefully save somebody else the headache.

Here’s the working code sample, just drop in as a standard ActionResult in your MVC project – no other code is required/involved.

public async Task<ActionResult> GetAccountsFromDynamics()
{// Once you've created your Native Client in Azure AD, you can get the clientID for it
var azureTenantGuid = "***";
var clientID = "***";
var tokenRequestUrl = string.Format(@"{0}/oauth2/token", azureTenantGuid);
// The credentials for the CRM *user* that you are accessing CRM on behalf of
var crmUrl = "";
var userName = "***";
var password = "***";

// Connect to the authentication server
var request = (HttpWebRequest)WebRequest.Create(tokenRequestUrl);
request.Method = "POST";

// Write our request to the request body
using (var reqStream = await request.GetRequestStreamAsync())
var postData = string.Format(@"client_id={0}&resource={1}&username={2}&password={3}&grant_type=password", clientID, crmUrl, userName, password);
var postBytes = new ASCIIEncoding().GetBytes(postData);
reqStream.Write(postBytes, 0, postBytes.Length);

// Call the authentication server and parse out the response
var accessToken = "";
using (var response = (HttpWebResponse)request.GetResponse())
// Proceed interpreting result
var dataStream = response.GetResponseStream();
if (dataStream != null)
var reader = new StreamReader(dataStream);

// The response is returned as JSON, these lines just conver it to a C# object. The format includes our access token:
// Example format: {access_Token: "abc...", scope: "public"}
var json = reader.ReadToEnd();

var tokenSummary = json.FromJson<TokenSummary>();
accessToken = tokenSummary.access_token;

// Now make a request to Dynamics CRM, passing in the toekn
var apiBaseUrl = "";
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var result = await httpClient.GetAsync(apiBaseUrl + "accounts?$select=name&$top=3");
var accountInfoJson = await result.Content.ReadAsStringAsync();

// You're done!
return Content(accountInfoJson);
Categories: General Tags: ,

Read our new book – How to know if your software developer is trying to kill you

August 29, 2016 Leave a comment

How to know your software developer is trying to kill you.jpgWoohoo!  Eight months in the making, my book is now published and released into the wild.

How to know your software developer is trying to kill you is available from Amazon or you can grab a free electronic copy from our website.

Everything you need to know to get started with software development

The book is a simple guide for people planning to get started with software development.  By the end you should be able to:

  • confidently select a software developer.
  • assess the price your developer is charging.
  • understand the basics of software development.
  • ensure your application is future-proofed and adaptable.
  • “speak geek” and actually understand what your developer is talking to you about.

It’s basically the spiel I give to any new client.  Plus some pictures of bears.


Categories: General

Choosing between open- and closed-source software

This is a pre-release chapter from my upcoming book about developer selection and beginning IT projects – I hope you enjoy it.  For more on the book, or notifications about its release date, please send me a quick message via my website.

Bruce is a chef who is famous for his delicious tomato soup. People flock to his restaurant from miles out of town and naturally he keeps the recipe a closely guarded secret, lest another chef cut in on his business. In this respect, we would call Bruce’s recipe “closed source”, meaning that while we can see the end result, we cannot see how it is made.

Later in life, Bruce decides he’s had enough of the restaurant business retires. Without a restaurant to serve it in, Bruce releases his soup recipe so that other chefs may serve it, or people may even make it at home themselves. Bruce has essentially “open sourced” his recipe.


In a similar way, a lot of modern software is now open source, meaning that anybody (usually another developer) can see exactly how the platform was built. This initially seems like a ridiculous idea (if everybody knows Bruce’s recipe, they will make the soup themselves and his sales will plummet). However the issue is not so cut-and-dried and open-source software has some other compelling benefits for its vendors:

  • open source software fosters a community of trust and transparency amongst its developers
  • other developers (many better than the vendor themselves) will spot and fix bugs and contribute them back to the community
  • technically it is possible for somebody to copy and use the software, so the risk of people doing this is real. But if they do so, their version will become incompatible from the ‘base’ version and they will forego any the aforementioned updates or bug-fixes from the community and/or vendor. So this is actually lower-risk than you might initially think

However, open-source software also suffers from a variety of ailments:

  • you still need a strong governing body to keep the software updates on track and in a consistent direction for the software’s evolution
  • failing that, because the software is contributed to by a wide variety of disparate developers, there is no single accountable entity to address problems when things go wrong
  • in-fighting and personal/political differences amongst members of the open-source community have brought many open-source projects to a standstill

To clarify, when talking about open-source here I do not mean that you open source your software product (that will be just for you). Instead I’m talking about the platform that your developer uses to build your software.

The open vs closed debate has very passionate advocates on both sides, but I don’t think it really matters. So here’s my recommendation to you:

  • open source is usually free (or at least cheaper), but any money you save is minimal compared to other costs in your business
  • open source is touted as having a stronger & more giving community but in my experience there is nothing lacking in any of the ‘paid’ communities. Developers in general are very willing to share their time & expertise, regardless of the platform
  • there are other much more important considerations in selecting a platform, like speed and developer support
  • most systems use a variety of platforms/languages, so you will probably end up using a bit of both anyway

Ultimately I suggest you simply ignore whether a platform is open- or closed-source and evaluate them on their other merits

Categories: General

Meet the star of my new book


Jenny from has found the perfect tone for my new book – How to know if your software developer is trying to kill you.

The illustrations strike the perfect tone – bring fun and simplicity to an otherwise pretty dry subject.  We’re working through the rest of the illustrations now and the book should be ready to go by mid-year.

Remember you can download an early preview from our site.

Categories: General

SQL Server–Always use sp_executesql over exec

April 27, 2016 Leave a comment

Today I was looking through some legacy code and found a loop that dynamically created a SQL string and executed using exec().

A quick check of the execution plans showed that SQL Server was creating a new plan for each loop.

We changed it to use sp_executesql instead.  Because this uses parameterised queries, it can re-use the execution plan each time.

Final result – our routine ran 9 times faster and as a bonus it used about a 1/3 less CPU.  Happy days!

Categories: General

Is your SQL Azure sys.event_log empty?

April 26, 2016 Leave a comment

Yip, mine was too.  The trick is that you have to query on the master database and filter by database_name:

select * from sys.event_log where database_name=’<your db>’

Happy debugging!

Categories: General

How to choose a software developer

March 21, 2016 1 comment


This is a pre-release chapter from my upcoming book about developer selection and beginning IT projects – I hope you enjoy it.  For more on the book, or notifications about its release date, please send me a quick message via my website.


Surely the single most important decision you make now is selecting the person that converts your idea into the actual software.  Everything you say or show your developer will be filtered through their own experience, preferences & expectations of how software should behave, so you want to find a good one right from the start.

Unfortunately (and as with most service industries like lawyers or accountants) you don’t usually realize you’ve made a bad choice until something goes wrong – and that could be years down the track.  The key to mitigating this is to ask the right questions and look for clues early in the relationship.


If your website goes down in the middle of the night, or a client has an urgent feature request, you need your developer to be ready and available. 

Now, I’m not talking about when they go on holiday or are away sick – these are predictable and part of life.  I’m talking about the times when they already have a 12 hour day behind them and your site goes down as they’re walking out the door. 

Promptness & availability are the type of thing that is best observed over time, and by then it’s too late to change (cheaply).  But there are still some helpful things to look for early on:

  • when you ask for your initial meeting request, are they quick to get back to you?

  • if they are late on something, do they advise you early or simply fail to deliver?

  • are you able to get their mobile number or just an office number?

It is my opinion that by virtue of them being the gatekeeper between you and your product, they should understand that being highly available is part of the job.  But don’t abuse their generosity.  If you’re pulling them out of family dinners with something you’d like to have – or worse, something that is urgent but late because you were disorganized – then you might be looking for a replacement soon.


As I said before, every idea you have for your product will be filtered through your developer, so needless to say it is imperative that you can communicate with them well.

There’s also much more to communication that just conveying an idea to them.  A good developer will listen to what you’re trying to say and fit that into the short- and medium-term requirements of your system.  They may recognize that two of your requirements are competing with each other, or two could be rolled into one to save money.

Ideally your developer will also have an appreciation of the non-technical parts of your business, such as sales, and advise on how your product can be built to complement these.

Finally, it also helps if you have a personal rapport with the developer.  It’s really important that you remain partners in the project and don’t devolve into adversaries.  Clear and open communication is key to this.

The best way I know to establish a developer’s communication level is to….communicate with them!  Organize a face to face meeting and make sure you have a chat about non-technical things too.

Word of mouth

As with most service industries, sometimes the best indicator of a reliable supplier is simply referencing their other work.  If you don’t know anybody with the first-hand experience that you need, it’s perfectly reasonable to ask prospective developers for examples of previous work or references from other clients.

Keep in mind that different software projects require different platforms and types of developers.  Even if a friend has recommended an individual, you still have to make sure they are suited to the type of software you are building.


The time it takes to develop a software feature generally increases exponentially as more features are added.

Or, another way of looking at it is the good old fashioned 80/20 rule – the last 20% of your software feature will take as long to build as the first 80% did.

If yours is a multi-million dollar company, you can probably afford to push features to 100%.  But when you are starting out you need to get the best value for money you can, and this means knowing how far to push a feature. 

Unfortunately for you, it’s not always apparent to non-developers where this line begins and ends so you need to rely on your developer for guidance.  In some cases, this may mean building code which the developer considers to be of lower quality, but they need to step back and ask themselves if the feature is good for the business or just their ego.  This is what I mean by a pragmatic developer.

Unlike many of the other attributes in this chapter, you don’t need to know how to recognise a pragmatic developer – you can usually just make one.  Tell them from the start that you value pragmatism and want them to view the software from both a technical and business perspective.


The price of your developer is one of the first and most tangible things you can ascertain about them.  Obviously you want to keep your costs low, but here’s a few things to keep in mind:

  • a low hourly rate means nothing if they take twice as long to complete the project

  • a higher hourly rate generally means the developer is more experienced, which means that are better equipped to handle that one in a hundred disaster that could tie up a junior for days

  • your choice of platform will be a large influence on price – platforms with high licensing fees or development tools tend to have their costs passed on to you, the client (I talk more about platform choice below)

  • other factors in this chapter have an indirect impact on value-for-money and therefore the ‘price’ you pay for your developer.  If you value promptness and good communication skills, be happy to pay for them

Finally, people often concern themselves too much with the up-front and short-term costs of a software developer.  Trust me – a talented & reliable developer who prices themselves accordingly, will save you money in the long run with an extensible architecture and software that your customers love.

Sweat equity

Sweat equity is a colloquial term for getting paid in shares/interest in your company, instead of cash.  A typical example is that developer may be offered 5% of your company if they work for half their hourly rate.

If done fairly and openly, sweat equity is a pretty good way to get a good developer at an affordable price, especially when you are not even sure if your product will even sell.  It also means that your developer is “invested” in the success of your project and more likely to go the extra mile.

Just keep the drawbacks in mind too:

  • your developer has other clients.  If you are paying them a lower hourly rate, they may be inclined to go for the short-term benefits of the other work

  • an invested developer will want more say in how the product evolves.  Even if their ideas are great, beware of having too many opinions and styles contributing to your product.  I advise that you outline responsibilities from the start of your contract so that everybody knows their role

  • the more they reduce their rate, the more sensitive your developer will become to drawn out deadlines and scope creep, because every extra hour they work means more money lost (as opportunity cost working for other clients).  Compare this with the usual mechanism of simple “time for money”, where your developer can at least console themselves with a higher income

  • if you replace the developer, you may have unwittingly given away 5% of your company to somebody no longer involved.  A good tip here is to pay equity as a share of annual revenue, for every year that they work for you.  That way you’re only exposed for the next 12 months (there are other issues to address with this, but I’m already too far down the rabbit hole – best talk to a lawyer)

As you can see, sweat equity may ironically result in competing instead of mutual interests.  Be careful.

How to know if your developer is ripping you off

You don’t.  As with most service industries like lawyers and accountants, the market puts a value on a developer’s time and if nobody is prepared to pay it, they lower their price.

Remember also that a smart developer (or lawyer, or accountant) actually wants you as a long-term client.  If their price means you drain your development budget without going to market then you’ve both lost.

So if I had to guess – no, your developer is not ripping you off.  But here are a few ways to help mitigate the possibility:

  • as your product evolves, the time it takes to maintain it will also increase and with it your development charges.  This is natural and to be expected.  But if their output suddenly halves, they might be taking advantage now that you’re an entrenched client

  • if your developer is working by the hour, it is reasonable to ask for a breakdown of how that time was spent.  Most developers use time-tracking software so this should not be a problem.  Get into the habit from day one so that it doesn’t feel accusatory if you begin later

  • if you have access to the source code, you are technically able to track how much code is being written.  Disclaimer: code is about quality not quantity, so you’re looking for averages and changes over time

Other skills and interests

I’ve always found that developers with skills and interests outside of computers are more creative and (just as important) easier to work with.  See if you can glean a little about these aspects of their life when you are speaking with them.

Similarly, ask how your developer keeps up with tech trends and/or participates in the tech community.  This could be as simple as subscribing to industry newsletters or attending monthly meetups. 

Activities like this show an enthusiasm for their craft beyond their weekly paycheck and are a really good sign.

Changing developers

Hope for the best, prepare for the worst – if you are unable to continue with your developer for any reason, you need to be able to salvage what you can and hand it over to the next person as quickly and cheaply as possible.  To do this, there are two things that must happen before you need them.

Get a copy of the source code

Source code refers to the programming your developer has done to build your software.  At the end of the day, it is literally just a set of files stored on a computer, the same as any other collection of computer files.

When developing, these files are on the developer’s computer, so if they disappear and their computer goes with them, your software is lost.  Forever.

A common solution to this is something called source control which is a piece of software that the developer uses to track the work they do.  One of the features of source control systems is that they allow multiple people to view the files.  So, ask if your developer is using source control and if so, simply ask for your own login.  You can then download the code whenever you like.

Failing this, there are more manual systems like popular file-sharing sites or even just zipping and emailing the source code to you once a month.  Whatever mechanism you choose, make sure you do it from day one and don’t let it lapse.


Once your new developer has the source code, they need to know how it works.  A lot of software is self-evident and easy to follow for even an inexperienced developer, but it can very quickly get complicated.  Your new developer will be able to work things out eventually, but it would be a lot quicker if the software was explained to them.

This is where documentation comes in, which as I’m sure you’ve guessed, is simply a case of your developers annotating their code as they go along.  The level of documentation ranges from massive multi-page files with working examples, down to simple one-line “comments” within the source code itself.

For this purpose, you definitely don’t need the former (it’s expensive) – just ask that your developer maintains good coding practice and comments on their work as they go along.  Your new developer will be very grateful for it.

This has been a sneak preview of my upcoming book about developer selection and beginning new IT projects.  Find out more at

Categories: General