C# Twisters–Round 2

More brain twisters. From http://stackoverflow.com/questions/241134/what-is-the-worst-gotcha-in-c-sharp-or-net, http://www.softwire.com/blog/2012/08/13/dont-be-too-lazy-linqs-lazy-evaluation-gotchas/, and others.

11.

static void CSharpPuzzle11()
{
    // Which implementation is faster?
    // Which implementation uses more memory?
    { // Implementation A.
        var before = DateTime.Now;
        int size = 100000;
        string a = string.Empty;
        for (int i = 0; i < size; ++i) a += i.ToString() + " ";
        var after = DateTime.Now;
        Console.WriteLine(a.SizeOf());
        Console.WriteLine(after - before);
    }
    { // Implementation B.
        var before = DateTime.Now;
        int size = 100000;
        StringBuilder a = new StringBuilder();
        for (int i = 0; i < size; ++i) a.Append(i.ToString() + " ");
        var after = DateTime.Now;
        Console.WriteLine(a.SizeOf());
        Console.WriteLine(after - before);
    }
}

12.

class Beer
{
    public bool IsAvailable;
    public bool IsNice;
    public string Name;
}

static void CSharpPuzzle12()
{
    Func<Beer, bool> BeerIsNice = (Beer b) =>
    {
        Console.WriteLine(b.Name);
        return b.IsNice;
    };

    List<Beer> availableBeers = new List<Beer>()
    {
        new Beer { Name = "Old Tom's", IsNice = false, IsAvailable = true },
        new Beer { Name = "Young Dan's", IsNice = true, IsAvailable = false },
        new Beer { Name = "Now Beer", IsNice = false, IsAvailable = true }
    };
    int count = availableBeers.Where(BeerIsNice).Count(); // What is the value of count?
    Console.WriteLine(availableBeers.Where(BeerIsNice).First().Name); // What is the output?
}


13.

private static IEnumerable<char> Keystrokes()
{
    while (true)
    {
        yield return Console.ReadKey(true).KeyChar;
    }
}

static void CSharpPuzzle13()
{
    // Why is keyboard read twice four times?
    System.Console.WriteLine("Enter 'beer'.");
    var firstFourKeystrokes = Keystrokes().Take(4);
    if (firstFourKeystrokes.SequenceEqual(new[] {'b', 'e', 'e', 'r'}))
    {
        System.Console.WriteLine("You entered 'beer'. Getting each char now...");
        firstFourKeystrokes.ToList().ForEach(Console.Write);
    }
}

14.

static void CSharpPuzzle14()
{
    // What's the correct way to create a new GUID?
    var which_one1 = new Guid().ToString();
    var which_one2 = Guid.NewGuid();
}

15.

static void CSharpPuzzle15()
{
    // What happens if you run this code?
    var t = new Program();
    var x = t.MyVar;
}

private int myVar;
public int MyVar
{
    get { return MyVar; }
}

16.

static void CSharpPuzzle16()
{
    // Why don't these work? How do we fix the problem?
    var a = Type.GetType("string");
    var b = Type.GetType("Program");
    var c = Type.GetType("System.Data.Entity.DbContext");
}

17.

static void CSharpPuzzle17()
{
    // Why doesn't this work? How do we fix it?
    for (int i = 0; i < 10; i++)
    {
        ThreadStart ts = delegate { Console.WriteLine(i); };
        new Thread(ts).Start();
    }
}

18.

static IEnumerable<char> CapitalLetters(string input)
{
    if (input == null)
    {
        throw new ArgumentNullException(input);
    }
    foreach (char c in input)
    {
        yield return char.ToUpper(c);
    }
}

static void CSharpPuzzle18()
{
    // Why doesn't this code throw an exception?
    try
    {
        var x = CapitalLetters(null);
        Console.WriteLine("An exception should have been thrown!");
    }
    catch (ArgumentNullException)
    {
        // Expected
    }
}

19.

static void CSharpPuzzle19()
{
    DateTime a = DateTime.Now;
    Thread.Sleep(2000);
    DateTime b = DateTime.Now;
    TimeSpan span = a - b;

    // Which is correct, the first or second line below?
    Console.WriteLine(span.Seconds);
    Console.WriteLine(span.TotalSeconds);
}

20.

static void CSharpPuzzle20()
{
    string my = "my ";
    var t1 = my + "string" == "my string"; //true

    var a = new ArrayList();
    a.Add(my + "string");
    a.Add("my string");

    // uses ==(object) instead of ==(string)
    var t2 = a[1] == "my string"; // True or False?
    var t3 = a[0] == "my string"; // True or False?

    var t4 = my + "string" == "my string"; // True or False?
}

21.

static void CSharpPuzzle21()
{
    // What does this output?
    string prefix1 = "C:\\MyFolder\\MySubFolder";
    string prefix2 = "C:\\MyFolder\\MySubFolder\\";
    string suffix1 = "log\\";
    string suffix2 = "\\log\\";

    Console.WriteLine(Path.Combine(prefix1, suffix1));
    Console.WriteLine(Path.Combine(prefix1, suffix2));
    Console.WriteLine(Path.Combine(prefix2, suffix1));
    Console.WriteLine(Path.Combine(prefix2, suffix2));
}

Posted in Tip

Another Visual Studio Extension for Antlr4 Files: AntlrVSIX

There are several Visual Studio extensions for Antlr: Antlr4Code, ANTLR Language Support, Actipro SyntaxEditor for WPF, and Syntax Highlighting Pack. However, each has problems (works on Antlr3, has advertisements, does not offer a “go to definition” right-click context menu command, etc). So, over the last few days, I implemented a simple VS 2015/2017 extension for Antlr4 grammars. You can find the sources on Github (https://github.com/kaby76/AntlrVSIX). The extension implements “go to definition” and “find all references” for grammar symbols. There are some restrictions, but it’s a start, works well, and is very simple code. Enjoy!

(Edited Jan 14, 2017)

Posted in Tip

CSharp Puzzles for the Agile – Round 1

For those who have free time on their hands, and who would like to work through some brain twisters, here is a list of C# code snippets for your perusal. See https://www.toptal.com/c-sharp/top-10-mistakes-that-c-sharp-programmers-make for more details.

1.

//=============================================================================

private static void CSharpPuzzle1()
{
    Point point1 = new Point(20, 30);
    Point point2 = point1;
    point2.X = 50;
    Console.WriteLine(point1.X);       // What is the output?
    Console.WriteLine(point2.X);       // What is the output?
    Pen pen1 = new Pen(Color.Black);
    Pen pen2 = pen1;
    pen2.Color = Color.Blue;
    Console.WriteLine(pen1.Color);     // What is the output?
    Console.WriteLine(pen2.Color);     // What is the output?
    Console.WriteLine();
}

2.

//=============================================================================

static Pen pen1;
static Point point1;
public static void CSharpPuzzle2()
{
    Console.WriteLine(pen1 == null); // What is the output?
    Console.WriteLine(point1 == null); // What is the output?
    Console.WriteLine(point1 == default(Point));
    // Note: you can't declare an auto of a value type without an initializer!
    //Point p;
    //p.X = 1;
    Console.WriteLine();
}

3.

//=============================================================================

static void CSharpPuzzle3()
{
    string s = "strasse";

    // What is the output?
    Console.WriteLine(s == "straße");
    Console.WriteLine(s.Equals("straße"));
    Console.WriteLine(s.Equals("straße", StringComparison.Ordinal));
    Console.WriteLine(s.Equals("Straße", StringComparison.CurrentCulture));
    Console.WriteLine(s.Equals("straße", StringComparison.OrdinalIgnoreCase));
    Console.WriteLine(s.Equals("straße", StringComparison.CurrentCulture));
    Console.WriteLine(s.Equals("Straße", StringComparison.CurrentCultureIgnoreCase));
    Console.WriteLine(s == "strasse");
    Console.WriteLine(s.Equals("strasse"));
    Console.WriteLine();
}

4.

//=============================================================================

class Account
{
    [Key]
    public string ID { get; set; }
    public string Status { get; set; }
    public decimal Balance { get; set; }
}

static void CSharpPuzzle4()
{
    List<Account> myAccounts = new List<Account>()
    {
	    new Account() { Status = "active", Balance = 1 },
	    new Account() { Status = "inactive", Balance = 2 },
	    new Account() { Status = "active", Balance = 3 }
    };

    // What is the output?
    {
	    decimal total = 0;
	    foreach (Account account in myAccounts)
	    {
	        if (account.Status == "active")
	        {
		        total += account.Balance;
	        }
	    }
	    Console.WriteLine(total);
    }

    // What is the output?
    {
	    decimal total = myAccounts.Sum((account) => (account.Status == "active") ? account.Balance : 0);
	    Console.WriteLine(total);
    }
}

5.

//=============================================================================

class Accounts : DbContext
{
    public Accounts() : base("Accounts.DbConnection") {}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
	    Database.SetInitializer<Accounts>(new SocialClubInitializer());
	    base.OnModelCreating(modelBuilder);
    }

    public DbSet<Account> _accounts { get; set; }
}

class SocialClubInitializer : DropCreateDatabaseAlways<Accounts>
{
    protected override void Seed(Accounts context)
    {
	    context._accounts.Add(new Account() { ID = "1", Status = "Active", Balance = 1 }); // Note capital "A"
	    context._accounts.Add(new Account() { ID = "2", Status = "Inactive", Balance = 2 });
	    context._accounts.Add(new Account() { ID = "3", Status = "Active", Balance = 3 }); // Note capital "A"
    }
}

static void CSharpPuzzle5()
{
    Accounts dbc = new Accounts();
    dbc.SaveChanges();
    var count = dbc._accounts.Count();
    {
	    decimal total = dbc._accounts.Sum(
	        (account) => (account.Status == "active") ? 
		    (decimal?) account.Balance :
		    0) ?? 0;
	    Console.WriteLine(total); // What is the output?
    }
}

6.

//=============================================================================

static void CSharpPuzzle6()
{
    int[] a = new int[] {1, 3, 5, 7, 9};
    int sum = a.Sum(); // Where is Sum defined?
    int len = a.Length; // Where is Length defined?
}

7.

//=============================================================================

static void CSharpPuzzle7()
{
    // Which implementation is faster?
    // Which implementation uses more memory?
    { // Implementation A.
	    var before = DateTime.Now;
	    int size = 100000000;
	    bool[] a = new bool[size];
	    for (int i = 1; i < size; ++i) a[i] = a[i - 1];
	    var after = DateTime.Now;
	    Console.WriteLine(a.SizeOf());
	    Console.WriteLine(after - before);
    }
    { // Implementation B.
	    var before = DateTime.Now;
	    int size = 100000000;
	    BitArray a = new BitArray(size);
	    for (int i = 1; i < size; ++i) a[i] = a[i - 1];
	    var after = DateTime.Now;
	    Console.WriteLine(a.SizeOf());
	    Console.WriteLine(after - before);
    }
}

8.

//=============================================================================

class SystemResource : IDisposable
{
    public void Dispose()
    {
        // The implementation of this method not described here.
        // ... For now, just report the call.
        Console.WriteLine(0);
    }
}

static void CSharpPuzzle8()
{
    // What is the output?
    using (SystemResource resource = new SystemResource())
    {
        Console.WriteLine(1);
    }
    Console.WriteLine(2);
    {
        SystemResource leak = new SystemResource();
        Console.WriteLine(3);
    }
    Console.WriteLine(4);
}

9.

//=============================================================================

class B { }
class D1 : B { }
class D2 : B { }

static void CSharpPuzzle9()
{
    try
    {
        B o = new D1();
        D2 c = (D2) o;
    }
    catch (Exception) { Console.WriteLine("Exception1"); }

    try
    {
        B o = new D1();
        D2 d = o as D2;
    }
    catch (Exception) { Console.WriteLine("Exception2"); }
}

10.

//=============================================================================

class CSharpPuzzle10
{
    // What does the compiler output for warnings and errors?
    int myId;
    int Id;
    CSharpPuzzle10(int id)
    {
        this.myId = Id;
    }
}
Posted in Tip

Getting Xamarin.Forms apps working with .NET Standard and Roslyn

Recently, I was trying to write a Xamarin.Forms app that uses Roslyn, Microsoft’s NET languages compiler framework. But, no matter what I did, it seemed as though it wasn’t possible. But, I tried a few things, and noticed that the Roslyn library could link with Android and iOS applications. That’s when I realized it might be possible.

That said, it depends on what you will be interested in of the Roslyn API. While one can parse and compile code from the .NET Standard/PCL library, Assembly.Load is essentially unavailable. Full functionality is available in Xamarin Android version 7. If you want to run compiled code, you need to use a bait/switch layer to accomplish that, in which case, you don’t need to make your PCL into a .NET Standard library, but it’s a good idea anyways.

Also, I’ve noticed VS 2015 is quite brittle in setting up an app to use .NET Standard. The following steps show that it can be done. Note: after each step, verify with a build and run.

  1. To set up a Xamarin Forms app to use the .NET Standard, open Visual Studio 2015 and create a blank cross-platform app that uses portable class libraries. You will see a portable class library and apps for each of the platforms.
  2. In the Project Explorer, Remove the Windows, Windows Phone apps, and leave the Android and iOS apps.
  3. Set the default project to the Android project. Build and run to make sure all is OK.
  4. Update the Xamarin.Forms in the three projects, to the latest version of Xamarin.Forms (2.3.3.175). Rebuild and run to make sure it works.
  5. In the Project Explorer, right-click on the References for the Xamarin Forms app portable class library, and “Manage NuGet Packages.” Remove the Xamarin.Forms library.
  6. Right-click on the portable class library, select Properties. Click on the Target .NET Standard hyperlink, then select NET Standard 1.5. Note, if you use .NET Standard 1.6, the References suddenly drops all DLL references, so don’t use that! In VS 2017, that appears to be fixed. Once VS has made the conversion, project.json will appear. After making the conversion, the default project has been reset. Set it back to the Android project.
  7. In the file project.json, change the ‘frameworks’ section with the following code, which allows the .NET Standard library to be compatible with certain PCL libraries.
 "frameworks": {
   "netstandard1.5": {
     "imports": [
       "portable-net45+wpa81+wp8+win8"
     ]
   }
 }
  1. Go back to the NuGet package management for the Xamarin Forms app PCL, add in Xamarin.Forms (the latest version).
  2. Rebuild and test. It should all work fine. If not, there is probably something wrong with your VS. Make sure it has the latest updates.

Roslyn works with .NET Standard, but adding it blindly causes a dependency/version issue. Roslyn requires Microsoft.Composition, but the version that it requires is old and incompatible with the .NET Standard (Package Microsoft.Composition 1.0.27 is not compatible with netstandard1.4 (.NETStandard,Version=v1.4). Package Microsoft.Composition 1.0.27 supports: portable-net45+win8+wp8+wpa81 (.NETPortable,Version=v0.0,Profile=Profile259)). Instead, add Microsoft.Composition first, then Microsoft.CodeAnalysis.

  1. In the Project Explorer, right-click on the References for the portable class library, and “Manage NuGet Packages.” Add in Microsoft.Composition (1.0.30), then Microsoft.CodeAnalysis (1.3.2). Make sure to add that to the Android project as well or you get “Severity Code Description Project File Line Source Suppression State
    Error Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly ‘Microsoft.CodeAnalysis, Version=1.3.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’. Perhaps it doesn’t exist in the Mono for Android profile….”

For a check, add source referencing some Roslyn classes, build and run.

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace App15
{
    public class Class1
    {
        public Class1()
        { }

        public static void YoDoit()
        {
            SyntaxTree tree = CSharpSyntaxTree.ParseText(@"
            public class MyClass
            {
                public int MyMethod()
                {
                    return 1+2;
                }
            }");
        }
    }
}

This code is in Github: https://github.com/kaby76/XamForms-Roslyn-Example

C# v7.0 pattern matching

Visual Studio “15” Preview 4 was recently released, so I decided to take it for a spin. In the upcoming C# 7.0, of the features being implemented, pattern matching is probably the most interesting. Consider how often we’ve designed code that uses a switch statement with complex cases, but then when we go to implement the design, a nested if-then-else statement must be coded instead because switch labels must be constant expressions. With pattern matching, this will finally change.

In theory, when the feature is fully implemented, we could write complex switch statements such as:

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int j = 0; j < 20; ++j)
            {
                System.Console.WriteLine("j = " + j);
                switch (j)
                {
                    case var i when i % 2 == 0:
                        System.Console.WriteLine("Even");
                        break;
                    case var i when i > 10:
                        System.Console.WriteLine("OK, > 10");
                        break;
                    default:
                        System.Console.WriteLine("Anything else");
                        break;
                }
            }
        }
    }
}

Unfortunately, while this example compiles, it does not run properly yet, in Visual Studio “15” Preview 4.

Years ago, I used to write C code that would contain declaration expressions. This would simultaneously assign a value and test to see if the value was non-zero. You can do this in C++, e.g.,

// ConsoleApplication2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

int foo() { return 1; }

int main()
{
    if (int a = foo()) printf("a = %d\n", a);

	// if ((int b = foo())) printf("\n"); does not compile.

	if (int x = 1 == 2)
		printf("x = %d\n", x); // OK, but x is 0, not 1 because of precedence rules.
	else
		printf("x = %d\n", x);
	
    // if ((int y = 1) == 2) return y; does not compile--does not like ()'s.

	// printf("x = %d\n", x); Note, x not available at this scope--outside if.

	// if (int c = 1 && int d == 2); Does not compile--only single variable can be declared.

    return 0;
}

In C#, we can use patterns to declare local variables within an expression, extending the declaration expression existing in C++:

namespace ConsoleApplication3
{
    class Program
    {
        static int foo() { return 1; }
        static void Main(string[] args)
        {
            if (foo() is var a) System.Console.WriteLine("a = {0}", a);

            // if ((int b = foo())) printf("\n"); does not compile.

            if (((1 == 2) is bool x) && ! x)
                System.Console.WriteLine("x = {0}", x);
            // else System.Console.WriteLine("x = {0}", x); // Does not compile "else" block--x is out of scope!

            if ((1 is int x) && x == 2)
                System.Console.WriteLine("x = {0}", x); // OK.

            // System.Console.WriteLine("x = {0}", x); // Note, x not available at this scope--outside if.

            if (1 is int c && 2 is int d)
                System.Console.WriteLine("c = {0}, d = {0}", c, d);
        }
    }
}

If the switch is rewritten as a nested if-then-else, the code works fine. Note, the scope of pattern matching variables is within the then clause, not the else clause of the if statement. I’m not sure why this would be the design, as in C/C++, the scope of declaration expression variables extend into the else clause. But perhaps it is to allow reuse of the same variable in a nested if-then-else.

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int j = 0; j < 20; ++j)
            {
                System.Console.WriteLine("j = " + j);
                if ((j is var i) && i % 2 == 0)
                {
                    System.Console.WriteLine("Even");
                } else if ((j is var i) && i > 10)
                {
                    System.Console.WriteLine("OK, > 10");
                } else
                {
                    System.Console.WriteLine("Anything else");
                }
            }
        }
    }
}

Further Information

https://www.infoq.com/news/2016/04/CSharp-7

Essential .NET – Designing C# 7, Mark Michaelis, December 2015 https://msdn.microsoft.com/en-us/magazine/mt595758.aspx

Pattern Matching for C# https://github.com/dotnet/roslyn/blob/future/docs/features/patterns.md

https://github.com/dotnet/roslyn/issues/2136

https://github.com/dotnet/roslyn/issues/206

https://github.com/dotnet/roslyn/blob/future/docs/features/patterns.md

Advanced Pattern Matching Features Removed From C# 7 https://www.infoq.com/news/2016/05/csharp7-pattern-matching-removed

C# 7 Features Previewed https://www.infoq.com/news/2016/04/CSharp-7

Unification: pattern matching, but twice as nice! By: on May 31, 2011  http://www.lshift.net/blog/2011/05/31/unification-pattern-matching-but-twice-as-nice/

https://github.com/dotnet/roslyn/blob/master/docs/Language%20Feature%20Status.md

 

Posted in Tip

Alternatives to Deeply-Nested Callback Functions in Javascript

A few days ago, I wrote a server in Node.js, the purpose of which is to email me when an API found in Nuget is updated. I thought the project would take a few hours, but as it turned out, it took several days. You may ask “How is this possible for such an easy problem?” Unfortunately, I spent a lot of time trying to figure out what API to use to read a text file, and how to use the API. It led me to an understanding of a fundamental problem with Javascript known as “callback hell” (1, 2).

Continue reading

Posted in Tip

Resources for C# WebSockets

WebSockets is a communication protocol on TCP between a web browser (or other client) and a server. It is full-duplex, event-driven. One important advantage of the technology is the elimination of the client polling of the server. The following post lists some resources for C# WebSockets (1).

C#/WebSocket Resources

 

Articles on Web Sockets

https://tools.ietf.org/html/rfc6455
https://tools.ietf.org/html/rfc7936
https://en.wikipedia.org/wiki/WebSocket
https://www.websocket.org/index.html
https://en.wikipedia.org/wiki/Comparison_of_WebSocket_implementations
http://www.codeproject.com/Articles/1063910/WebSocket-Server-in-Csharp
http://www.codeproject.com/Articles/617611/Using-WebSocket-in-NET-4-5-Part-1
http://www.codeproject.com/Articles/618032/Using-WebSocket-in-NET-Part
http://www.codeproject.com/Articles/619343/Using-WebSocket-in-NET-Part
http://www.codeproject.com/Articles/620731/Using-WebSocket-in-NET-Part

 

Note:

  1. Initial list from http://stackoverflow.com/questions/33467089/net-websocket-client-and-server-library
  2. Although it was suggested in a StackOverflow.com discussion to use “Sockets for PCL“, that is not a viable solution because the library is for TCP sockets not WebSockets.

 

Posted in Tip

Runtime Performance of NET Core vs. NET Framework vs. Mono

With the release of NET Core, the acquisition of Xamarin and Mono, and the 15 or so years of development of the NET Framework, we now have three platforms to choose from for C#. Why are there three platforms? What are the differences between each? And, what is the performance of the three to each other? From the NET Core Roadmap, it’s clear that Microsoft is trying to focus on OS-agnostic implementations of NET.

NET Framework is for Windows desktop and mobile applications. The NET Framework is specific for Windows because it has Windows UI functionality. If you want an application that works across different OSes, then this won’t be your choice.

NET Core is for console and server applications that need to work on any OS. Also, a focus of the NET Core framework is small size/efficient applications. The first release was only a month ago, and there are many things missing. If you need UI beyond System.Console, look to one of the other two platforms.

Finally, Mono/Xamarin is for mobile applications. Mono can also run NET Framework console applications on most OSes without changes. On Android, C# and Java can call each other. If you have a large Java code base, this is a good choice. Xamarin Forms is an OS-independent UI for mobile devices.

What are the differences in performance between NET Framework, NET Core, and Mono? The following test computes the performance of a recursive implementation of Ackermann’s function and a looping implementation of a Fibonacci function. If you are looking for performance of in a console application, NET Core is your choice.

 

NetPerf1

NetPerf2

Runtimes based on sample size of 10, .NET Core 1.0.1, .NET Framework 4.5, Mono JIT compiler version 4.2.2 (Visual Studio built mono), Windows 10 Anniversary Update, Intel(R) Core(TM) i5-3570K CPU @ 3.40GH, Northbridge Intel Ivy Bridge rev. 09, Southbridge Intel Z77 rev. 04, Graphic Interface PCI-Express, PCI-E Link Width x16, PCI-E Max Link Width x16, Memory Type DDR3, Memory Size 16 GBytes, Channels Dual, Memory Frequency 800.7 MHz (1:6), CAS# latency (CL) 11.0, RAS# to CAS# delay (tRCD) 11, RAS#, Precharge (tRP) 11, Cycle Time (tRAS) 28, Command Rate (CR) 2T, Host Bridge 0x0150.

On Ubuntu, there is a similar speedup for Ackermann’s function with NET Core. But for the Fibonacci function, surprisingly slightly slower with NET Core compared to the Mono implementation.

 PerfAckUb

PerfFibUb

Runtimes based on sample size of 3, .NET Core 1.0.1, .NET Framework 4.5, Mono JIT compiler version 4.4.2 (Stable 4.4.2.11/f72fe45 Fri Jul 29 09:58:49 UTC 2016); Intel(R) Xeon(R) CPU E5-2650L v3 @ 1.80GHz; 512 MB Memory / 20 GB Disk / SFO2 – Ubuntu 16.04.1 x64.

Benchmark Code:

perf.tar.gz

Data analysis in XLSX

Further Information:

.NET Core 1.0, .NET Framework, Xamarin – The “WHAT and WHEN to use it”.  Accessed August 10, 2016.

Microsoft reveals big plans for .Net Core. Accessed August 10, 2016.

.NET Core. Accessed August 10, 2016.

.NET Core Roadmap. Accessed August 10, 2016.

.NET Core Version 1 Released – So What? Accessed August 10, 2016.

Getting Started with ASP.Net Core Accessed August 10, 2016.

Posted in Tip

Cross-Debugging Mono C# Executables Running on Linux

Debugging C# programs that run on a Linux server can be a challenge. On Ubuntu, a server may not have the Unity GUI installed, so you can’t use MonoDevelop. Even if the server had the GUI, MonoDevelop often does not work with a C# project because it doesn’t support many Visual Studio 2015 projects. Visual Studio supposedly can cross-debug a program running on Linux from a Windows box, but I haven’t been able to get one solution to work. (It does work for C++.Xamarin Studio works, but the steps are somewhat convoluted, and won’t work if you naively follow what has been outlined by others for a Windows box (e.g., in (a), you cannot simply build the app on Linux using xbuild, because the paths for files between server and debugger host differ). Here, I note how one can get Xamarin Studio working on Windows.

  1. Download a copy of Xamarin Studio for Windows, and install it. Xamarin Studio for Windows is, in fact, no longer officially available, but you can still find the download here as of July 2016. I don’t know how long this link will last; you can’t download Xamarin Studio for Windows though Xamarin.com.
  2. In your Linux server, make sure to have it set up with a firewall, SSH, and Mono.
  3. Create a variable in your environment to enable Xamarin Studio “Custom Soft Debugging.” Create “MONODEVELOP_SDB_TEST” with the value “1” (no quotes) through the System Properties box.
  4. Start Xamarin Studio, and open or create a C# test program, like “Hello World.” Set the configuration to Debug and build the program.
  5. Mono does not understand PDB files, so you have to create the equivalent MDB files. Start a command-line Bash shell in the directory ‘bin/Debug/”. Type: for i in *.exe *.dll;do echo $i; pdb2mdb $i; done. If pdb2mdb is not found, make sure Mono/bin is on the search path.
  6. Open a command-line Bash shell on your Linux box using “ssh”, e.g., “ssh root@192.168.1.10”.
  7. In the Windows Bash shell, type: tar -cvf – Debug | ssh root@192.168.1.10 ‘cat – > Debug.tar’.
  8. In the Linux Bash shell, type: tar -xvf Debug.tar; cd Debug; mono –debug –debugger-agent=transport=dt_socket,address=0.0.0.0:12345,server=y HelloWorld.exe, replacing HelloWorld.exe with the name of the executable you want to debug.
  9. In Xamarin Studio, open Run -> Run with -> Custom Command Mono Soft Debugger2016-07-14 (1)
  10. In the pop up, enter the IP address of the Linux box, then click on “Connect”. 2016-07-14 (9)
  11. You should now be able to debug your program. Note: you don’t need to compile the program on Linux. Note: if you can’t set breakpoints, it’s because you haven’t copied the .mdb files from Windows to Linux. Path names in the .mdb files are full paths, and Linux path names do not work.

 

Further Information

  1. https://eladnava.com/debug-remote-mono-apps-via-xamarin-studio/
  2. http://www.mono-project.com/docs/advanced/runtime/docs/soft-debugger/
  3. http://www.jeffongames.com/2012/03/debugging-embedded-mono/
  4. http://tirania.org/blog/archive/2008/Sep-04.html
  5. https://blogs.msdn.microsoft.com/vcblog/2015/11/18/announcing-the-vs-gdb-debugger-extension/

Installing Docker

OK, really simple. I want to install Docker on an Ubuntu box. Should be easy. Right?

Wrong!

When I do a Google search for “install docker”, Google returns a link to the Docker installation page for Ubuntu. That’s fine, but following the 18 page/2000 word installation is insane. The first time I did that, it took 15 minutes. What a waste of time, and not easily reproducible if I stop to get a cup of coffee, then come back.

So, I go to docker.com, and somehow find some other documentation for a Linux install through the now totally indecipherable menu system in docker.com. The instructions are shorter, and seem the right thing to do, basically: curl -fsSL https://get.docker.com/ | sh.

Why ask why there are two different instructions?