New languages are fun…

Been playing around with Zig, which is a new language that is still in beta for the most part, but is pretty well polished already, and can be used as a drop-in replacement compiler/linker for C/C++. Home ⚡ Zig Programming Language (ziglang.org)

The syntax highlighting below may be a bit drab, but C++ seemed to be the closest option in the plugin being used.

const std = @import("std");
const print = std.debug.print;

pub fn main() !void {
    for (1..1001) |counter_value| {
        for (1..1001) |counter_value2| {
            print("Value1 = {} and Value2 = {}\r", .{ counter_value, counter_value2 });
        }
    }
    print("\n", .{});
}

Code language: C++ (cpp)
const std = @import("std");
const print = std.debug.print;

pub fn main() !void {
    var counter_value: u32 = 0;
    while (counter_value <= 10000) : (counter_value += 1) {
        var counter_value2: u32 = 0;
        while (counter_value2 <= 10000) : (counter_value2 += 1) {
            print("Value1 = {} and Value2 = {}\r", .{ counter_value, counter_value2 });
        }
    }
    print("\n", .{});
}

Code language: C++ (cpp)

Adventure in Windows Assembly

So, I decided to see what I would need to do to create a Windows program in assembly. Started with a basic Hello World example that I found on the internet, and then had to debug it to get it to compile and link correctly in MASM. Had to change title to win_title, for one of the ‘variables’, as title seems to be a reserved word. Went ahead and changed msg to win_msg to have a matching naming convention for both values.

;---ASM Hello World Win64 MessageBox

extrn MessageBoxA: PROC
extrn ExitProcess: PROC

.data
win_title db 'Hello', 0
win_msg db 'Hello World!', 0

.code
main proc
  sub rsp, 28h  
  mov rcx, 0       ; hWnd = HWND_DESKTOP
  lea r8, win_title    ; LPCSTR lpCaption
  lea rdx, win_msg     ; LPCSTR lpText
  mov r9d, 0       ; uType = MB_OK
  call MessageBoxA
  add rsp, 28h  
  mov ecx, eax     ; uExitCode = MessageBox(...)
  call ExitProcess
main endp

EndCode language: Intel x86 Assembly (x86asm)

Creating sites and application pools in IIS from Powershell

I was messing around with my test/dev virtual machine over on Azure, after having blown away the old one so that I could create one with Server 2022, and got tired of creating the pools and sites manually. The code below is the result of a few hours of research and tinkering around, but works well for what I am doing.

This first part is used when creating the main part of the domain on the server.

$Domain="domain.tld"

New-Item -ItemType Directory -Path "W:\inetpub\vhosts\$Domain\" -Name httpdocs
New-Item -ItemType Directory -Path "W:\inetpub\vhosts\$Domain\" -Name logs

New-Item IIS:\AppPools\$Domain

New-Item IIS:\Sites\$Domain -bindings @{protocol="http";bindingInformation="*:80:$Domain"} -physicalPath W:\inetpub\vhosts\$Domain
Set-ItemProperty "IIS:\Sites\$Domain" -name logFile -value @{directory="W:\inetpub\vhosts\$Domain\logs"}
Set-ItemProperty IIS:\Sites\$Domain -name applicationPool -value $Domain
Code language: PowerShell (powershell)

The code below is used for adding a subdomain, and would need to have the wildcard SSL issued for the related main domain already, which I am currently getting from Let’s Encrypt via the Certify the Web application in Windows.

$Domain="sub.domain.tld"
$Parent=$Domain.Substring($Domain.IndexOf(".") + 1)
$Child=$Domain.Split('.')[0]
$Cert = (Get-ChildItem Cert:\LocalMachine\My | Where{$_.Subject -eq "CN=*.$Parent"}).ThumbPrint

New-Item W:\inetpub\vhosts\$Parent\$Child -type Directory

New-Item IIS:\AppPools\$Domain

New-Item iis:\Sites\$Domain -bindings @{protocol="http";bindingInformation="*:80:$Domain"} -physicalPath W:\inetpub\vhosts\$Parent
Set-ItemProperty "IIS:\Sites\$Domain" -name logFile -value @{directory="W:\inetpub\vhosts\$Parent\logs"}
New-IISSiteBinding -Name "$Domain" -BindingInformation "*:443:$Domain" -CertificateThumbPrint $Cert -CertStoreLocation "Cert:\LocalMachine\My" -Protocol https
Set-ItemProperty IIS:\Sites\$Domain -name applicationPool -value $Domain
Code language: PowerShell (powershell)

Finally, two simple lines that can be used to remove the pool and site for any domain/subdomain.

Remove-WebSite -Name "$Domain"
Remove-WebAppPool -Name "$Domain"
Code language: PowerShell (powershell)

Recursion in C#

Decided to try my hand at writing a recursive function today, and was able to do so, and have it work without a lot of work.

using System;

namespace Recursion
{
    class Program
    {
        private static void recursiveLoop(int startNumber,int endNumber)
        {
        if (startNumber <= endNumber)
            {
                Console.WriteLine(startNumber);
                startNumber++;
                recursiveLoop(startNumber,endNumber);
            }
        }
        static void Main(string[] args)
        {
            recursiveLoop(1,10000);
        }
    }
}
Code language: C# (cs)

C# Methods (functions) in separate files

Decided to sit down tonight and work on getting used to working with methods in C#, and how to work with them in external files, to help organize the code. Need to be comfortable doing so for when I start doing more OOP style stuff with classes and such.

//Program.cs

using System;

namespace TryingStuff2
{
    class Program
    {
        static void Main(string[] args)
        {
            int numberOne = 5;
            int numberTwo = 7;

            Console.WriteLine(MathFunctions.AddNumbers(numberOne, numberTwo));
            Console.WriteLine(MathFunctions.SubNumbers(numberOne, numberTwo));
            Console.WriteLine(MathFunctions.MulNumbers(numberOne, numberTwo));
            Console.WriteLine(MathFunctions.DivNumbers(numberOne, numberTwo));
        }
    }
}
Code language: C# (cs)
//MathFunctions.cs

namespace TryingStuff2
{
    public class MathFunctions
    {
        public static int AddNumbers(int numberOne, int numberTwo)
        {
            return (numberOne + numberTwo);
        }

        public static int SubNumbers(int numberOne, int numberTwo)
        {
            return (numberOne - numberTwo);
        }
        public static int MulNumbers(int numberOne, int numberTwo)
        {
            return (numberOne * numberTwo);
        }

        public static int DivNumbers(int numberOne, int numberTwo)
        {
            return (numberOne / numberTwo);
        }
    }
}
Code language: C# (cs)

Porting from Python to C#

Decided to work on porting at least part of the Python program I had done with the video on Youtube into C#, and am really happy with getting the original core part working.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TryingStuff1
{
    class Program
    {
        static void Main(string[] args)
        {
            string user_input= "";

            while (user_input != "quit")
            {
                int calculation_to_units = 24;
                string name_of_unit = "hours";
                
                Console.Write("Enter the number of days.  Enter 'quit' to exit the program: ");
                user_input = Console.ReadLine();
                Console.Clear();
                if (user_input.ToLower() == "quit")
                {
                    System.Environment.Exit(0);
                }
                else if (int.TryParse(user_input, out int number))
                {
                    int user_input_int;
                    if (int.Parse(user_input) <= 0)
                    {
                        Console.WriteLine("Please enter a positive integer.");
                    }
                    else
                    {
                        user_input_int = int.Parse(user_input);
                        int total_time = user_input_int * calculation_to_units;
                        string conversion_output = String.Format("{0} days are {1} {2}", user_input_int, total_time, name_of_unit);
                        Console.WriteLine(conversion_output);
                        continue;
                    }
                }
                else
                    Console.WriteLine("Please enter an integer or 'quit'.");
            }
        }
    }
}

Code language: C# (cs)

The C# code does not have the functions like the Python code, or the sets being used, but is still doing almost all of the same work.

#! /bin/python

calculation_to_units = 24
name_of_unit = "hours"

def days_to_units(number_of_days):
    if number_of_days > 0:
        return f"{number_of_days} days are {number_of_days * calculation_to_units} {name_of_unit}"
    else:
        return "You did not enter a positive integer..."

def validate_and_execute(validated_days):
    try:
        print(days_to_units(int(validated_days)))
    except ValueError:
        print("Please enter a positive integer value...")

user_input = 0
while user_input != "quit":
    user_input = input("""Enter the number of days (comma separated lists are accepted (e.g. 10, 20, 30).\nEnter 'quit' to exit the program: """)
    if user_input.lower() == "quit":
        quit()
    list_of_days = user_input.split(", ")
    for num_of_days in set(list_of_days):
        validate_and_execute(num_of_days)
Code language: Python (python)

Moving functions to modules.

Learned how to move the functions in my little program out to a separate module file, and then call the functions inside of it as needed. Nice thing is that you do not have to actually import any functions that you do not need, such as ones that are only used by other functions in the same module.

The main part of the program below calls the function validate_and_execute, as well as the variable user_input_message, from the helper.py file in the functions sub-directory.

from functions.helper import validate_and_execute, user_input_mesage
#import functions.helper

user_input = 0
while user_input != "quit":
    user_input = input(user_input_mesage)
    if user_input.lower() == "quit":
        quit()
    days_and_unit = user_input.split(":")
    #print(days_and_unit)
    days_and_unit_dictionary = {"days": days_and_unit[0], "unit": days_and_unit[1]}
    #print(days_and_unit_dictionary)
    validate_and_execute(days_and_unit_dictionary)
Code language: Python (python)

The file below is the actual helper.py file.

def days_to_units(number_of_days, conversion_unit):
    if conversion_unit == "hours":
        calculation_to_units = 24
    elif conversion_unit == "minutes":
        calculation_to_units = 24*60
    else:
        return("Invalid conversion unit...")
        
    if number_of_days > 0: 
        return f"{number_of_days} days are {number_of_days * calculation_to_units} {conversion_unit}."
    else:
        return "You did not enter a positive integer..."

def validate_and_execute(days_and_unit_dictionary):
    try:
        print(days_to_units(int(days_and_unit_dictionary["days"]), str(days_and_unit_dictionary["unit"])))
    except ValueError:
        print("Please correct your input...")

user_input_mesage = """Enter the number of days and conversion to unit (10:minutes or 20:hours).\nEnter 'quit' to exit the program: """
Code language: Python (python)

Pretty cool stuff, and can see how it would make the code more organized.

Using Dictionaries in Python

I have updated the program that I have been writing while following the video I have been watching. I am still having to do some of my own tinkering, as my code is structured slightly different than the one in the video, but works mostly the same, and has a little more entry validation in it. I am pretty sure it could use some more cleaning up, as evolving code usually does, but that can wait until later.

def days_to_units(number_of_days, conversion_unit):
    if conversion_unit == "hours":
        calculation_to_units = 24
    elif conversion_unit == "minutes":
        calculation_to_units = 24*60
    else:
        return("Invalid conversion unit...")
        
    if number_of_days > 0: 
        return f"{number_of_days} days are {number_of_days * calculation_to_units} {conversion_unit}."
    else:
        return "You did not enter a positive integer..."

def validate_and_execute():
    try:
        print(days_to_units(int(days_and_unit_dictionary["days"]), str(days_and_unit_dictionary["unit"])))
    except ValueError:
        print("Please correct your input...")

user_input = 0
while user_input != "quit":
    user_input = input("""Enter the number of days and conversion to unit (10:minutes or 20:hours).\nEnter 'quit' to exit the program: """)
    if user_input.lower() == "quit":
        quit()
    days_and_unit = user_input.split(":")
    #print(days_and_unit)
    days_and_unit_dictionary = {"days": days_and_unit[0], "unit": days_and_unit[1]}
    #print(days_and_unit_dictionary)
    validate_and_execute()
Code language: Python (python)

Simple name entry and validation

Decided to work on getting getting a user to enter their name, and then printing it out. The code below will allow someone to enter their name with characters, spaces and the period, and will then output Hello and their name. Numerals and special characters will not be accepted and will print a message that states that a valid text name needs to be entered. It will also ensure that the first position of the string is a character, and if the last position is a period will not print the period again, in case they enter something like “John S.”.

full_name = input("Enter your name please: ")
if (full_name[0].isalpha()
    and all(x.isalpha() or x.isspace() or x=="." for x in full_name)):
    if (full_name[-1] == "."):
        print("Hello " + full_name)
    else:
        print("Hello " + full_name + ".")
else:    
    print("Please enter a valid text name...")
Code language: Python (python)

More learning the differences…

Decided to start doing small projects to see the differences in how C, C++, C# and Python handle doing the same thing. Started off with a simple enter your name, and then print Hello and the name, since that is one of the more basic things that everyone should know how to do.

// C
#include <stdio.h>
int main()
{
    char name[40];
    printf("Enter your name please: ");
    scanf("%s",name);
    printf("Hello %s.\n", name);
    return 0;
}
Code language: C++ (cpp)
// C++
#include <iostream>
using namespace std;

int main() 
{
    string name;
    cout << "Enter your name please: ";
    cin >> name;
    cout << "Hello " << name << ".\n";
    return 0;
}
Code language: C++ (cpp)
// C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace print_enter
{
    class Program
    {
        static void Main(string[] args)
        {
            string name;
            Console.Write("Enter your name please: ");
            name = Console.ReadLine();
            Console.WriteLine("Hello {0}.\n", name);
        }
    }
}
Code language: C# (cs)
# Python
username = input("Enter your name please: ")
print("Hello " + username + ".")
Code language: Python (python)