Fixing my BF1942 woes with Win32 APIs

Battlefield 1942 was one of a number of great games I played when I was growing up. I was first introduced to the game through a demo disc on a magazine – it was the expansion “Secret Weapons of WWII”. I spent many hours playing that demo and eventually managed to snag the complete set of the game with both expansions. It was game that ran pretty well on old hardware and have a lot of fun memories playing it.

Jumping forward several years, I wanted to give the old game another play. I knew the graphics wouldn’t hold up but to play in its nostalgic sandbox would more than overcome that. I installed the game and the various patches, modified configuration files to use my monitor’s native resolution (1080p) and tried to launch it. Unfortunately, it wouldn’t launch at all.

Some people online suggest it was issues with SecureROM as that no longer works with Windows 10 while others suggest it is an issue with Direct Play. What ultimately solved it for me was an unofficial patch by a group called Team Simple.

Now with the game launching, I start to hear the classic BF1942 main menu music. Sped through the profile setup, jumped to instant battle, picked my favourite level (Hellendoorn) and pressed start. The music changes to, in my opinion, an even more iconic piece when the level is loading. The progress bar moves maybe a quarter of the way and then… I’m back on my desktop.

After going back and forth with settings and the resolution changes I made, I found it just didn’t want to work in full screen.

Battlefield 1942 in Window mode

For the sharp-eyed individuals, you might notice that this is actually playing through Parsec – this is part of my vision for a remote desktop experience. It actually plays great (no noticeable input lag) via Parsec, over Wi-Fi, from my desktop to my laptop. That said, I did try the game directly on that machine and it still crashed so something else was to blame.

While I could play in window mode, I couldn’t actually move the window so I could see the whole screen. Anytime I attempted to drag the window, it would just bring the cursor back in the game. Tried shortcuts to maximise the window but none of those worked either.

So what would any good programmer do? Search for an existing solution online. Write their own program to fix it!

Seemed like the fun thing to do anyway.

The Plan

This is what I wanted to do:

  • Get rid of the game’s window border as it was just taking space
  • Position the window so it is centered to the monitor

The second point is important – the menu displays at 800×600 but the game when loading and playing is at whatever resolution I configured in window mode. My plan was to build a launcher that would bootstrap the main game.

I’ve messed around with removing borders from applications years back when I wanted to run a console application in the background. The way I achieved it back then was to invoke Win32 APIs from .NET and figured that would be a good starting place. My initial task was to find the APIs I need to use.

Fortunately someone already found the APIs to use to remove borders and reposition the window. My job then was to work out how to bring that into my application.

//A snippet of the code that helped me with the Win32 APIs from the Simple Runtime Window Editor (SRWE)
public void RemoveBorders()

I put together bits and pieces from that codebase like the remove border and window positioning code and combined it with additional API calls for monitor information. I needed the following Win32 APIs to do everything I wanted:

After doing a rough integration with pieces from that codebase, I gave it a run and… my application crashed. I was using process.MainWindowHandle to get BF1942’s game window. Turns out that it isn’t set till, well, there is a main window available. So I wrote some code to wait for that and bingo – it launched the game and worked!

Well, it mostly worked – see BF1942 has an interesting quirk where it launches a new process when you end a match and go back to the main menu. This required me to write logic to track when processes changed while also still allowing it to exit when BF1942 is closed properly.

Improving the Win32 APIs

While my prototype worked, cobbled together from bits of SRWE and my own bits, I wasn’t entirely happy with how I integrated the Win32 APIs. Below is the snippet of code I had that takes a window handle, gets the window’s size, the monitor’s size, calculates the position and finally sets it.

unsafe static void UpdateWindowPosition(int handle)

    var info = new WINDOWINFO();
    var success = WinAPI.GetWindowInfo(handle, ref info);
    if (success)
        var windowDimensions = info.rcWindow;
        var monitorHandle = WinAPI.MonitorFromWindow(handle, 0);
        var monitorInfo = new LPMONITORINFO
            cbSize = (uint)sizeof(LPMONITORINFO)
        WinAPI.GetMonitorInfoA(monitorHandle, ref monitorInfo);
        var monitorDimensions = monitorInfo.rcMonitor;
        var x = monitorDimensions.Width / 2 - windowDimensions.Width / 2;
        var y = monitorDimensions.Height / 2 - windowDimensions.Height / 2;
        SetPosition(handle, x, y);

static void SetPosition(int handle, int x, int y)

What I would prefer is to actually have it feel more like a typical .NET API, something more like:

static void UpdateWindowPosition(Window window)

    var monitorBounds = window.GetCurrentMonitor().GetBounds();
    var windowBounds = window.GetBounds();
    var x = monitorBounds.Width / 2 - windowBounds.Width / 2;
    var y = monitorBounds.Height / 2 - windowBounds.Height / 2;
    window.SetPosition(x, y);

All I’m doing is abstracting away the Win32 APIs but it makes my “business logic” here far cleaner. While doing this, I also decided to remove the pieces of SRWE and replace it with a more maintainable interface to the APIs.

I tried out both TerraFX.Interop.Windows and CsWin32, ultimately settling on the latter. CsWin32 was a little less intimidating as the API is generated based on strings in a text file rather than containing everything at once. Also I like jumping to definition of types to read more and explore APIs etc and doing that to one of the types in the TerraFX library crashed Visual Studio. That’s more of a VS problem than a TerraFX library but still – CsWin32 would work great for what I’m doing.

The way I went about achieving my desired interface to the Win32 APIs I needed was via creating record-struct wrappers around the various native handles and having instance methods wrap the API calls themselves. For example, below is my Window type that I have most of my functionality hanging off of.

public readonly record struct Window(nint Handle)

    private HWND Win32Handle => new(Handle);

    public Monitor GetCurrentMonitor()
        nint handle = PInvoke.MonitorFromWindow(Win32Handle, 0);
        return new(handle);

    public void SetPosition(int x, int y)

    public Rectangle GetBounds()
        var windowInfo = new WINDOWINFO();
        PInvoke.GetWindowInfo(Win32Handle, ref windowInfo);
        return Rectangle.From(windowInfo.rcWindow);

    public void RemoveBorders()
        _ = PInvoke.SetWindowLong(Win32Handle, WINDOW_LONG_PTR_INDEX.GWL_STYLE, style);

        style = PInvoke.GetWindowLong(Win32Handle, WINDOW_LONG_PTR_INDEX.GWL_EXSTYLE);
        style &= ~(int)(WINDOW_EX_STYLE.WS_EX_DLGMODALFRAME 

The End Result

BF1942 in a borderless window for the intro cinematics
BF1942 in a borderless window at fullscreen

I called my project Borderless 1942 and is available on GitHub. It is a self-contained, single-file .NET 6 application. Because it is self-contained, you don’t need .NET 6 installed to run it.

I’m quite happy that I got this working and could enjoy the game again. In terms of the code, the main thing I’d want to change is to move from a constant loop resetting the window position to something that listens on window resize events. This is possible via the Win32 APIs but has its own complications which I haven’t got around to addressing yet.

I’m also looking at turning the style of wrapper I wrote into a dedicated library. There seems to be some interest in improved access to the Win32 APIs. I don’t know how far I’d go with it (what Win32 APIs I’d support) but I think it could make this a lot easier for developers in certain situations.

Source link

Proposed Alternative DOTNET Repository Layout

Layout for GitHub Repo for Blazor Web App with API and shared Logic layer and server-side Data Layer.

I’m thinking that a directory layout for Solutions that represents the relationship of projects would be good. Also, pairing test projects with their library being tested.

Proposed Layout

πŸ“„ .gitignore                // Global Git Ignore
πŸ“„                 // README for entire repository
πŸ“„ LICENSE                   // LICENSE for entire repository
πŸ“„ nuget.config              // NuGet Configuration
πŸ“‚ .github                   // Github config
  πŸ“‚ workflow                // Github Workflows
    πŸ“„ cd.yml                // Continuous Integration Pipeline
    πŸ“„ ci.yml                // Continuous Deployment Pipeline
πŸ“‚ .idea                     // (hidden) Rider config
πŸ“‚ .tools                    // Dependent Tooling
  πŸ“‚ Cake                    // Cake Build Tooling
πŸ“‚ .vs                       // (hidden) Visual Studio Config
πŸ“‚ .vscode                   // VS Code Config
  πŸ“„ settings.json           // VS Code Solution Settings
  πŸ“„ tasks.json              // VS Code Task Definitions
  πŸ“„ launch.json             // VS Code Launch Definitions
  πŸ“„ extensions.json         // VS Code Extension Recomendations
πŸ“‚ _artifacts                // Built Artifacts
  πŸ“‚ npm                     // Built NPM Modules
  πŸ“‚ nuget                   // Built NuGet Packages
  πŸ“‚ other                   // Other Built Artifacts
πŸ“‚ _build                    // Nuke or Cake
  πŸ“‚ .nuke                   // Nuke Project
    πŸ“„ Build.cs              // BUKE Targets
    πŸ“„ Build.csproj          // NUKE Build Project
πŸ“‚ _cd                       // CD Config
  πŸ“„ nuke-cd.yml             // CD Config for NUKE
πŸ“‚ _ci                       // CI Config
  πŸ“„ nuke-ci.yml             // CI Config for NUKE
πŸ“‚ _lib                      // Loose dependencies
πŸ“‚ _requirements             // Loose requirements docs
πŸ“‚ _scripts                  // Loose PowerShell Scripts
  πŸ“„ publish.ps1             // Push artifacts to repositories
  πŸ“„ helpers.psm1            // PowerShell Module of helper functions
πŸ“‚ MySolution                // Start of Visual Stduio Solution
  πŸ“„ Directory.Build.Props   // Global MSBuild Configuration
  πŸ“„ MySolution.sln          // Visual Studio Solution File
  πŸ“‚ Data
    πŸ“„ Directory.Build.Props // Data-Tier MSBuild Configuration
    πŸ“‚ _integration          // Data-Tier integration tests
    πŸ“‚ _sql                  // Loose SQL Scripts
    πŸ“‚ MyProject.Entities    // Project Grouping
      πŸ“‚ docs                // Markdown based generated and/or manual docs
        πŸ“‚ Generated         // Generated Documentation
          πŸ“‚ <metadata folder> // DocFx Generated
          πŸ“‚ api             // DocFx Generated
            πŸ“„ <namespace>.yml // DocFx Generated
            πŸ“„ <class>.yml   // DocFx Generated
          πŸ“„ toc.yml         // DocFx Generated
          πŸ“„ index.yml       // DocFx Generated
        πŸ“‚ Pages             // Hand-created Documentation
          πŸ“„   // Index for MyProject.Entities Docs
          πŸ“„ // Index for MyProject.Entities Docs
        πŸ“„ docfx.json        // DocFx Configuration
        πŸ“„          // Index for MyProject.Entities Docs
      πŸ“‚ src                 // Library
        πŸ“‚ Entities          // POCO Entities
        πŸ“‚ Migrations        // Database Migrations
        πŸ“‚ Repositories      // Repositories or DbContexts
        πŸ“„ MyProject.Entities.csproj
      πŸ“‚ test                // Library Tests
        πŸ“‚ Data              // Test Data
        πŸ“‚ Mocking           // Mocking Objects
        πŸ“„ MyProject.Entities.Tests.csproj
  πŸ“‚ Logic
    πŸ“„ Directory.Build.Props // Logic-Tier MSBuild Configuration
    πŸ“‚ _integration          // Logic-Tier Integration Tests
    πŸ“‚ MyProject.Rules
      πŸ“‚ docs
        πŸ“‚ Generated         // Generated Documentation
          πŸ“‚ <metadata folder> // DocFx Generated
          πŸ“‚ api             // DocFx Generated
            πŸ“„ <namespace>.yml // DocFx Generated
            πŸ“„ <class>.yml   // DocFx Generated
          πŸ“„ toc.yml         // DocFx Generated
          πŸ“„ index.yml       // DocFx Generated
        πŸ“‚ Pages             // Hand-created Documentation
          πŸ“„   // Index for MyProject.Logic Docs
          πŸ“„ // Index for MyProject.Logic Docs
        πŸ“„ docfx.json        // DocFx Configuration
        πŸ“„          // Index for MyProject.Logic Docs
      πŸ“‚ src
        πŸ“‚ Mapping           // Entities-to-Domain Models Mappings
        πŸ“‚ MVC               // Real MVC (see: )
          πŸ“‚ Controllers     // Controllers
          πŸ“‚ Models          // POCO Domain Models
        πŸ“„ MyProject.Rules.csproj
      πŸ“‚ test
        πŸ“„ MyProject.Rules.Tests.csproj
  πŸ“‚ Services
    πŸ“„ Directory.Build.Props // Services-Tier MSBuild Configuration
    πŸ“‚ _integration          // Services-Tier Integration Tests
    πŸ“‚ MyProject.Api
      πŸ“‚ docs
        πŸ“‚ Generated         // Generated Documentation
          πŸ“‚ <metadata folder> // DocFx Generated
          πŸ“‚ api             // DocFx Generated
            πŸ“„ <namespace>.yml // DocFx Generated
            πŸ“„ <class>.yml   // DocFx Generated
          πŸ“„ toc.yml         // DocFx Generated
          πŸ“„ index.yml       // DocFx Generated
        πŸ“‚ Pages             // Hand-created Documentation
          πŸ“„   // Index for MyProject.Api Docs
          πŸ“„ // Index for MyProject.Api Docs
        πŸ“„ docfx.json        // DocFx Configuration
        πŸ“„          // Index for MyProject.Api Docs
      πŸ“‚ src
        πŸ“„ MyProject.Api.csproj
      πŸ“‚ test
        πŸ“„ MyProject.Api.Tests.csproj
  πŸ“‚ UI
    πŸ“„ Directory.Build.Props // UI-Tier MSBuild Configuration
    πŸ“‚ _assets               // Shared UI assets
      πŸ“‚ css                 // Shared Styling
      πŸ“‚ fonts               // Shared Fonts
      πŸ“‚ images              // Shared Images
      πŸ“‚ resources           // Shared Resource files
    πŸ“‚ _integration          // UI-Tier Integration Tests
    πŸ“‚ MyProject.Blazor
      πŸ“‚ docs
        πŸ“‚ Generated         // Generated Documentation
          πŸ“‚ <metadata folder> // DocFx Generated
          πŸ“‚ api             // DocFx Generated
            πŸ“„ <namespace>.yml // DocFx Generated
            πŸ“„ <class>.yml   // DocFx Generated
          πŸ“„ toc.yml         // DocFx Generated
          πŸ“„ index.yml       // DocFx Generated
        πŸ“‚ Pages             // Hand-created Documentation
          πŸ“„   // Index for MyProject.UI Docs
          πŸ“„ // Index for MyProject.UI Docs
        πŸ“„ docfx.json        // DocFx Configuration
        πŸ“„          // Index for MyProject.UI Docs
      πŸ“‚ src
        πŸ“‚ wwwroot
        πŸ“„ MyProject.Blazor.csproj
      πŸ“‚ test
        πŸ“„ MyProject.Blazor.Test.csproj

Source link

Top 8 Programming Languages For Game Developers

The choice of programming language depends on factors including the game type– console, computer game or mobile game; and the extent of interactivity. Here’s a list of top eight programming languages for game development: original article source…



Despite its high entry barrier, C++ is one of the most popular and commonly used programming languages for game designers. It offers a high abstraction level for both fine object-oriented programming and generic programming, providing direct control over hardware and graphical processes.

Additionally, C++ allows the optimisation of special parts to a very high level– a feature almost impossible to achieve with other languages.

C++ is used to build most big console and Windows games. Apart from that, popular games built using C++ include Counter-Strike, Football Pro, Starcraft, Master of Orion III.



Given Java’s versatility and rich collection of open-source material, it is popularly used for the development of indie and mobile games. It is easy-to-use, is beginner friendly and can write a range of reusable system-agnostic code. When compared with C++, Java offers easy writing, debugging, learning and compiling.

Games including the likes of Mission Impossible III, Minecraft, FIFA 11, and Ferrari GT 3: WOrld Track, have all been created using Java.



HTML5 is one of the top choices by game developers to build cross-platform and cross-browser apps and games. Further, it can be interchangeably used with JavaScript.

HTML5 is widely preferred for game development for its ultimate gaming engines. Game Frameworks including Construct 2, ImpactJS, Phaser, Turbulenz and Booty5 have taken the responsibility of the HTML5 Game Development process.

Some popular games built with HTML5 include Cookie Clicker, Gods Will Be Watching, World Cup Penalty 2018.


JavaScript is one of the best programming languages for interactive online games. It integrates with web technologies including CSS and HTML, allowing the development of cross-platform mobile games.

JavaScript is often used along with HTML5 since the latter cannot create animation or interactivity. Additionally, contributing to its popularity is JavaScript’s humongous online community and large number of frameworks.

Some popular games made with JavaScript include Hangman, HexGI, Little Alchemy, Swoop and Polycraft.



Although not as popular as Java or C++, Python is used for game development. Its PyGame library is developer-friendly, easy to use for building games and enables developers to prototype games quickly. Additionally, just like Java and C++, Python also runs on OOP principles. Its simple learning curve makes Python a go-to option for many game developers.

Some popular games built using Python include Battlefield 2, Disney’s Toontown Online, Eve Online and Frets on Fire.



Unreal Engine has developed the programming language UnrealScript or UScript. Like Java, UnrealScript is object-oriented without multiple inheritance. Major gaming platforms including the likes of Microsoft Windows, Android, Linux and Playstation use UnrealScript.

However, in 2014, Epic Games had announced that Unreal Engine 4 would not be supporting UnrealScript.

Some popular games developed using UnrealScript include Advent Rising, America’s Army, The Wheel Of Time, Batman- Arkham Knight and its series.



Lua is a light weight, high level and multi-platform programming language that is easy to run, making it fun and efficient to be used for video game development. It can be designed to embed into many applications, making it convenient for developers and players to alter the game.

Game engines including the likes of Gideros mobile, Corona SDK, and CryEngine, use Lua as its primary programming language.

Some popular games developed using Lua are Age of Conan, American Girl, Angry Birds, and Aquaria.



Despite considered easier than C++, C# is a powerful language. Its XNA framework makes it perfect for building games on Windows and Xbox. Additionally, C#’s game engine Unity3D and Xamarin enables developers to build games on all platforms including iOS, Android, PlayStation and Windows.

C# is as popular in the gaming industry due to its efficiency and scalability.

Popular games developed using C# include Pokemon Go and Super Mario Run.


What I use :- Javascript , C#(very less) and Unrealscript
Comment down what you guys mostly Use πŸ‘‡πŸΌ

Happy Coding!!!

Source link

Game Dev Digest β€”β€ŠIssue #121 – Show Me The Money

Issue #121 – Show Me The Money

This article was originally published on

Issue #121 - Show Me The Money

Back with another issue, the latest updates from Unity, enjoy!

Systems that create ecosystems: Emergent game design – We created a new e-book, The Unity game designer playbook, for game designers who want to learn how to prototype, craft, and test gameplay in Unity. New and experienced game designers can use this guide as they begin to add Unity skills to their profile.

How to come up with a game idea that you’ll love working on – I’ll give you a step-by-step process for coming up with a game idea that you’ll love, that you’ll be excited to work on, and that is appropriate for your skill level in game development.
Jason Tu

Unity Security’s Public Bug Bounty Program – Today we’re announcing Unity’s bug bounty program is now public, opening it for all individuals to contribute their security findings in Unity products.

Modified Grid – This is the third tutorial in a series about procedural meshes. It introduces a second way to generate a square grid and a way to animate it via a shader.

Introduction to Asynchronous Programming in Unity – Dive deeper into the world of asynchronous programming in Unity by creating a fun town-builder game.

Unity 2022.1 beta is now available – As of today, it includes over two thousand fixes and more than 600 features and changes.

The magic of Cinemachine 2.6 in Unity 2020 LTS: Unparalleled precision, workflows, and more – As part of the 2020 LTS, Cinemachine 2.6 is now a verified package (more on what that means below). We also have several new tools for cinematic creators like you to make the most of this latest version. [UPDATED November 2021 to reflect the latest developments in Cinemachine 2.6] Unity

Sword Slash Shader Breakdown – Hey! This shader uses a technique similar to that of a β€œsoulercoaster” (which are similar to ribbons/trails, commonly used in VFX involving magic spells). It involves panning a texture across a premade mesh, masking sections of it to be visible over time. In this case the mesh is a ring that will surround the player and we’ll be panning two textures – one trianglular shaped one which masks the shape of the slash, and a noise texture to add detail.


How the Hell Do You Make Money!?
How the Hell Do You Make Money!? – In this 2021 GDC Game Career Development session, game developers and designers discuss and share a variety of approaches to surviving and occasionally thriving in the game spaceβ€”even without having a major hit.

How to use Cinemachine in Unity: Overview and Brain Explained! – Learn how to use the Cinemachine Camera Package in Unity with this new tutorial and breakdown!

How to make Minimap in Unit 2021 – When you want to make a minimap in Unity it usually is all about creating a separate camera. The tricky part is showing on your minimap information’s important to the player and not exactly what they can see in front of them but just in top-down view.
Sunny Valley Studio

Unity FAST Tutorial – Magical Orb (VFX Graph) – In this Unity FAST Tutorial, you’ll see how to create a magical orb with Visual effects Graph (VFX Graph) in the Universal Render Pipeline (URP) or the High Definition Render Pipeline (HDRP).

Refraction ShaderGraph tutorial for Unity – Refraction shader using ShaderGraph, works both on URP and HDRP. Uses the opaque texture to achieve screen space refraction.

Hades: Transition Effect (Quick How It’s Made | Unity Tutorial) #shorts – Let’s learn how to recreate the Hades Transition effect! It adds that extra bit of polish in your transitions making them much more interesting than a boring fade to black. It involves a simple shader and you can draw the mask texture in any way you want to get all kinds of unique effects.
Code Monkey

Making a tiny HORROR GAME in Unity. – PLAY it here

Lobby and Relay Demo Overview | Unity Gaming Services – As part of the release of the Unity Gaming Services, we’d like to show how Lobby and Relay can work well together.

Cloud Content Delivery and Addressables | Unity Gaming Services – Check out our latest workshop that will walk you through the Addressable Asset System and how to get started with Cloud Content Delivery. Cloud Content Delivery (CCD) combines cloud storage, content management, and a reliable content delivery network to help you deploy the right content to the right players at the right time.


War FX
War FX – War FX is now FREE!
40+ REALISTIC EFFECTS for war games of all genres!

  • Optimized for Desktop & Mobile
  • Works in 3D and 2D Includes Cartoon FX Easy Editor to easily scale any effect, and change other properties!
    Jean Moreno (JMO) Affiliate

Text2Mesh [Project Page] – Text2Mesh is a method for text-driven stylization of a 3D mesh.
threedle Open Source

DarkConfig – DarkConfig is a configuration library for games which supports fast and expressive iteration.
SpryFox Open Source

Simple Scroll-Snap – “Simple Scroll-Snap” is an elegantly designed, intuitive solution that allows for elements within a ScrollView to be snapped to, offering a wide range of customization options.
daniellochner Open Source

Unity Rulers – A ruler editor to measure distances between game objects in the Scene view.
geekrelief Open Source

A minimal spring physics library for Unity – A minimal spring physics library for Unity.
thammin Open Source

Unity Bezier Curves – A simple C# library to create 2D Bezier curves of any order in Unity3D.
wmcnamara Open Source

Dash Animation System – Dash Animation System for Unity is a system that was designed to make animation editing more approachable and user friendly. It offers solution to commonly encountered problems like visual editing and prototyping of programmatic animations called tweens. Combining tween and statically authored timeline animations. Sequencing, altering and retargeting of statically authored animations and much more.
pshtif Open Source

Asset Management Tools for Unity – Small collection of tools for Unity used to manage your assets.
NibbleByte Open Source

Unity Automatic Speech Recognition – Automatic Speech Recognition in Unity.
voxell-tech Open Source

UImGui – UImGui (Unity ImGui) is an UPM package for the immediate mode GUI library using ImGui.NET. This project is based on RG.ImGui project.
psydack Open Source

The First Person – The First Person (TFP) is a user friendly, feature rich extendable first person controller built for Unity.
boaheck Open Source

ShadowBaker – Simple tool for baking blob shadow textures in Unity!
Helix128 Open Source

Metamesh – Metamesh is a Unity package that generates primitive meshes. It works as a custom asset importer but doesn’t import anything from an input file. Instead of importing a file, it reads properties from a metafile and procedurally generates a mesh.
keijiro Open Source

unity.webp – WebP made easy for Unity3d.
netpyoung Open Source

Ragdoll Trainer Unity Project – Active ragdoll training with Unity ML-Agents (PyTorch).
kressdev Open Source


Gardenia – A laid-back combination of a gardening simulator and a fairy tale adventure. Help Wood Grandpa clean the island and restore its beauty so that its former inhabitants can return to their homes. Take photos of your garden compositions, relax and discover the secrets.
[You can also follow along on Twitter]
Sleepwalking Potatoes, SimFabric

You can subscribe to the free weekly newsletter on

This post includes affiliate links; I may receive compensation if you purchase products or services from the different links provided in this article.

Source link

Traversing the C# Syntax Tree with F#

This article will go over the basics of the .NET compiler platform feature for analyzing the C# syntax tree, using F#.

.NET provides a Syntax API that can read any C# or Visual Basic source file and provide the corresponding Syntax Tree for that code.


Why would someone need to traverse the C# syntax tree?

Well, it can be for a number of reasons, maybe you want to gather statistics about how many classes, namespaces and methods you have, maybe you want generate code based on what is already written, maybe you want to create new tools like a new linter or a tool like Swagger. All these things can be done by analyzing the syntax tree.

Recently I found myself using the Syntax API for finding Attributes above certain methods and classes, and based on the name and arguments of the Attributes, I generated various other files that were used elsewhere.

using System.Collections;
using System.Linq;
using System.Text;

namespace FunWithSyntaxTrees

    class Program
        static void Main(string[] args)
            // ...

The snippet above shows a small program. We will use this snippet as our input for analyzing the syntax tree.


Assuming you have an F# environment setup. You can begin by installing the nuget package Microsoft.CodeAnalysis.CSharp and importing that into your project.

open Microsoft.CodeAnalysis
open Microsoft.CodeAnalysis.CSharp
open Microsoft.CodeAnalysis.CSharp.Syntax

module Main =

  let main argv =

After you install the package and add your open directives, we will hardcode the C# source code from above into the file, above the main entrypoint function.

// ... open directives

let code = """
using System.Collections;
using System.Linq;
using System.Text;

namespace FunWithSyntaxTrees

    class Program
        static void Main(string[] args)
            // ...


module Main =

  let main argv =

When you write a real program that uses the Syntax API, you will most likely be reading the C# source from files, like this let code = File.ReadAllText "/path/to/file", instead of hardcoding the string like we did, but for this tutorial it is fine for demonstration.

So we will begin by passing the string of C# source code to the Syntax API to be parsed, in return we will get the Syntax Tree that we can begin analyzing.

let main argv =
  let syntaxTree: SyntaxTree = CSharpSyntaxTree.ParseText code


Note: I will write out the Type‘s of all the variables, but it is unnecessary most of the time since F#’s type inference is very capable of inferring the type itself. Just like in C# when you use the var keyword, it is capable of knowing the underlying type, in F# this inference is even more powerful and applies to arguments, functions and everything in-between.

Now that the Syntax API has returned our needed Syntax Tree, we can begin travering it and exploring what it offers as data.

First let us get all the using directives in the file. We start by getting the root node of the file, then we iterate over all the child nodes inside the root node and find the ones that are the correct UsingDirective type.

let main argv =
  let syntaxTree: SyntaxTree = CSharpSyntaxTree.ParseText code

  let rootNode: CompilationUnitSyntax = syntaxTree.GetCompilationUnitRoot()
  let rootNodeChildren: SyntaxNode seq = rootNode.ChildNodes()


The rootNodeChildren variable holds all the child SyntaxNode‘s of the root node. The root node is basically the first node of the SyntaxTree which holds everything, and a SyntaxNode is the most general type of node.

We now need to iterate over these children to find the correct SyntaxNode for using directives since that is what we are looking for. We will declare a small helper function to help find them.

let usingDirectiveNode (node: SyntaxNode): UsingDirectiveSyntax option =
  match node with
  | :? UsingDirectiveSyntax as usingDirective -> Some usingDirective
  | _ -> None

let main argv =
  let syntaxTree: SyntaxTree = CSharpSyntaxTree.ParseText code
  let rootNode: CompilationUnitSyntax = syntaxTree.GetCompilationUnitRoot()
  let rootNodeChildren: SyntaxNode seq = rootNode.ChildNodes()

  let usingDirectives: UsingDirectiveSyntax seq =
    Seq.choose usingDirectiveNode rootNodeChildren


The new helper function usingDirectiveNode takes a generic SyntaxNode and checks if it is of the UsingDirectiveSyntax variety, if it is, it returns an F# Option type containing the using directive node.

Note: An F# Option type is a way to represent a “nullable” value, since there are no real null values in F#, nullable values are representated as Algebraic Data Types, such as the Option type.

We use the new helper function by mapping over every node and passing it to the function. We use Seq.choose to filter out any None types and keep all the Some types. It also unwraps the Some types so we can keep using them without Option mapping.

So Seq.choose is just a fancy way of doing and then Seq.filter specifically with Option types since the type signature is ('T -> 'U option) -> seq<'T> -> seq<'U>.

Moving along, so now that we have a sequence of using directives in a variable, we can get the specific properties of a using directive. For now we wil just print them out as proof.

let usingDirectiveNode (node: SyntaxNode): UsingDirectiveSyntax option =
  match node with
  | :? UsingDirectiveSyntax as usingDirective -> Some usingDirective
  | _ -> None

let main argv =
  let syntaxTree: SyntaxTree = CSharpSyntaxTree.ParseText code
  let rootNode: CompilationUnitSyntax = syntaxTree.GetCompilationUnitRoot()
  let rootNodeChildren: SyntaxNode seq = rootNode.ChildNodes()
  let usingDirectives: UsingDirectiveSyntax seq =
    Seq.choose usingDirectiveNode rootNodeChildren

    |> List.ofSeq
    |> (fun u -> printfn $"u.ToString()")
    |> ignore


The output of running our program would be:

using System.Collections;
using System.Linq;
using System.Text;

Pretty cool right? We analyzed our C# code and found our using directives and printed them out.

We can use that strategy to find anything in our code, including methods, method arguments, types, classes, interfaces, enums, comments, attributes, etc, everything!

If you found this useful, feel free to follow me on twitter at @rametta

Source link

C# conversions: Implicit VS Explicit

After many years programming in .NET, you may have already realized that the framework allows us, in a very simple way, to make conversions between different types of data.

Conversions can be of 2 types πŸ‘‡

  • Implicit Conversions
  • Explicit Conversions

Implicit conversions are for which it is not necessary to indicate the conversion in parentheses (…).

double variable = 10;

In the code we assign a variable of type double a value of type int:

But the compiler doesn’t tell us anything and lets us continue working as if nothing had happened. This is known as an implicit conversion.

Instead, if we do the following πŸ‘‡

int variable = 10.0;

The compiler will give us an error indicating that an implicit conversion from double to int cannot be done, and tells us to use an explicit conversion

There is no mystery about it, simply this problem can be fixed by putting (int) in front of 10.0 πŸ‘‡

int variable = (int) 10.0;

Placing the type of data to which we want to convert it in parentheses is called explicit conversion. What this means is that with this syntax we are explicitly indicating to the compiler that we want to convert one type of data into a different one.

At this point you could perfectly tell me that this would also work πŸ‘‡

double variable = (double) 10;

Apparently it does the same as if we don’t put (double) in front of it.

So… where is the difference? πŸ€”

The only difference between implicit and explicit conversions has to do with whether or not there is a risk of that information being lost.

If we go to the first case (without parentheses), it is an implicit conversion. The value of the litetal int does not matter as if we write double since there will be no risk of losing the information as it is a type of greater capacity.

On the contrary, if we go to the second case, we are forced to do an explicit conversion. This works because a double object can contain values ​​that a smaller capacity int type cannot represent.

Let’s take an example πŸ‘‡

int variable = (int) 10.5;

An integer type cannot contain decimals, so it will truncate 10.5 to 10, thus losing information.

How we can create our own conversions

Usually the conversions of the Framework are more than enough for the needs that arise. However, there may be many cases where it would be more useful to define our own implicit and explicit conversions. The .NET platform provides us with an easy way to do it.

To create a conversion between two types, we simply have to write the corresponding operator, either implicit or explicit.

We are going to create an imaginary scenario in which we have to manage the temperatures so that the degrees can change between Celsius and Fahrenheit.

Let’s create the code πŸ‘‡

class Temperature
    public float Degrees  get; set; 
class Celsius : Temperature
    public Celsius(float temp)
      Grados = temp;
  class Fahrenheit : Temperature
      public Fahrenheit(float temp)
    Grados = temp;

Now with this code we have the possibility of writing methods so that we do the conversion between them, and which we call each time.

class Temperature

  public float Degrees  get; set; 
  public Celsius ToCelsius()
    return new Celsius(((5.0f / 9.0f) * (this.Degrees - 32)));
  public Fahrenheit ToFahrenheit()
    return new Fahrenheit(((9.0f / 5.0f) * this.Degrees + 32));

Celsius cel = new Celsius(10);
Fahrenheit far = cel.ToFahrenheit();
Celsius cel2 = far.ToCelsius();

This works, but we will have to call the corresponding method each time and this makes the code very messy.

If we want to do an implicit conversion, we simply have to define a static operator with the static implicit operator.

We go back to our example πŸ‘‡

class Temperature
    public float Degrees  get; set; 
  class Celsius : Temperature
  public Celsius(float temp)
    Grados = temp;
  public static implicit operator Fahrenheit(Celsius c)
      return new Fahrenheit((9.0f / 5.0f) * c.Degrees + 32);
  class Fahrenheit : Temperature
    public Fahrenheit(float temp)
      Grados = temp;
  public static implicit operator Celsius(Fahrenheit fahr)
  return new Celsius((5.0f / 9.0f) * (fahr.Degrees - 32));

Celsius cel = new Celsius(10);
Fahrenheit far = cel;
Celsius cel2 = far;

We can see that to each class we add an implicit conversion operator for the other related class, and after that, we just implicitly perform the conversions.

What we gain from this is a much cleaner code that meets the conditions for implicit conversions.

If we want to do it differently… πŸ€”

Let’s imagine that we have an application that has to manage the teachers and students of a school.

Let’s see it better πŸ‘‡

public class Person
    public string Name  get; set; 
  public class Pupil : Person
    public string Class get; set; 
    public List<int> IdsCourse  get; set; 
  public class Teacher : Person
    public string Class  get; set; 
    public int IdContract  get; set; 

If at some point a student becomes a teacher or vice versa, we will need to use a conversion to reuse the data. As in this case, we are going to lose information since the different classes do not handle the same information.

Therefore the conversion will have to be explicit πŸ‘‡

public class Person

public string Name  get; set; 

public class Pupil : Person

public string Class  get; set; 
public List<int> IdsCourse  get; set; 
public static explicit operator Teacher(Pupil alum)

return new Teacher Name = alum.Name, Class= alum.Class, IdContract = -1 ;

public class Teacher: Person

public string Class get; set; 
public int IdContract  get; set; 
public static explicit operator Pupil (Teacher prof)

return new Pupil Name = prof.Name, Class= prof.Class, IdsCourse = new List<int>() ;

Teacher teacher = new Teacher  Name = "Juan", Class= "Programming", IdContract = 10 ;
Pupil student = (Pupil)teacher;
Teacher teacher2 = (Teacher)student;

βœ… Conclution:

Marking a conversion as implicit or explicit must strictly meet the criteria of whether there is a risk of information loss. It may be the case that today you consider the loss of information that occurs to be negligible, but that at some point it is not.

If you have marked the conversion as implicit, anyone who uses it directly assumes that there is no information loss.

If there is later and the failure is in that conversion, it can be a big headache, even more so if the code is part of a library and the person who uses it cannot see the code, so always think about it before defining the conversion. πŸ€—

Source link

3+3 ASP.NET Mistakes (+ How to avoidΒ them)

The internet is a dangerous place, hackers are always looking for new ways to break into your system and steal your data.Β 

As a developer, you know how important it is to protect your application. If your app is hacked, it can be a big problem for you and your customers. With the increase in internet security breaches and cyber attacks, protecting your app has never been more essential.Β 

To help prevent potential threats, I’m going to share some mistakes and how to avoid them to help you better protect your ASP.NET applications.

The 3+3 is that I am going to explain 3 common simple ones and 3 security ones. Let’s start with the most common ones

3 Common Mistakes made in ASP.NETΒ πŸ“š

ToLower() in LINQ Query Doesn’tΒ Work

The ToLower function returns a lowercased duplicate of a string. When you try to compare numbers from multiple sources, though, this might result in a perplexing error. Consider the following example:

list = (from ds in dbContext.dotnetsaferServices
             join c in dbContext.customer on ds.customerName equals c.customerName)
              where  (ds.shield.number.ToLower().Contains(productLicense.ShieldNumber.ToLower()))

One approach is use IndexOf only with case-insensitive OrdinalIgnireCase attribute within the query instead ofΒ .ToLower:

list = (from ds in dbContext.dotnetsaferServices
join c in dbContext.customer on ds.customerName equals c.customerName)
Where (ds.shield.number.IndexOf(productLicense.ShieldNumber, StringComparison.OrdinalIgnoreCase) != -1))

Not Making Use of Dependency Injection

Assume our Controller requires a FooService to obtain a Foo that it may deliver to the user, as seen below:

public class FooController

    public IActionResult Index()
        var fooService = new FooService(new BarService(), new BazService());
        return View(fooService.GetFoo());

The problem is that our Controller requires specifics on how to establish a FooService. That implies we’ll have to repeat that reasoning every time a FooService is required.

Dependency Injection is a built-in feature of ASP.NET 5 MVC 6. As a result, you may indicate the dependence in the constructor. The ASP.NET 5 framework would then submit it on our behalf.

Incorrect usage of the VarΒ keyword

The misuse and abuse of the var keyword is a common and fundamental problem. The true function of var is to allow us to declare a local variable when you don’t know what type it is. This is frequently the case with anonymous types because you don’t know what the type name is until compile time.

Nonetheless, some programmers use var every time they define a variable. The type name in a local variable declaration adds another layer of description:

// let's say you have a static method called GetProducts()
// that returns System.Data.DataTable
var products = GetProducts(ModelTypes.Subscription);

// how is it clear to the reader that I can do this?
return products.Compute("MAX(Price)", String.Empty);

3 Security Mistakes made in ASP.NETΒ πŸ’»

Storing Secrets inside Web.config

This stems from the desire to save time by storing cryptographic keys in a web.config file. Here’s an example:

<add key="AWS" value="someSecret" />
<add key="Database" value="someKey" />

You should never keep secrets in a web.config file. Therefore, you must redirect the code to a protected file, as seen below:

<appSettings file="Web.SECRETS.config">
<add key="Database" value="someSecret" />

Request with Potentially Dangerous Consequences.Form Value

By default, we’ll get an error because ASP.NET MVC prevents this sort of code from being sent to the server in order to prevent Cross Site Scripting (XSS) attacks. Here’s a fix for an issue that occurs when you try to transmit HTML code to a server.

As demonstrated below, you may deactivate ASP.NET MVC validation for a specific field by using the AllowHtml attribute for the model class.

public class ProductModel

    [Display(Name = "Description:")]
    public string Description  get; set; 

Not using to the client an XSRFΒ token

Cross-site request forgeries are prevented via XRSF tokens. You must utilize them whenever the browser can implicitly authenticate the user. This covers programs that use Windows authentication or use automated authentication using cookies.

Let’s see an example:

public class SecurityController : Controller

    private readonly IAntiforgery _antiforgery;

    public SecurityController(IAntiforgery antiforgery)
        _antiforgery = antiforgery;

    public IActionResult Get()
        var tokens = _antiforgery.GetAndStoreTokens(HttpContext);

        return new ObjectResult(new 
            token = tokens.RequestToken,
            tokenName = tokens.HeaderName

ASP.NET is a web development framework that can be either open-source or commercial. ASP.NET is used to create web pages, web applications, and XML Web Services.

Security is a major issue for many of the ASP.NET applications today because of the common vulnerabilities of SQL injection and Cross-site scripting (XSS).

Although it is difficult for a developer to make an error-free software product, these common security errors mentioned above can be easily avoided when developing ASP.NET applications.

Source link

Everything You Need to Know About Blazor Kanban Cards

Learn how to work with cards in the Syncfusion Blazor Kanban component. You will learn about a few card options like setting card headers, content, and the left border color.

Product Overview: Blazor Kanban

Download an example from GitHub:

Refer to the following documentation to learn about Blazor Kanban cards:

Check out this online example of Blazor Kanban cards:

Watch the following video to customize the Blazor Kanban cards using templates:

Watch the following video to get started with a Blazor WebAssembly app and add Syncfusion Blazor components to it:

Source link

Create Blazor Polar and Radar Charts in Just 10 Minutes

Learn how easily you can create and configure Syncfusion Blazor polar and radar charts in a Blazor WebAssembly app using Visual Studio 2019. In this video, you will learn how to add a simple Blazor polar and radar charts to a Blazor WebAssembly app. You will see how to render the Blazor radar and polar charts with basic features like data markers, series plotting types, and tooltips.

Explore our tutorial videos:

Download example from GitHub link:

Source link