Category: C#

Debugging C# on Ubuntu and you get

Debugging C# on Ubuntu and you get

vs-debugger-popup

So you’re trying to debug C# code on Linux, maybe Ubuntu. You’ve installed .NET 6 or 7, you’ve built your solution in Visual Studio on your Windows PC, published it then copied the files over to the Linux box. But when you run it, you get an error “Unable to find debugger script at”. It’s time to debug your Linux app from your Windows Visual Studio.

Now there is a Microsoft support issue for this and it’s less than helpful. Read below to see how I fixed it.

Only, as soon as it tries to attach over SSH (with username, password, IP etc), you get this popup on the left. “Computer says no”.

Looking in the VS Output folder you see the text below or something similar. For whatever reason, it failed to create a hidden folder in your home folder. To fix this, all you have to do is create that folder. It’s .vs-debugger under your home folder.

If you’re not familiar with .folders on Linux, note that the . at the front of the name means it’s a hidden folder. A simple ls command will not reveal it. If you use the File Manager, you can click the settings in the top right and tick the Show Hidden Files. Then you can do a cd ~ followed by a mkdir .vs-debugger. And View in files to confirm that it’s there.

Now the only pain with debugging is that the application must be running for Visual Studio to attach to it. I was debugging a utility that is run, does its business and closes. So to debug it, I added this as the first line in main() in program.cs

Console.ReadKey();

So run it, let it sit waiting for a key then attach visual studio’s debugger to your app over SSH, add your breakpoints and hit a key. Simples!

Is Tiobe Index misinformation?

Is Tiobe Index misinformation?

news, false, conceptEvery month a new Tiobe Index is published purporting to show the most popular programming languages. Except, if you look at other programming language popularity surveys, lists etc, the Tiobe Index increasingly seems to be at odds with everybody else.

Take the programming language C. As you can imagine I have a particular interest in it. I was at first delighted when I saw it at #3 in the Tiobe Index. In fact, in their most recent index it is listed as the 2nd most popular programming language. Well that is just crazy. No matter how much I might want it, there is no way on Earth that it is the 2nd most popular programming language.

It’s not just me saying it. Let’s look at who else says it.

SiteC's RankingComments
Tiobe Index2Updated monthly
GitHub Octoverse Programming languages9Annually- this is October 2022
Reddit Programming languages10Subreddits for programming languages
Red Monk Programming Language Rankings10June 2022. Updated every 6 months
StackOverflow developer survey11Annually
Statista most used programming languages 202211
Hackerrank Developer skills report 202312

There are other programming language lists or surveys but those show what I mean.  No one else has C anywhere that high. Here it’s in positions 9-12 with an average roughly around 10.5 if you exclude Tiobe or 9.3 if you don’t.  I think their methodology is flawed and biased by age. Older languages appear to carry more weight.

Never mind C, what about JavaScript? Everyone else has it in first place (except HackerRank who has it in 4th). Tiobe index has it in 7th. Misinformation is defined as “false information that is spread, regardless of intent to mislead.”. Maybe that’s a bit harsh but that’s how I regard the Tiobe Index.

And with a bit of help I got it fixed

And with a bit of help I got it fixed

Visual Studio Publish Target runtime dialogThanks to suggestions in the Reddit CSharp subreddit (you can view the entire thread here), I fixed the missing file issue and SkiaSharp is now happily outputting graphics on the VPS.  I’m referring to the More Programming Joys blog entry I posted yesterday.

There were two things that were needed to fix it.

  1. Add a package to the solution. This was the SkiaSharp.NativeAssets.Linux package and I used Nuget to add it to my Windows solution. If you haven’t used Nuget, it’s a great package manager and makes it very easy to add packages.
  2. On the Visual Studio Publish page, I needed to change the Target Runtime to linux-x64. That’s the dialog above. When I clicked the Publish it put all the files including the library that was missing (libSkiaSharp.so) into the Target location and once uploaded it worked.
More Programming Joys

More Programming Joys

Game MapSo I’ve been doing some .NET programming. First on Windows because I can debug it there then “Publish it” which puts all the files (compiled in release) needed, including any dlls into one folder and upload it to a VPS using WinSCP. I’ve also got a terminal session connected by Putty. I use Serilog for logging and SkiaSharp for graphics.

First bug was a missing file but it was a stupid error on my part. I had the file in a path under the home folder and had used ~ in the file’s path. You can use ~ in Bash- it means your home folder, but not in a file path in an application. Putting in the full path fixed the bug. D’oh.

Because it’s .NET (6) that I’m using, you don’t get configuration stuff the same as you did with .NET Framework. I store some config information in a file and define the path with these lines of code which work on both Linux and Windows.

 bool IsWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
 var appSettingsFilePath = IsWindows ? @"c:\turfwar\twConfig.json" : "/home/user/turfwar/twConfig.json";

I like Serilog ( with project on Github at ). Nice and simple logging but flexible enough. As this application is a command line app run whenever, it’s easier to view the logs afterwards.

Why use SkiaSharp?

I was quite happy to use System.Drawing but according to this, There are issues with libgdiplus. So I thought I’d try SkiaSharp as I’m doing stuff with Flutter and Skia is the library that underpins that. This is what it takes to create a 100 x100 grey coloured Bitmap in SkiaSharp, add yellow dots and save it to disk as a .jpg. That’s what you see up above.

        internal void SaveBitMap(int id, string filename, Gang gang)
        {
            var info = new SKImageInfo(100, 100);
            using var surface = SKSurface.Create(info);
            SKCanvas myCanvas = surface.Canvas;

            // clear the canvas / fill with white
            myCanvas.DrawColor(new SKColor(0x99, 0x99, 0x99));

            // draw the dots, one for each block
            foreach (var block in Blocks)
            {
                if (block.Owner == id)
                {
                    myCanvas.DrawPoint(block.X*5/2, block.Y*5/2, SKColors.Yellow);
                }
            }

            // Now save to filename
            var mainCanvasImage = surface.Snapshot();
            var TempTIFbitmap1 = SKBitmap.Decode(mainCanvasImage.Encode());
            using (var image = SKImage.FromBitmap(TempTIFbitmap1))
            using (var data = image.Encode(SKEncodedImageFormat.Jpeg, 100))
            {
                // save the data to a stream
                using (var stream = File.OpenWrite(filename))
                {
                    data.SaveTo(stream);
                }
            }
        }

It works fine on Windows but on Linux, (Ubuntu 20.04) I hit bug #2. “System.TypeInitializationException: The type initializer for ‘SkiaSharp.SKImageInfo’ threw an exception.”. And that’s where I am at the moment.  This is similar.  I’ll keep you informed.

It’s that book again

It’s that book again

Basic Computer games bookOne of my favourites and one that I actually bought twice in my life and of course I have mentioned before. Originally I bought it back in 1982 and more recently in 2015 along with the sister “More Computer Games” book. The reason  I mention it because there’s an ongoing project to do the games in it in languages other than BASIC.

The languages they’ve chosen are:

  • Java
  • Python
  • C#
  • VB.NET
  • JavaScript
  • Ruby
  • Delphi / Object Pascal
  • Perl

I no, it’s sad. No C… But given that it includes C#, I’ll let them off.

Using JSON as a datastore in C#

Using JSON as a datastore in C#

Shapes
Image by Gerd Altmann from Pixabay

For some not too complex applications, JSON can be a very handy way to store data rather than say using a database. It also has the advantage of storing data of varying sizes. For instance Lists with varying numbers of items. I created a Saveable generic class below that you use as an ancestor class for that you wish to Save/Load an IList of whatever.

 

 

    public class SaveAble<T>
    {
        private string _error = "";
        string LastError()
        {
            return _error;
        }
        public IList<T>? Load(string filePath)
        {
            if (!File.Exists(filePath))
            {
                Log.Error("Missing file {filePath}");
                _error = $"Missing file {filePath}";
                return null;
            }

            var content = File.ReadAllText(filePath);
            if (string.IsNullOrEmpty(content))
            {
                Log.Error("{filePath} file is empty");
                _error=$"{filePath} file is empty";
                return null;
            }

            return JsonSerializer.Deserialize<IList<T>>(content, new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            })!;
        }

        public bool Save(string filename,IList<T> collection)
        {
            var options = new JsonSerializerOptions
            {
                WriteIndented = true,
                PropertyNameCaseInsensitive = true
            };
            try
            {
                var bytes = JsonSerializer.SerializeToUtf8Bytes(collection, options);
                File.WriteAllBytes(filename, bytes);
                return true;
            }catch (Exception ex)
            {
                _error = $"Exception:{ex.Message}";
                return false;
            }
        }

    }

Just define your class MyClasses from SaveAble<MyClass>

where MyClass is the class you have a List of. Then you can do

MyClasses myclasses;
myclasses.Save("filename",List<MyClass>) and

List<MyClass> list = myclasses.Load("filename");

It is fast. On my PC (now six years old), it can load a 99,000 line JSON file in well under a second.

Why C# for the server?

Why C# for the server?

https://commons.wikimedia.org/wiki/File:Csharp_Logo.png
From Wikimedia

There are plenty of other programming languages that would do.  Programming languages are just tools but C# comes with several advantages.

  1. I know it pretty well, having been using it since 2005.
  2. With .NET 6 (and 5), it’s easy to create applications that run on Linux. This lowers the cost for hosting. I’m setting the game on a low cost VPS.
  3. Also on Linux, ASP.NET works pretty well for both Websites and Web Apis.
  4. I like some of the recent changes in C#. And Visual Studio 2022 Community Edition is pretty good. For instance the JSON handling has got better and better.

Do you know what Hello World in C# looks like now? Here it is in its entirety.

Console.WriteLine("Hello, World!");

That’s a console application. One line! Follow the link for more details about the C# templates. Note, there’s no usings there either. That’s because applications now start with a default set in C# 10 and .NET 6 (you get both if you install VS 2022). And if you want a particular namespace that you’ve written to be available to all source code in a project, you can just add this:

global using xyz;

And it becomes available everywhere without needing any more usings.

 

A new beginning – C#

A new beginning – C#

Postage
Image by Please Don’t sell My Artwork AS IS from Pixabay

You may have noticed, I stopped posting here a while back because basically I ran out of ideas for C related games stuff plus I was doing other stuff that wasn’t relevant (Delphi, C#).

I will get back to finishing my 2nd eBook, but for now, I’m working on a web/mobile game that isn’t really C related. However I thought I’d cover development of it here. as (a) part of it is C# (so technically it’s C and (b) it’s a game.  The backend part is C#, the front end Flutter which is Dart. I’m also going back to my old game design roots as the game architecture is ‘Postal Game’.

What is ‘Postal Game’ architecture?

Well first a little potted history.

Back before the web existed (late 80s), people used to play games by post. They’d fill in a postcard with the orders, post it to the game provider who would enter the details in a computer, process the game then print the results out and post that back. I discovered this (in the UK) back in 1986 and created a postal game: Casus Belli. A 16 player version of Empire. It ran for a year or so and I even attended a postal games conference with a stall back at the start of 1987 in London. By chance, the stall next to mine was run by KJC Games and we got chatting. Kevin J Cropper (The KJC of KJC Games) said “If I ever wanted to sell the game contact me” and at the end of 1987 I did and found myself working for KJC Games as a game designer and programmer in Cleveleys (just North of Blackpool). It was a small cottage industry in the UK and KJC Games was the biggest fish in this admittedly small pond.

Over the next two and a half years I created the 100 player version of Casus called Warlord. Long after I left they ran games across the web and though they don’t run it any more you can still see the page for it. My big creation was a 1,000 player postal game called Quest which KJC still runs. Not bad for a game created in 1989! They still have my name in the Advanced rules which is nice as I last did some work on it in 1996. It took me a year and 40,000 lines of code (Turbo Pascal 5) to create. The others listed helped test it, made suggestions and Steven Fairbrother who came along after I left, fixed my bugs.  When you write 40,000 lines of code in a year, there are a few bugs included…

So each turn gets posted in, processed, printed and posted back. The architecture is the same except its all now sent across the web. There’s a front end programmed in Flutter. This makes it possible to use the same code for Web and mobile development. The game is processed at a fixed rate. In this case I’m going for every three hours but slower or faster is possible. When it’s time, all orders are processed and the results made available to be fetched from the web or mobile device.

Pros and Cons

A Game Processing Engine (GPE) is a completely different kettle of fish from your traditional multi player game server. Hardware requirements are much less and you don’t manage multiple players all at once. Basically the game web/mobile uploads a zip file from each player to send in the orders and then fetches one containing the results. The GPE maintains game state, processes all orders, outputs all results and backs up the game, both before processing each turn (in case it goes wrong so it can be fixed and rerun) and afterwards,

So I’ll be posting here about my progress, programming issues and so on. If you have any queries, please don’t add them as comments – I delete any non-technical comments so instead use the contact form via the About me link on the top.

 

 

Work in Progress – Web game

Work in Progress – Web game

Blazor AppI did some investigative work on this at the weekend, This is my Inselkampf type web game. Although I know C#, I’m fairly new to ASP.NET and Blazor. Now the first thing you’ll notice about most Blazor examples on the web is that many look like the screenshot. In particular, the purple gradient down the left hand side.

So my first job was find out where that’s defined and try changing it. In the project which is Blazor WebAssembly, there’s a shared folder and it contains two .css files. MainLayout.razor.css and NavMenu.razor.css. These are the files you need to alter.

Now its probably seven or eight years since I last touched CSS and it has come on quite a bit since then. I discovered css-grid which simplifies things enormously.  If you want to find out more about CSS, take a look on FreeCodeCamp.org. This site has lots of example layouts using CSS-Grid and I went for Redefining Grid Areas with Media Queries. 

This lets you specify a width so you can have a responsive website which adapts to mobile phones as well as desktop. I merged the css and HTML from the example into the project and although its an early stage, I’m quite pleased with it.

Game framework This is very early. The font, colours etc will all change but this has given me a web template with round corners, header, footer and two sidebars.

If I shrink the width of the browser the two sidebars move to positions above and below the main content like this below. It would have taken a lot more effort before css-grid to do this.

Narrow game framework

 

 

An interesting project- Converting BASIC Computer Games

An interesting project- Converting BASIC Computer Games

Basic Computer games bookYes it’s that book again, one I have mentioned a few times.  Now there’s a project to convert all of the games from the book into C#, Java, JavaScript, Python, Ruby and VB.NET. As with all Git sites, you can download all code from the site in a zip file or individual files. So far though its very early in the project and there’s only a .BAS file in each of the subfolders for each of the games in the book. If you fancy getting involved, pick a game, a language and start coding. Sadly there’s no desire for C or C++ but that still leaves C# .

I still have this book and its sequel (More BASIC Computer games!) but to be honest I wouldn’t have bothered with most of the games in either book. They are all very much of the era (1978) which was just on the cusp of the home computer revolution and so were mostly obsolete within seven or eight years, due mainly to the terminal I/O. They’re ok for learning programming and of course you could run them in a Linux terminal.