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)

Working with firewall rules

Needed to be able to work with firewall rules on servers at work, so decided to start by getting the actual rule query and update part done, so I can add them to a more fleshed out script later.

#NetFirewallRule method for newer versions of Powershell

#Create a new test rule
New-NetFirewallRule -DisplayName "BLACKLIST_IN" -RemoteAddress 9.9.9.9 -Direction Inbound -Protocol TCP -LocalPort Any -Action Block

#Get the IP addresses in the current rule for the remote address field
$curIP = (Get-NetFirewallRule -DisplayName "BLACKLIST_IN" | Get-NetFirewallAddressFilter).RemoteAddress

#Define the new IP addresses to add, and then merge the lists
$newIPs = "9.9.9.10-9.9.9.11","9.9.9.14/31"
$addIPs = @($newIPs) + @($curIP)

#Set the rule with the new list
Set-NetFirewallRule -DisplayName "BLACKLIST_IN" -RemoteAddress $addIPs
Code language: PowerShell (powershell)
#netsh version for older versions of Powershell

#Get the current rule and convert it from comma separated to a list
$netshout = netsh advfirewall firewall show rule name="BLACKLIST_IN"
$nshIP=($netshout | findstr RemoteIP).trim("RemoteIP: ").split(",")

#Define the new IP addresses to add, and then merge the lists
$newnshIPs = "9.9.9.13","9.9.9.14/31"
$nshaddIPs = @($nshIP) + @($newnshIPs)

#Take the new list and convert back to comma separated
$IPList = ($nshaddIPs | Select-Object) -join ","

#Set the rule with the new list
netsh advfirewall firewall set rule name ="BLACKLIST_IN" new remoteip=$IPList
Code language: PowerShell (powershell)

Adding list entry to the Python script

Next up is adding the ability to enter a comma separated list to the script, so that multiple values can be processed at once. The list will still be validated, and if there are values that are not positive integers they will be ignored.

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):
    if validated_days == "quit":
        quit()
    try:
        print(days_to_units(int(validated_days)))
    except ValueError:
        print("Please enter a positive integer value...")

days_entry = 0
while days_entry != "quit":
    days_entry = input("Enter the number of days, and enter 'quit' to exit the program: ")
    for num_of_days in days_entry.split(","):
        validate_and_execute(num_of_days)
Code language: Python (python)

Even more Python in the mix

Added a very simple while loop to the script, as well as a check for the word ‘quit’ which will exit the program cleanly. It will still catch any negative, 0, string or null (enter key with no value) and prompt to enter an integer again.

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():
    days_entry = 0
    try:
        days_entry = input("Enter the number of days, and enter 'quit' to exit the program: ")
        print(days_to_units(int(days_entry)))
    except ValueError:
        if days_entry == "quit":
            quit()
        else:    
            print("Please enter a positive integer value...")

while True:
    validate_and_execute()
Code language: Python (python)

Getting the hang of Python

Following a Python video on Youtube, and think I am doing pretty good so far. Finally got the following compacted as much as I can do for now, but really happy with it.

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():
    try:
        days_entry = int(input("Enter the number of days: "))
        print(days_to_units(days_entry))
    except ValueError:
        print("Please enter a positive integer value...")

validate_and_execute()
Code language: Python (python)

Editors

I thought I would share images of my development setups. I have Visual Studio Community set up in a virtual machine running Windows 10 to do my Powershell and Windows C++ stuff on, and then have Visual Studio Code set up on my main desktop, and interfaced with the Windows Subsystem for Linux, so that I can work on a lot of the languages that can be set up in Linux. I even threw Haskell in there for fun.