Archive for Microsoft category

5 simple steps to publishing a NuGet package

There is a fair amount of info on making and publishing NuGet packages but I couldn’t find a simplified guide for the simple case. Here it is and start by downloading nuget.exe and putting it in your path.

1. Multi-platform considerations (optional)

Supporting multiple platforms gives you a choice to make:

  1. Portable Class Library (PCL)
  2. One project with MSBuild magic
  3. Multiple projects

If you can go with PCL do it. For CSharpAnalytics we use platform-specific system info and hooks so it’s not an option – we went with multiple projects.

Multiple projects

Creating a separate .csproj for each platform and putting in the same folder means adding files isn’t too painful (show all files then include the ones you need) but you do need to take steps to make sure the build process for the projects don’t interfere with each other by separating the bin and obj paths:

  1. Set the output path in the Build tab of project properties to be unique per configuration to for the bin files, e.g. “bin\Net45\Release\”
  2. Edit the .csproj file adding a BaseIntermediateOutputPath tag for obj files, e.g. <BaseIntermediateOutputPath>obj\Net45</BaseIntermediateOutputPath>

2. Create your .nuspec definition

Now that you know which release dll files you need to include you can go ahead and create the nuspec file that tells nuget how to package your files up.

Open a PowerShell and type nuget spec to create you an XML file to edit in your text editor

Once you’ve entered your author details, a snappy description and links to your project page and license you can then add the files. Libraries will want to copy the .dlls into the lib folder with element like these:

<file src="..\bin\Net45\Release\MyLibrary.dll" target="lib\net45" />

Each platform will require a specific target and they should use platform name (e.g. net45, sl5, windows8) described in the NuSpec creating packages documentation. That page has a lot more detail on things such as content file types etc.

If you prefer a graphical UI then NuGet Package Explorer will make your life easier.

Remember to check your .nuspec file to source control (there is nothing private in it) and add it to your solution as a solution item so it doesn’t get missed.

3. Create your .nupkg package

The easiest part of the process. From PowerShell type:

nuget pack yourfile.nuspec

If all goes well it will create yourfile.nupkg.

4. Test your package

Just because your package was created doesn’t mean it works and you don’t want to publish to the world until you know it works especially given you can’t delete packages from NuGet:

  1. Create a folder to be your own private testing NuGet repository, e.g. c:\testnuget
  2. Publish to your test repository with nuget publish yourfile.nuspec -source c:\testnuget
  3. Configure Visual Studio to use your test repository by going to Tools > Library Package Manager > Package Manager Settings > Package Sources and then adding your test folder to the Available package sources test
  4. Create a new test application and then add a reference using Manage NuGet Packages to choose your new package from your test repository.
  5. Write a few lines of code to test you can actually use your package ok!

5. Publish to the world

Okay, you’re now ready to publish. If you haven’t yet signed up for an account over at Nuget.org you’ll need to do that first.

  1. Go to Your Account and copy your API key
  2. Run the PowerShell command nuget setApiKey followed by your API key, e.g. nuget setApiKey 99995594-38d2-42cd-a8b1-ddcd722bb7e7
  3. Run nuget publish yourfile.nuspec again this time without the -source option to publish to the default public repository

[)amien

Probable C# 6.0 features illustrated

C# 6.0 is now available and the final list of features is well explained by Sunny Ahuwanya so go there and try it with his interactive samples page.

Adam Ralph has a list of the probable C# 6.0 features Mads Torgersen from the C# design team covered at new Developers Conference() NDC 2013 in London.

I thought it would be fun to show some before and after syntax for comparison and in doing so ended up with a few thoughts and questions.

1. Primary Constructors

Shorter way to write a constructor that automatically assigns to private instance variables.

Before

public class Point {
    private int x, y;

    public Point(int x, int y)
        this.x = x;
        this.y = y;
    }
}

After

public class Point(int x, int y) {
    private int x, y;
}

Thoughts

  • Do you need to independently define x and y?
  • Can you still write a body?
  • How would you make the default private?

This solution feels too constrained, would have preferred something like:

public Point(set int x, set int y)

That set the property and optionally created a private one if it didn’t. Would allow bodies, use on multiple constructors etc.

2. Readonly auto properties

Readonly properties require less syntax.

Before

private readonly int x;
public int X { get { return x; } }

After

public int X { get; } = x;  

Thoughts

  • Love this.
  • Very useful for immutable classes.

3. Static type using statements;

Imports all the public static methods of a type into the current namespace.

Before

public double A { get { return Math.Sqrt(Math.Round(5.142)); } }

After

using System.Math;
...
public double A { get { return Sqrt(Round(5.142)); } }

Thoughts

  • Not something I’ve run into often but no doubt very useful for Math-heavy classes.
  • Could be useful for Enumerable LINQ-heavy classes if it works with static extension methods.

4. Property Expressions

Allows you to define a property using a shorthand syntax.

Before

public double Distance {
    get { return Math.Sqrt((X * X) + (Y * Y)); }
}

After

public double Distance => Math.Sqrt((X * X) + (Y * Y));

Thoughts

  • Small but useful syntax reduction.
  • Has nothing to do with System.Linq.Expression despite the name.

5. Method Expressions

Allows you to define a method using a shorthand syntax.

Before

public Point Move(int dx, int dy) {
    return new Point(X + dx1, Y + dy1);
}

After

public Point Move(int dx, int dy) => new Point(X + dx, Y + dy);

Thoughts

Same as Property Expressions.

6. Params for enumerables

No longer need to define your params methods as an array and force early evaluation of the arguments.

Before

Do(someEnum.ToArray());
...
public void Do(params int[] values) { ... }

After

Do(someEnum);
public void Do(params IEnumerable<Point> points) { ... }

Thoughts

  • Can have params methods for IEnumerable and array side-by-side? Probably not.
  • Is evaluation deferred until evaluated if you pass a single IEnumerable instead of a params?

7. Monadic null checking

Removes the need to check for nulls before accessing properties or methods. Known as the Safe Navigation Operator in Groovy).

Before

if (points != null) {
    var next = points.FirstOrDefault();
    if (next != null && next.X != null) return next.X;
}   
return -1;

After

var bestValue = points?.FirstOrDefault()?.X ?? -1;

Thoughts

Love it. Will reduce noise in code and hopefully reduce null reference errors everywhere!

8. Constructor type parameter inference

Removes the need to create static factory methods to infer generic types. This is helpful with Tuples etc.

Before

var x = MyClass.Create(1, "X");
...
public MyClass<T1, T2> Create<T1, T2>(T1 a, T2 b) {
    return new MyClass<T1, T2>(a, b);
}

After

var x = new MyClass(1, "X");

Thoughts

  • Another great addition.
  • Does it understand list and collection initializers to automatically determine the generic types too?

9. Inline declarations for out params

Lets you declare the out variables inline with the call.

Before

int x;
int.TryParse("123", out x);

After

int.TryParse("123", out int x);

Thoughts

  • Not a particularly large syntax reduction.
  • Shorter code for Try methods and DirectX.

Wrapping up

Hopefully there are a few more gems to come that would help reduce noise. Would especially like to see syntax that wired up an interface to an internal instance variable where not specifically overridden to aid in encapsulation, e.g.

public MyClass : IList => myList {
  private IList myList;

  public Add(object item) {
    // Do something first
    myList.Add(item);
  }
}

[)amien

Windows media keys on a regular keyboard

Many full-size Windows keyboards come with extra buttons some of which are of questionable value but the volume and music controls are useful especially if you’re a programmer that likes to listen to music all day.

Unfortunately my two keyboards of choice (DAS Ultimate and Topre Realforce) do not come with such controls. Neither does my MacBook Pro but Apple do the elegant thing and repurpose some of the function keys.

Apple media control keys

If only I could do that on my keyboards and take advantage of the Windows global music controls. (It also makes testing a bit easier if you support background music playback in your Windows Store apps). In fact Windows 8 even has a great little pop-up that comes up to show you what you’re doing:

Windows 8 music overlay

Thankfully with the help of the wonderful AutoHotkey you can. This great little tool lets you remap keys globally or per-app and even put some scripting and macro’s in place to really take control of Windows.

My keyboards don’t have a Fn key like the Mac but given the Windows key is the modifier for system shortcuts we can repurpose that! Once you’ve unpacked and run AutoHotkey simply right-click on it’s system tray icon and choose Edit This Script then paste the following into the Notepad Window that opens and hit save:

; Windows Media controls in Mac positions
#F7::Media_Prev
#F8::Media_Play_Pause
#F9::Media_Next
#F10::Volume_Mute
#F11::Volume_Down
#F12::Volume_Up

Now simply right-click on AutoHotkey and choose Reload This Script and enjoy Windows media controls on your laptop or regular keyboard!

[)amien

Working at Microsoft

Ahmet Alp Balkan on the Microsoft Azure team reflected on his experiences at Microsoft. His experiences do not exactly match mine (initially on LINQ to SQL, then Entity Framework and finally xbox.com) but I recognize some of his points.

Here is some further discussion along with some other thoughts that have come up over the years. A lot of these don’t apply just to Microsoft and some are useful for people new to the industry to think about.

Firstly

People think of Microsoft as a single entity with a sole focus and one opinion.

That’s about the worst mistake you can make.

Microsoft is like hundreds of small companies that often work together but sometimes against each other. They have different processes, dynamics, attitudes and goals not only within the same division but also within the same building or floor.

Thinking your experience with one team is a reflection of the whole company is short sighted. Microsoft employs almost 100,000 people including over 40,000 in the Redmond area alone.

It’s like a small country.

Stack of books“Expect no documentation”

Documentation can sometimes be found checked in with source code, in wikis, buried in Sharepoint sites or OneNote. Wherever it may exist it will be out of date by the time you find it.

Documentation can only be up to date if it is never changed or you have a team of incredibly rare developers who like to read and write documentation more than code. Don’t fret unless nobody has the source code.

It might appear that people are critical and dropping dead will kill the project because everything gets funnelled through one or two people but that’s not the case. Many people know more than they let on but don’t want to be involved on a day-to-day basis because they have moved onto something better. When a dire situation arises these people step up.

“Not everyone is passionate for engineering”

It’s true not everyone you meet will be interested in quality software engineering. Some people just want to get the job done and go home. That happens to across all jobs and all walks of life. It’s a personal choice.

Ask yourself how many engineers you meet are passionate about delivering great experiences to users. Do they prioritize their own wants and desires such as a high test coverage in a rarely-regressed area over a simple useful feature many users are asking for.

Software engineering is a means to an end.

Your customers aren’t interested in software engineering. They want a useful tool or something entertaining.

What you want is to be able to sustain happy paying customers.

“2-3 hours of coding a day is great”

When you’re coding for yourself you are the user. You can make the decisions quickly and know what you’re asking of yourself. There is no communication overhead.

When you work with customers that slows things down especially if they’re not easy to get hold of. Most of the time you work with a project or program manager (PM in Microsoft speak) who advocates for the user. This speeds up the simpler decisions but complex or difficult decisions will still require time.

With more developers, testers and partners the communication overhead increases. You make educated guesses and perform iterative steps and keep everyone involved. If those guesses are wrong they should show up quickly. You can address those wrong guesses before too many features, code or documentation rely upon them being implemented wrongly.

If a decision can’t be easily reversed in the short term the it needs discussion. That takes time.

Two hours of coding a day can be fine. If it takes the product in the right direction.

“Not giving back to the public domain is a norm”

Whether you contribute code back to the outside world is defined by your personal goals and the team around you.

Some teams like the ones on ASP.NET MVC and Entity Framework have completely opened their stacks. Other teams have contributed back to existing projects. Your might not be able to do either… yet. Things are changing at Microsoft as these projects show and it can take patience and perseverance to make it happen.

It can be painful for a developer to break through the resistance of his own team and legal. There are reasons not to:

  • It takes time and effort to put something out for public consumption
  • It can take ongoing time and effort to maintain that code publicly
  • If your code is innovative to your business area you might be giving the competition a boost
  • Legal may perceive code contributions as a patent minefield

If your code doesn’t give you an edge then why are you writing it? Intellectual challenge? Do that on your own time. If something open source already provides important functionality you need to get permission to use that instead. Don’t give your competitors your edge while it counts.

“It’s about getting it done”

Shipping good products leads to success. Waiting for perfection leads to failure.

Shipping is everything. True, it’s not always first-to-market that wins but being late won’t help unless you have something that’s radically different. A lower bug rate or a slightly more polished experience won’t be enough.

It’s incredibly easy to ship updates today. Concentrate on getting the features usable and ensure it doesn’t harm the user. That means no corrupting data or major security issues.

All we have to decide is what to do with the time that is given to us. - Gandalf ;-)

Your product will ship with bugs. If you have a good test team you’ll know what some of them are. Fix the critical, the blockers and the high-priority as best you can. Your competition isn’t going to wait, nor are your users.

The more easily discovered or hard to work around a bug is the quicker it will be found. A hard-to-reproduce bug that’s easy to work around isn’t worth the time you already spent thinking about.

“Copy-pasting code can be okay”

Starting a shared library between teams requires an intentional co-ordinated effort.

  • When a team modifies a shared library do they know how it affects other teams? No.
  • Will the other teams be carefully monitoring the shared library? No.

Copy and pasting is fine for odd classes. You get code re-use without having to set-up merging, policies and ownership.

Fixing a critical bug in shared code always requires co-ordination between teams whether they copy and pasted the code or whether they take a shared dependency.

Bugs can hide bugs. Fixes can reveal more bugs.

“Code reviews can be skipped”

There are a few things people want to get out of a code review and how well it goes depends on the people interested in reviewing the code.

How well did I implement this feature?

We’d all love to know this but it’s the hardest thing for somebody to critique in a code review. They probably don’t know the requirements well and unless they’ve been in that area of code lately they probably don’t know what the alternatives are and why you went with this approach. To know as much as you do about implementing this feature they would likely have needed to have spent as much time on it as you.

Code reviews rarely provide good feedback in this area unless you’re new to the team – in which case you should probably have pair-programmed instead and had a better experience.

Are there any glaring bugs?

If you’re a professional you should have read your code back and forth several times and probably refactored it until it looked good. If regular bugs or code reviews point out issues then you need reviews for this. Some people are much better than this than others – it’s one of personal discipline.

You should spend far more time reading your code than you did writing it.

Did I regress performance, security or reliability

This is about the best thing you can get out of a code review. People know arcane little bits about the system that are probably not well known and tricky to document. If you’re working in code that is called all over the place go for the code review especially.

“So… can code reviews be skipped?”

I’d be lying if I said I had a code review for everything I did. Sometimes you know the code base like the back of your hand and there are plenty of checkpoints further in the process as well as other eyes constantly on the codebase. A lot of open source projects work well this way.

Never skip a code review when:

  1. You’re in a rush. That’s exactly when you need it most. Send it to multiple people and wait for 1 or 2 responses – it parallizes well.
  2. The code is used everywhere. The more callers, the more places to fail.
  3. The code accesses sensitive data. Patching after a breach is too late.

At the end of the day ask yourself “Could this code damage the reputation of the company and therefore my career?”. If the answer is YES you need a review.

Competition and stagnation

When new markets and opportunities appear it often doesn’t belong to one team and many teams can find themselves in the same space as executives go for the land-grab. This behaviour is actually encouraged at all levels in the annual reviews … “expand your influence”.

Unfortunately this often results in customer confusion, especially as products expand and subsequently overlap. LINQ to SQL and Entity Framework are my own personal experience this but I’m sure you think of plenty more.

Conversely once a market is owned by a team it can stagnate quite quickly. Microsoft Billing and the MVP/MCP portals spring to mind. The latter requires Internet Explorer only to function. In compatibility mode no less. There are more than a few Microsoft web sites looking very dated.

Be aware of what other teams are doing and how it impacts yours. Treat teams in similar spaces as potential competitors but remember that their public failures reflect on the whole company including you.

A busy whiteboardBring solutions, not problems

The article reminded me of one from a year or two back where somebody left Microsoft after a promising start that turned into a series of bad reviews after he started trying to change things by pointing out to people what’s wrong.

People know what’s wrong.

Microsoft like other big tech companies has a lot of smart people working for it. Smart people are busy.

Going around telling people that they’re doing things wrong or that things need to change without a plan is never going to make you friends or cause change. Guess what. Career progression is part popularity contest.

Worried the new site has so many hands it’s going to be a mess?
Don’t complain, do something. Figure out a solution that also solves pain for others so they’ll buy in. Work with the designers on a grid based PSD template, codify it into CSS, check it in and get it included on every page. Sacrifice a few lunchtimes to train the team on it. Get it done.

Think the approach you’re taking for security isn’t enough?
Liaise with experts, find the issues, develop or adopt libraries, tools and techniques to make the problem go away.

Get to the root of a problem and make sure the solution fits both sides

If you interface with customers directly through one of the many partner or support programs or indirectly through forums and twitter you’ll see upset customers. It’s hard, but it applies to all products. Upset people forget there are real people working hard on the product they use. That if they scream and shout they’ll get what they want. It doesn’t work that way.

You will come across good ideas, suggestions and feature requests internally and externally. Take the time to distill them down into small useful bite-sized pieces. Take from the critic’s what you can use for a better product and forget the rest.

People develop for themselves and what makes a great solution for them might not be for other people using your product.

Teams can be resistant to fully-baked solutions being handed to them. Come with bite-sized pieces and a few ideas on how they could interact. Let the solution flow out of discussion and debate. The result will be better than what you could come up with anyway.

This is even more important when dealing with other teams. They know their internals, other customers and future roadmap better than you do.

Expert means something different on the inside

Whether you’re an MVP or wrote a best-selling book joining the team behind it means you’re about to become a different type of expert.

You’re an expert on using the product. On the features that shipped. On the way it’s used.

You are about to learn is why the product is shaped that way. The hard decisions, the cut features, the implementation and constraints.

Brace your ego for impact. It doesn’t matter that you can write any kind of LINQ query off the top of your head and have used it in several apps. When you join the team behind it you’re in for a crash course in expression trees, compilers and query reduction.  How far down does the rabbit hole go?

All those great ideas and suggestions you had as a user? Be prepared to find out 99% of them aren’t original. There are reasons why they’re not there. Ideas are cheap.

It’s now your job to figure out how to make them happen. Execution matters.

Conclusion

Don’t get me wrong, I loved working at Microsoft. It’s an exciting place to be with so many cool things going on. Leaving was a hard decision motivated by factors not on this list.

Like any job there will be challenges. Some unique to Microsoft, some big-company specific and some near-universal that you may be experiencing for the first time if you’re new to the industry.

Learn, adapt, thrive.

[)amien