c# – The uShip Blog https://ushipblogsubd.wpengine.com Mon, 24 Mar 2025 18:28:59 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.2 Visual Studio+ReSharper-level Productivity in VSCode https://ushipblogsubd.wpengine.com/shipping-code/visual-studioresharper-level-productivity-in-vscode/ https://ushipblogsubd.wpengine.com/shipping-code/visual-studioresharper-level-productivity-in-vscode/#comments Tue, 06 Sep 2016 14:18:04 +0000 https://ushipblogsubd.wpengine.com/?p=6350 Update 2017-05-22: This post originally written for a project.json .NET Core project. It has been edited for a .csproj .NET Core project. Visual Studio Code (aka VSCode) is a lightweight text editor from Microsoft. Many people think just because it is a “text-editor”, they will be missing the features they are used to from an... Read More

The post Visual Studio+ReSharper-level Productivity in VSCode appeared first on The uShip Blog.

]]>
Update 2017-05-22: This post originally written for a project.json .NET Core project. It has been edited for a .csproj .NET Core project.

Visual Studio Code (aka VSCode) is a lightweight text editor from Microsoft. Many people think just because it is a “text-editor”, they will be missing the features they are used to from an IDE like Visual Studio. With the proper configuration, VSCode can be a very powerful tool.

Setup

VSCode by default doesn’t come with the tools necessary to build .NET Core projects. The following setup will be necessary to get the editor, compiler, and extension necessary to get you closer to an IDE experience.

To install an extension, open the Command Palette (cmd+shift+p), remove the >, and run ext install csharp.

Note: While this tutorial is cross-platform , all given commands are using Mac OS X key bindings. For Windows and Linux, replace cmd with ctrl.

Key Bindings

Command Palette

The most important key binding in VSCode is cmd+shift+p, which brings up the Command Palette, similar to Sublime Text. Why is it so important? Hitting those keys brings up a search box that allows you to start typing a command like “ext” for “Extensions: Install Extensions” or “build” for “Tasks: Run Build Task”.

Shell

You will frequently need to run shell commands within VSCode. ctrl+` toggles an in-editor shell.

ReSharper Bindings

Where would each of us be without alt+enter, ReSharper’s quick fix and context actions key binding? Just because you don’t have ReSharper doesn’t mean your life is over (even though some people might think that). Common ReSharper operations are supported in VSCode, and these operations can be bound to custom key bindings, which allows us to roughly mirror the ReSharper plugin in VSCode. The below are the most common ReSharper key bindings I use. You can use the Command Palette to search for “Preferences: Open Keyboard Shortcuts”.

[
	{ "key": "alt+enter",                 "command": "editor.action.quickFix",
                                     "when": "editorTextFocus" },
	{ "key": "cmd+b",               "command": "editor.action.goToDeclaration",
                                     "when": "editorTextFocus" },
	{ "key": "alt+f7",               "command": "editor.action.referenceSearch.trigger",
                                     "when": "editorTextFocus" },
	{ "key": "cmd+shift+alt+n",                 "command": "workbench.action.showAllSymbols" },
	{ "key": "cmd+n",                 "command": "workbench.action.quickOpen" },
	{ "key": "cmd+shift+n",                 "command": "workbench.action.quickOpen" },			
	{ "key": "cmd+f12",			"command": "workbench.action.gotoSymbol"},
	{ "key": "cmd+t l", 			"command": "workbench.action.tasks.test"},

	{ "key": "cmd+p",			"command": "editor.action.triggerParameterHints"}
]
Command ReSharper VSCode default
Quick Fix alt+enter cmd+.
Go to anything cmd+n cmd+p
Go to symbol cmd+shift+alt+n cmd+t
Go to declaration cmd+b f12
Go to file cmd+n cmd+p
Go to file member cmd+f12 shift+cmd+o
Parameter info cmd+p shift+cmd+space
Find usages alt+f7 shift+f12
Run all tests cmd+t l N/A

VSCode key bindings reference: https://code.visualstudio.com/docs/customization/keybindings
ReSharper key bindings reference: https://www.jetbrains.com/resharper/docs/ReSharper_DefaultKeymap_IDEAscheme.pdf

Building and Debugging .NET Core Applications

This is it. The moment you’ve been waiting for. Using VSCode as an IDE.

Creating a .NET Core Project

VSCode doesn’t have a UI to create new projects, since it is file and folder based. However, we can use the in-editor shell to create a project after creating a folder.

mkdir my_project
code my_project

Note that the above requires code to be in your path. You can do this via searching “PATH” in the Command Palette.

Once we are in VSCode, run the following in the in-editor shell to create a new .NET Core command line project

dotnet new
# Run `dotnet new -h` to see your available options.
# Some templates that are available: Console (the default), Web (ASP.NET Core MVC), Lib (class library), xunittest and nunittest (XUnit and NUnit test projects)

You might see: “Required assets to build and debug are missing from your project. Add them?” Select “Yes”.

Building and Debugging

The building and debugging key bindings are the typical bindings from Visual Studio.

To debug, set a breakpoint and hit F5. It’s really that easy!

NuGet

Now that we are able to debug a .NET Core application, let’s walk through the common task of adding a NuGet dependency.

VSCode doesn’t come with a NuGet client by default, so let’s install one via ext install vscode-nuget-package-manager.

To install a NuGet package:

  • Open the Command Palette and search for “NuGet Package Manager: Add Package” and hit enter
  • Enter a search term and hit enter (e.g. “json”)
  • Select a package from the list and hit enter (e.g. “Newtonsoft.Json”)
  • Select a version from the list and hit enter (e.g. 9.0.1)
  • Select a project to add the reference to
  • Run dotnet restore in the in-editor shell as prompted by the NuGet extension

Alternatively, you can use the dotnet NuGet commands directly:

dotnet add path/to/your_project package Example.Package -v 1.0

Be aware that not all NuGet packages are compatible with .NET Core. See this awesome list of packages that support .NET Core. Hint: your favorite packages are probably there.

Testing

“The code is not done until the tests run” – A person

Now that we have a .NET Core project with a NuGet package reference, let’s add a test.

Set up

We need to install the following NuGet packages:

  • NUnit
  • NUnit3TestAdapter, at least version 3.8.0-alpha1

The following will have to be added to .vscode/tasks.json:

{
	"taskName": "test",
	"args": [],
	"isTestCommand": true,
	"problemMatcher": "$msCompile"
}

Note: You may be able to run dotnet new -t xunittest or dotnet new -t nunittest depending on what version of dotnet you have installed. The bleeding edge can be installed from the GitHub page.

Running the Test

Now we can add the simplest failing test:

using NUnit.Framework;

[TestFixture]
public class ProgramTests
{
	[Test]
	public void Should_fail()
	{
		Assert.Fail("This is a failure!");
	}
}

Now when we hit cmd+t l, our test will fail!

Debugging the Test

If you prefer to use xUnit (see: dotnet-test-xunit) you can easily run or debug the test by simply selecting the corresponding option in the editor. Unfortunately, debugging with NUnit isn’t quite as simple yet, and currently requires a convoluted process. See this GitHub issue that addresses this.

Conclusion

VSCode out-of-the-box won’t give you everything you need to be fully productive with .NET Core, but with some setup you should be up and running in no time. Do you have any VSCode tips and tricks of your own that I didn’t mention? Please comment below and share.

Summary of Setup

[amp-cta id=’8486′]

The post Visual Studio+ReSharper-level Productivity in VSCode appeared first on The uShip Blog.

]]>
https://ushipblogsubd.wpengine.com/shipping-code/visual-studioresharper-level-productivity-in-vscode/feed/ 3
April Fools – Developer Style https://ushipblogsubd.wpengine.com/shipping-code/april-fools-developer-style/ https://ushipblogsubd.wpengine.com/shipping-code/april-fools-developer-style/#respond Fri, 01 Apr 2016 10:50:05 +0000 https://ushipblogsubd.wpengine.com/?p=4301 Here at uShip we are pretty big fans of open sourcing code. At the same time, we are also fans of a good ol’ prank. Hence, we have decided to open source a few of our favorite code pranks to share with the world (and just in time for April Fool’s Day). But first, a... Read More

The post April Fools – Developer Style appeared first on The uShip Blog.

]]>
Here at uShip we are pretty big fans of open sourcing code. At the same time, we are also fans of a good ol’ prank. Hence, we have decided to open source a few of our favorite code pranks to share with the world (and just in time for April Fool’s Day).

But first, a few ground rules:

We believe in following Isaac Asimov’s first two rules of robotics, roughly, you can’t harm anyone with your prank, and you can’t harm their computer
Make sure others are okay with what you are about to do. Generally if you have a great culture like here at uShip, you will find that innocuous pranks are just an inevitable, natural remnant of some age-old perpetual developer-magic duel

Expeliarmus – taskkill /f /im explorer.exe
Additionally, added bonuses for pranks whereby:

The developer learns something in the end (other than to hate you)
The prank is either horribly complex or involves a lot of patience

Also note, for brevity’s sake, we kept most of the below examples in Windows and .NET, but feel free to rant about that in the comments.
Let’s get started…

Change Compile Time Constants

aka
π = 3
In 1897, Indiana for some reason thought it was a good idea to redefine ? as 3. We feel that you should express this idea to your fellow developers as well.

How it works:

 

In some languages like C#, you can override almost any code in the Assembly Info class. Although normally this can be done for any sane reason (of which there are few), we just decided why not have a little fun with the static Math functions instead?

Show me the code already!!!
using System;
namespace IndianaPi
{
class Program
{
static void Main()
{
Console.WriteLine(“PI is {0}”, Math.PI);
Console.WriteLine(“Press any key to continue…”);
Console.ReadKey();
}
}
}

The Trick:
// In AssemblyInfo.cs, located under the Properties folder for any project
internal class Math
{
public static double PI =3.0;
}

Note: One can also use this for enforcing good coding practices as well, although there are likely better means to do so, such as lint or ReSharper code formatting instead.

 
Startup Scripts
aka
What the heck is that sound!!!??

Recently, one of our favorite developers – Jordan Patapoff – left uShip to go and start his own startup Clyp.  Lucky for us, he knows enough about API’s that he left us a perfect entry-point for our next prank.

How it works::

Using Clyp’s API, and a quick script to open a media file, one can have a random media clip played on demand. Then by adding this new script to a user’s startup folder, we are able to give them a nice little surprise whenever they log in.

Show me the code already!!!

Registry Key Rebinding

aka
How-the-hell-do-I-fix-this?
One of the most awesome things windows allows is replacing one key with another. This can have a few purposes, from when a key just randomly falls off your laptop keyboard when riding your bike, to when you just hate a key and want to annihilate it from existence.

I’m looking at you Caps Lock!
However, we find the best usage of this feature is probably to have someone’s spacebar output dashes instead. This way you can wreak havoc, yet likely not get them locked out since rarely do people who fall for this prank use spaces in their passwords anyway.

How it works:

The below script is probably the easiest way to use the exploit (since anyone who wants to go through and manually modify the windows registry in the short amount of time it takes for someone to get a cup of coffee is either insane or the flash). Once run, restart their computer, and sit back and enjoy as they slack you “messages-such-as-this”.

Show me the code already!!!

Copy & Paste from the web
aka
These are not the scripts you are looking for

Some developers (especially those who are new to development) suffer from “just copy it from the internet” syndrome. Generally in order teach that not all code on the internet is “good code”, you can introduce them to your “found” code they should try out. Then once they copy the code blindly without even giving it a second look, they will find that you secretly had some invisible injected code hidden in the middle.

How it works:

When providing a code sample on a web page for someone to copy paste, you can insert code through the use of an invisible span. Even though the span is invisible, its contents will still be copied to the clipboard. After a little html magic, as well as an unsuspecting developer who doesn’t pay attention to what they copy and paste, the rest is history. And the end result is phenomical. The best part is that this works in ANY language!

Show me the code already!!!

 
Aliasing
aka
A rose command by any other name

I think I’m going to name you su
I think all of us as developers have become accustomed to blindly typing certain command line messages. Whether it be git commit or hg push, some developers only have production on the mind and will never give your inserted command a second thought.

How it works:

Using doskey, one is able to alias any command they want to another command. Often this is for the lazy who want to not have to type things like git push, but instead type gp. However, this also leaves the door open for those who want to add a little something extra, such as git commit -ma “<insert message>” $T git push. That is, so long as no one does anything silly like doskey doskey=echo “uh oh… now what?”

Show me the code already!!!

doskey git=git add -A $T git commit -am “I’m a little teapot” $T git pull $T git push

 

URL Redirecting

aka
The Host with the most!

No, not those guys
This one is pretty old school, but I am surprised how many developers still fall for a changed host file. As such, they will never understand when they go to their favorite sites (e.g. stackoverflow.com), then suddenly appear on some of their least favorite (although not uShip.com of course).

How it works:

Whenever a website tries to go to any url, it will always check to see if there is an override in the hosts file. However, if you happen to know of a url that can be accessed using their IP address, you can easily override any site (that is, assuming it does not redirect over https).

Show me the code already!!!

What else?

Obviously this list can easily grow, but hopefully what we have shared is enough to get you started. If you find that one of the above just isn’t good enough in its entirety, feel free to mix them up. For instance, redirect a user from stackoverflow to a place with javascript that changes their keyboard bindings!

Additionally, if you are not used to windows, be sure to try to run as administrator if you can (which is true for most developers) and running Set-ExecutionPolicy RemoteSigned if using any of the powershell commands.

And whatever you do, just be sure to be safe, have fun, and try not to let this wonderful gift of the First of April go to waste.

Feel like we are missing your favorite idea? Then leave us a comment and let us know. Or… just make a pull request!

The post April Fools – Developer Style appeared first on The uShip Blog.

]]>
https://ushipblogsubd.wpengine.com/shipping-code/april-fools-developer-style/feed/ 0
JavaScript for C# Developers https://ushipblogsubd.wpengine.com/shipping-code/javascript-for-csharp-developers/ https://ushipblogsubd.wpengine.com/shipping-code/javascript-for-csharp-developers/#comments Thu, 17 Mar 2016 14:45:48 +0000 https://ushipblogsubd.wpengine.com/?p=4285 Overheard at work today: “…this is why I hate JavaScript so much.” Sound like something you’d say? Instead of letting the hate flow through you, know that it doesn’t have to be like that. JavaScript is evolving quickly and picking up luxuries that C# has had for years. Subtle Differences Before I get into the... Read More

The post JavaScript for C# Developers appeared first on The uShip Blog.

]]>

Overheard at work today:

“…this is why I hate JavaScript so much.”

Sound like something you’d say? Instead of letting the hate flow through you, know that it doesn’t have to be like that. JavaScript is evolving quickly and picking up luxuries that C# has had for years.

Subtle Differences

Before I get into the cooler, newer parts of JavaScript, a few key differences from C# that you should really know about:

  • Equality checking. Use triple equals (===) for common, everyday equality checking (or !== for inequality). Avoid double equals (==) due to some hidden gotchas.
  • Variable declarations. Variables instantiated with var do not behave how you expect. They’re lexically scoped as opposed to the block scoping of C# and most other languages. e.g. vars created inside of for loops and if blocks are visible beyond the curly braces. The 2015 edition introduces let, which works like C#’s var.

Language Features

JavaScript went several years between editions: the third edition was released in 1999, the fifth edition in 2009. Not anymore – the sixth edition was published June 2015 and included a proposal for two-year release cycles. Some of the new features include:

    • LINQ. Code written with LINQ is generally more declarative and expressive than code that isn’t, and it’s easily within reach when writing JS. Similar functions for arrays exist in JS, they’re just named differently:
      • map instead of Select
      • filter instead of Where
      • sort instead of OrderBy
// C#
var philly = new MenuItem("philly", "fries", 10.99m);
var reuben = new MenuItem("reuben", "fries", 9.99m);
var pizza = new MenuItem("pizza", "salad", 16.99m);
var menu = new [] { philly, reuben, pizza };

var choices = menu
   .Where(x => x.Side == "fries")
   .OrderBy(x => x.Price)
   .Select(x => x.Name);

// choices => ["reuben", "philly"]
// JS
var philly = { name: "philly", side: "fries", price: 10.99 }
var reuben = { name: "reuben", side: "fries", price: 9.99 }
var pizza = { name: "pizza", side: "salad", price: 16.99 }
var menu = [philly, reuben, pizza];

var choices = menu
   .filter(x => x.side === "fries")
   .sort((x, y) => x.price > y.price)
   .map(x => x.name);

// choices => ["reuben", "philly"]
    • Class syntax. Introduced in ES6, the class syntax makes creating classes look much more familiar to the usual C# style. There are still fundamental differences in how inheritance works in JS vs. C#, but a similar syntax will help smooth some of that over.
// C#
class Address {
    private readonly string _city;
    private readonly string _state;
    private readonly string _zip;

    public Address(string city, string state, string zip) {
        _city = city;
        _state = state;
        _zip = zip;
    }

    public string ToFormattedString() { 
        return _city + ", " + _state + " " + _zip;
    }
}
// JS
class Address {
    constructor(city, state, zip) {
        this.city = city;
        this.state = state;
        this.zip = zip;
    }

    toFormattedString() {
        return this.city + ", " + this.state + " " + this.zip;
    }
}
    • String interpolation. JavaScript’s version of string interpolation uses backtick (`) characters. Must be using ES6 or later. Use it like so:
// C#
var number = 3;
var size = "large";
return $"I'll take {number} {size} pizzas, please";
// JS
var number = 3;
var size = "large";
return `I'll take ${number} ${size} pizzas, please`;

Development Environment

Both the development environment and tools that are available to you for a given language greatly affect your productivity and experience for that language, irrespective of the language itself. Visual Studio, despite being a bit sluggish at times, is a great development environment to work in. Popular JavaScript IDEs tend to be less IDE and more text editor, which makes them feel quicker and more responsive.

  • Powerful IDE with community plugins. What makes VS even better is the plugin ecosystem, ranging from the essential ReSharper to the tiny Hide Main Menu (personal favorite). For JavaScript, Sublime is hugely popular, and more recently Atom by GitHub, which both offer a fantastic set of user-created packages and themes. There’s also the lightweight Visual Studio Code, which supports both C# and JS!
  • ReSharper-style suggestions. Even though JavaScript is an interpreted language, front end developers have recognized the value in catching potential errors before execution. In Sublime, adding the SublimeLinter package (plus a little bit of configuration) gives you static code analysis à la ReSharper. Examples include removing unused variables, removing unreachable code, and requiring a default case in switch statements.
  • Importing. Gone are the days where you have to include a multitude of scripts on the page in a particular order. Just like in statically typed languages like C#, you can use import statements in your JS files to reference other files, which are then built with a tool like webpack or Browserify. Throw NodeRequirer into the mix, an Intellisense-like plugin for Sublime for finding files, and you’ll feel right at home.
  • Package manager. NuGet is handy, but npm is handier.

Testing

JavaScript development is a wild west of roughly thrown together code, with undefined is not a function hiding under every rock, right? Wrong!

    • Unit testing. Popular testing frameworks include Jest and Mocha, with Karma as a kickass test runner – it even has the ability to rerun the test suite when a .js file changes! Test-driven development is popular in .NET communities, and JS developers are starting to embrace it – for example, this Redux tutorial is written in TDD style.
// C#
[Test]
public void Should_return_true_for_valid_prime_number()
{
   var isPrime = _classUnderTest.IsPrimeNumber(37);
   isPrime.Should().Be(true);
}
// JS
describe("isPrimeNumber", function () {
    it("should return true for valid prime number", function () {
        var isPrime = isPrimeNumber(37);
        expect(isPrime).to.be(true);
    });
});

Server-side

Historically, JavaScript has always been known as a client-side language, but node.js has completely changed that notion.

    • Server / API frameworks. With the addition of a middleware layer like Express or Hapi, you can quickly write robust, fully-featured server and API code.
// C#
public class SandwichesController : ApiController
{
   public ActionResult Index(int id)
   {
       // do stuff with the request and response
   }
}
// JS
var express = require("express");
var app = express();

app.get("/v2/sandwiches/:id", function (request, response) {
   var sandwichId = request.params.id;
   // do stuff with the request and response
}

Conclusion

JavaScript isn’t so bad, right?

Originally posted on the author’s personal blog.

The post JavaScript for C# Developers appeared first on The uShip Blog.

]]>
https://ushipblogsubd.wpengine.com/shipping-code/javascript-for-csharp-developers/feed/ 1