Write C# on a Mac like a Champ!

Let’s face it – Apple makes some of most desired notebooks in the industry. The MacBook Pro Retina is loved by many developers for its screen real estate and silent but robust performance. The MacBook Air, on the other hand, offers portability and long battery life for productivity. If you own one of these, you know that you’re not alone in your love for notebooks with glowing fruit!

If you are a Microsoft stack developer, you may want to use a Mac as a development machine and write C# code – is that even possible? Alternatively, you may have always been a Mac developer, but are interested in .NET going Open Source and want to try out some native ASP.NET on OSX. Either way, your goal is to marry up two of the best things for developers: quality Mac hardware and C# comfort. Good news – they happily coexist! Let’s talk about options in this article.

Windows Finds the Perfect Host

It is always good to see innovation from PC manufacturers, like the recent beautifully thin Lenovo 2-in-1 Yoga Pro 3. Not to mention, Microsoft’s own tablet convertible, the Surface Pro 3, is selling like hot cakes. But it is also no secret that MacBooks make wonderful laptops for running full Windows as an OS. As an added bonus if you have a MacBook Pro Retina laptop, your Windows installation enjoys high resolution, as you can see in the image below of Windows running on my Mac. Developers love screen real estate, even at the expense of squinting eyes, right?

ScreenResolution

There are two ways you can run Windows on a Mac:

  1. Bootcamp – This is the Apple way of allowing you to run Windows on an Intel-based Mac. Simply use the built-in Bootcamp Assistant, make a partition and install Windows. Once done, you can easily boot into Windows instead of OSX and reuse all of the I/O (input-output) drivers for peripherals. In this mode, Windows is running natively “on the metal” and you get the full performance benefits. This of course means you can install Visual Studio and write C# all day, just as in a Windows machine.
  2. Virtual Machines – If choosing which OS to boot into isn’t your cup of tea, your other option is to run Windows in a virtual machine (VM) with OSX acting as the host OS. There is dedicated software that will do the heavy lifting for your VM – like managing virtualization, memory and peripherals. Parallels and VMWare Fusion are two excellent options for running Windows VMs on your Mac. With customizable virtualization, resource fine-tuning options and easy switch-ability between Windows/OSX , you should be rocking Windows running as a VM in no time. And just as easily, you can install Visual Studio inside your Windows VM and write C# to your heart’s content.

Now, whether you go BootCamp or VM, you are running full Windows. And that means, you get the benefit of Telerik DevCraft to supercharge your .NET productivity for any type of application you are building!

Visual Studio ‘Monaco’ Editor

Although not fully baked in yet, C# is about to get a new ubiquitous code editor – yes, the browser – any browser across any OS! C# in the browser comes courtesy of a special light-weight editor codenamed ‘Monaco’, which was launched with Visual Studio 2013. To quote Microsoft – “With Monaco, we want to provide developers with a lightweight, friction free companion to the Visual Studio desktop IDE that is accessible from any device on any platform. Monaco is a rich, browser based, code focused development environment optimized for the Windows Azure platform, making it easy to start building and maintaining applications for the cloud.” Check out this Channel 9 video series on how to get started with Visual Studio Online Monaco editor, as well as keeping up with latest enhancements.

Want to try out the Monaco editor today? Well, it is really geared to work with sites hosted in Windows Azure for now. But you can absolutely write the C# code-behind code for the server-side, hook up your code to a source control and perform builds/deployments. Here’s how to get started:

  1. First, you’ll need to have a Windows Azure account. Sign up for free.
  2. Log in to the Windows Azure Management Portal.
  3. Create a new Azure Website from the big ‘+’ sign on bottom left.
  4. Open up Website Configuration and turn on the option for ‘Edit in Visual Studio Online’.
  5. From the Website dashboard, click on the ‘Edit in Visual Studio Online’ link.
  6. Enjoy C# edits in your browser!

Here are the steps visually, starting with creating the Azure Website – choose your Azure Subscription and hosting appropriately:

WebsiteCreate

Next up, navigate to your newly created Website Dashboard and click on the ‘Configure’ tab. Scroll down a little with your configurations and you’ll see the ‘Edit in Visual Studio Online’ setting. Turn it on to see the magic:

EditInVSConfig

Back on your Website Dashboard, the link to ‘Edit in Visual Studio Online’ lights up:

EditInVSLink

Go ahead, and click the link. Voila – a new page opens up with light-weight code edits for your Windows Azure website. You can see here that I added a new Test.cs file and I’m able to write C# code in the Chrome browser on my Mac – how cool is that?

C#InBrowser

You can also hook up your website project to GitHub or Visual Studio Online for source control. When done, the ‘Monaco’ editor shows your Project Explorer with all the files – just double click to edit.

MonacoSourceControl

Visual Studio’s Monaco editor also supports a large number of shortcut keyboard commands.

MonacoCommands

If editing HTML/CSS/JavaScript, you’ll find the Visual Studio Monaco editor rather smart with intellisense; the C# experience keeps improving every release. You’ll also find solid support for online editing of LESS, PHP, Node.js and TypeScript. When done with your edits in the browser, simply fire up a build and see the output in a console window or even run your Azure website to pick up the changes. In effect, you can build out a full ASP.NET website in your browser – including writing C# on any browser running on your Mac OSX.

Let’s Rock Some ASP.NET

I’ve saved the best for the last, since you’re going to have the most fun writing C# on a Mac when building modern web/mobile applications with ASP.NET. You may have already heard about .NET Framework core being open sourced – the future of .NET is modular, cross-platform and rather exciting.

ASP.NET vNext leads the way, being open source and offering improved tooling, along with flexible hosting outside of IIS using a new KRuntime. Using the core cross-platform .NET Framework, your ASP.NET web applications will run everywhere – and yes, that means natively in OSX on your Mac!

Getting Ready

Before you start rocking C# on your Mac to build your next ASPNET vNext application, there are few things to set up with your environment and get some handy packages. Let’s walk through the steps:

  1. First up, visit the NET vNext home on GitHub to make sure you understand the moving pieces and check minimum system requirements.
  2. NET vNext architecture is modular and you’ll be using several packages or components. Let’s get some prerequisites out of the way first.
  3. Install the latest version of Node which comes bundled with the ubiquitous package manager npm.
  4. Homebrew is another excellent open source package manager that allows you to install/manage software that you cannot normally do via the OSX terminal. Install Homebrew as well by entering the following Ruby code in your terminal:
    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
  5. Tap the ASP.NET vNext related Git repositories using Homebrew, like so:
    brew tap aspnet/k
  6. Next up, install the K Version Manager (KVM) – you can use KVM to install and switch between different ASP.NET runtimes. Simply fire up the brew command – note that this step will install Mono on OSX if not already present. Alternatively, you can always manually pull down Mono from GitHub and build it yourself. The ASP.NET runtime on a Mac depends on Mono for now.
    brew install kvm
  7. With KVM set up, the next step would be to install the latest K RunTime Environment (KRE), and formalize the K commands, like so:
    
    kvm upgrade
    source kvm.sh
    
  8. With the previous step, you are now technically ready to run ASP.NET vNext natively on your Mac. But a few more handy tools will help down the line – starting with Yeoman. Yeoman is a sleek and open source scaffolding tool and yes, it can now work for your ASP.NET projects. So, grab Yeoman and the ASP.NET Yeoman generators, as follows:
    
    npm install –global yo
    
    npm install –g generator-aspnet
    

Running ASP.NET

Now you are ready to start building your ASP.NET vNext web applications on OSX. Let’s start by running the Yeoman ASP.NET scaffolding tool within an appropriate project folder, like so:

yo aspnet

You can see a glimpse of the expected behavior, as below:

YoASPNet

In this case, an ASP.NET MVC application scaffolding was requested. Navigate to the directory where you ran your scaffolding, and voila – the exact project structure with all requisite files (as seen below), just as if you had created an ASP.NET MVC web project using Visual Studio.

YoScaffolding

Now that you have your ASP.NET project set up, how do you run it in a Mac? This is where the KVM Command line comes into play. Simply navigate to your ASP.NET project directory in the terminal and run the following command to resolve any missing package dependencies:

kpm restore

And finally, you can use the Mono runtime to host your ASP.NET web application. Simply fire it up with the following command:

k kestrel

Your terminal console should show a message indicating the site has been started. Now simply pull up any browser and navigate to http://localhost:5004, as shown below (ASP.NET running on LocalHost in Chrome on a Mac):

NativeASPNetOnMac

If you’re like me, the first time you see a native ASP.NET web application running on a Mac, it is a “WHOA” moment!

OmniSharp

Well, at this point, you have a fully scaffolded ASP.NET web application running natively on your Mac. But you may still need a little more help as you get cracking working on the website’s code, especially if writing a lot of C# server-side code. Enter the marvelous OmniSharp.NET.

It may be adventurous to run .NET applications on OSX or Linux, but is it practical to write C# code outside of the comfort of Visual Studio? OmniSharp helps you do this. To quote – “OmniSharp is a family of Open Source projects, each with one goal – to enable great .NET development in YOUR editor of choice”. And this extends to non-Windows editors, the likes of Sublime Text, Atom, Emacs, Brackets or Vim. Yep, you can write C# in any of these editors of your choice!

Sublime Text

Let’s talk about how to use one of the most popular options – Sublime Text. Want to write C# in Sublime Text and get some of the benefits you expect from Visual Studio? Turns out, efforts are underway to make C# a first-class citizen in editors like Sublime Text.

Here are the few simple steps to set up Sublime Text for writing C# in ASP.NET applications:

  1. Download the beta of Sublime Text 3.
  2. Make sure to have the latest Sublime Text Package Manager plugin installed.
  3. Install the Kulture plugin through Package Control.
  4. Install the Omnisharp plugin through Package Control.
  5. Make some C# language specific settings to provide appropriate intellisense event triggers.

That’s all that’s needed. Now, open up the Yeoman scaffolded ASP.NET vNext project from your OSX directory in Sublime Text (point to the root folder). Sublime shows all your files in a Project tree, each of which is perfectly editable. Open up or create a new C# file, start typing and (boom!) Visual Studio like intellisense as you type, all inside Sublime Text, as shown below:

SublimeIntellisense1

Even more, try a context specific dot (.) operator in C# – you get intellisense and contextual code completion prompts, as seen below:

SublimeIntellisense2

Wonder how all this is working in Sublime Text or other editors? This is courtesy of the OmniSharpServer.

“OmniSharpServer is a local web server (written in Nancy) that accepts requests to various different endpoints which returns results about the code you sent to it. For example, in Sublime Text when you have a string variable and you type (.) after the variable name, a request is sent to OmniSharpServer with a specific payload and the response contains all the possible completions for that variable.”

“NRefactory is the C# analysis library used in the OmniSharpServer. It allows applications to easily analyze both syntax and semantics of C# programs. It is quite similar to Microsoft’s Roslyn project; except that it is not a full compiler – NRefactory only analyzes C# code, it does not generate IL code.”

Sounds complicated, but you get to reap the benefits as the open source community works on OmniSharp.NET with Microsoft’s endorsement. Essentially, as you type your C# code, the locally hosted Omnisharp Server is doing all the heavy lifting trying to provide you with contextual intellisense, while stopping short of actually compiling your code. You get to write C# on your editor of choice, complete with Visual Studio like code editor features. As for Sublime Text, you get to enjoy features like – Intellisense, Go To Definition, Rename, Find Usages, Go To Implementation, Format Document, Override, Add Reference, Syntax/Semantic Errors, Code Refactoring, Build Solution and many more! Check out this wonderful post on what to expect when writing C# in Sublime Text, complete with GIFs demonstrating each interaction.

Conclusion

Choice is a good thing for developers, and most popular .NET language on one of the best possible laptops seems like a solid match. Pick what works best for you – VM, browser or native editors with OmniSharp – but the bottom line is: you can write C# on a Mac, like a champ. And you can do so today! Fun times indeed.

Header image courtesy of Mircea

Comments

  • Pingback: 1p – Write C# on a Mac like a Champ – Exploding Ads()

  • Pingback: Dew Drop – January 12, 2015 (#1931) | Morning Dew()

  • spboyer

    Nice post! Lots more to come from the OmniSharp group on xplat ASP.NET Dev.

  • Pingback: Write C# on a Mac like a Champ! | Ramblings of a Modern Developer()

  • Prasad Honrao

    Nice read. The only limitation of running C# on Mac IMO is lack of touch screen. I think having a touch option is always good if you’re building a touch centric app, but otherwise I agree that Mac hardware is good as compared to other available options

  • Pingback: What to Expect When Expecting MVC 6 - Telerik Developer NetworkTelerik Developer Network()

  • jirapong

    I just put up the instruction to run ASP.NET Mvc Sample on OS X (Yosemite). You can check it out at http://blog.bananacoding.com/blog/first-impressions-of-aspnet-and-visual-studio-code-on-osx

  • Konstantin

    Hi! Fun reading thank you!
    One thing in #7 should not the commands be flipped? Without “source kvm.sh”, I at least could not execute “kvm upgrade”.

    • Konstantin

      Another small issue, I needed to do “sudo npm install -g yo” rather than “npm install -global yo”

  • markalanevans

    We have an .Net mvc app that we are now moving to Azure, we all develop on our Mac’s but use Parallels.
    The stack is Windows Server, IIS, SQL Server, .Net C# & AngularJS.

    Toggling around inside of windows is always a pain, but its the closets thing to production.

    Production we are now moving to Azure.

    Can we really change up the entire dev process and have it be a better experience for developers?

  • Xander

    I like the yo aspnet part of the tutorial. I got it running…BUT Bower should be removed. NPM ALL THE THINGS!!!!!

  • Dinis Cruz

    Hi, is there a way to run Unit Tests in this environment?

  • Nice post. I have learned lot more! I think, if you have no coding experience whatsoever, you will not be a sufficient programmer in a week. There is more to programming to “Just getting Things Done” there are many concepts you must grasp in logic itself to be a good programmer. Even if you have an amazing grasp of logic/critical thinking, you won’t get C# in a week.