Coding

All things computer programming related...

Convert images to Base64 strings and vice versa

- Posted in Coding by

I wrote a library, crypt.dll that permits conversion of images to Base64 strings, and vice versa. The source code can be downloaded from github

Numerical encoding of text using c-sharp

- Posted in Coding by

It just so happens that any character we might use in a string has a numerical encoding. The alphabet ranges from 65-90 for capital letters A through Z, and from 97-122 for lowercase letters a-z. When we want to work with text encoding, we need to add the following namespace to the top of our source code file:

using System.Text;

The numerical representation of our English alphabet takes the form of unique numbers for each upper and lowercase letter, and these are stored in a variable type called byte. A byte is an 8-bit integer that can hold values from 0 to 255.

If we have a string variable named sChar, we can obtain its numerical encoding as follows, if we have referenced the System.Text namespace:

byte[] bt = Encoding.Default.GetBytes(sChar);

The reverse is encoding bytes to characters. If we have an array of bytes, we can convert each element’s value to its corresponding character:

byte[] bytes = {40, 80, 20};
char result;
foreach(byte number in bytes)
{
    result = Convert.ToChar(number);
    Console.WriteLine(“{0} converts to {1}.”, number, result);
}

You can download a sample program here.

Sort a list of DateTime objects

- Posted in Coding by

This sample program shows how, in C#, to sort a list of DateTime objects either in ascending or descending order.

Handy way to access constants in c-sharp application

- Posted in Coding by

It can be convenient to put constants that need to be available throughout your project into their own public class, accessible from other code belonging to the same namespace. For instance, if our project namespace is EarthApotheosis, we might set up our constants like this:

using System;

namespace EarthApotheosis {

  public class EarthApotheosisConstants
  {
      public static string TITLE = Properties.Resources.Title;
      public const int KILLS_TO_EARN_ONE_COMBAT_ADV_POINT = 50;
      public const int MAX_CHARS_PER_LINE_IN_LABEL_DISPLAY = 80;
      public const string INPUT_CURRENTLY_DISABLED = "Input currently disabled...";
      public const string AVATAR_NAME_NEEDED = "Please specify avatar name...";

  }

}

We'd then reference constants from with our project's main form as follows:

int max_chars = EarthApotheosisConstants.MAX_CHARS_PER_LINE_IN_LABEL_DISPLAY;

Lazy day

- Posted in Coding by

I've been lazy today. I finished a sci-fi movie named 'Quanta', did a little website updating, ran some backups, started Season 3 of Colony, and made a payment on my Amazon Store card.

Learned that Hannah's fiance's grandfather fell and broke a hip. Mother has left for the Outer Banks with Sharylon. She plans on getting back on the 6th. We got a $200 bonus at work Friday in the form of a credit card. I spent mine on a Windows 10 Pro PC-on-a-stick. Should be a handy gadget to have. I've also ordered a 10" android tablet for Susan, and an identical one for me. They run the latest Android OS, Pie.

Emma got in from the University of Kentucky last night, and slept late today. Her classes are difficult, but I think she's enjoying college life. She heated up a pizza for lunch, and Susan and I had some. It's in the 90s today through next Thursday. Then, starting next Friday we should have a few cooler days in the 70s.

I wrote a C# console app today that will wind up saving me a few minutes everyday that I had been spending to launch 7zip and manually zip multiple subdirectories of my My Documents for backup via uploading. Note: I commented-out the section that zips my DokuWiki, because I hope to replace it with localhost-hosted blog entries.

Here is the source code:

using System;
using System.IO;
using System.Diagnostics;
using System.Threading;

namespace ZipThem{

    class Program {

        static void Main(string[] args){

            ProcessStartInfo startInfo = new ProcessStartInfo();
            Console.Clear();            

            startInfo.FileName = @"C:csdevtoolsZipFolder.exe";
            if(!File.Exists(startInfo.FileName)){
                Console.WriteLine("n Couldn't find ZipFolder.exe in csdevtools... goodbye...");
                Thread.Sleep(1500);
                Environment.Exit(0);
            }

            string startPath = @"C:UserskyratDocumentspublic_html";
            string zipPath = @"C:UserskyratDocumentspublic_html.zip";
            ZipDirectory(startPath, zipPath, startInfo);

            startPath = @"C:UserskyratDocumentsTwine";
            zipPath = @"C:UserskyratDocumentsMyTwineStories.zip";
            ZipDirectory(startPath, zipPath, startInfo);

            startPath = @"C:UserskyratDocumentsMySquiffy";
            zipPath = @"C:UserskyratDocumentsMySquiffy.zip";
            ZipDirectory(startPath, zipPath, startInfo);   

            startPath = @"C:Zwamp";
            zipPath = @"C:UserskyratDocumentswebsite atop zwamp.zip";
            ZipDirectory(startPath, zipPath, startInfo);       

            startPath = @"C:csdev";
            zipPath = @"C:UserskyratDocumentscsdev.zip";
            ZipDirectory(startPath, zipPath, startInfo);            

/*             startPath = @"C:UserskyratDocumentsDokuWik";
            zipPath = @"C:UserskyratDocumentsDokuWik.zip";
            ZipDirectory(startPath, zipPath, startInfo);               */

            Console.WriteLine("nn Press any key to exit...");
            Console.ReadKey();
        }

        static void ZipDirectory(string startPath, string zipPath, ProcessStartInfo startInfo){
            if(Directory.Exists(startPath)){
                try{                                        
                    if(File.Exists(zipPath)){ File.Delete(zipPath); }
                    Console.Write("n Now zipping '{0}' folder...", startPath);
                    Console.WriteLine(" to {0}", zipPath);
                    Thread.Sleep(2000);
                    startInfo.Arguments = startPath + " " + zipPath; 
                    var proc = Process.Start(startInfo);
                    proc.WaitForExit();
                    Console.WriteLine(" Successfully zipped folder {0}", Path.GetFileName(startPath));
                }catch(Exception ex1){
                    Console.WriteLine("n Exception thrown while trying to zip folder 'public_html':n " + ex1.Message);
                }
            }            
        }


    }

}

Twine Fray

- Posted in Coding by

I've discovered the blog of Mr. Riley, a web programmer. He has lots of great Twine code examples.

Mr. Riley is a teacher. He has a good starting point example of a combat system for a Twine game called Twine Fray.

I plan to scour his blog for learning purposes.

Lately, I've been reading some articles put out by prominent researchers in the SETI at Home project: Here is an explanation of the Drake Equation. And here is an article of what we might expect from E.T.

For a while now, I've had my desktop PC (which I don't use on a daily basis but do leave running) executing BOINC and assisting the SETI @ Home program to process telescopic data.

BOINC downloads scientific computing jobs to your computer and runs them invisibly in the background. It's easy and safe.

About 30 science projects use BOINC; examples include Einstein@Home, IBM World Community Grid, and SETI@home. These projects investigate diseases, study global warming, discover pulsars, and do many other types of scientific research.

Batch file time saver

- Posted in Coding by

Part of my morning routine is to launch three applications which I use to record my previous day's caloric intake and expenditure (per data from my FitBit device).

The following text in a batch file suffices to save me a few clicks and the better part of a minute's time:

start cmd.exe /k cd C:/csdev/utils/cal
START C:/windows/system32/calc.exe
start cmd.exe /k cd C:/Users/[user]/Documents/DokuWik

Note that I've replaced my actual username in the third line of the batch file code above with [user], for security purposes.

This batch file launches Windows' calculator, and opens command prompts at the directories containing my calorie tracking console C# app, and the launcher for my local DokuWiki. It saves me time navigating the directory structure. All I have to do after clicking this batch file is enter the requisite program name in each command prompt — in my case, cal in one prompt, run in the other.

Squiffy timeout

- Posted in Coding by

It's easy to sleep or pause or delay for x milliseconds in Squiffy. The following code makes use of the javascript setTimeout function (each Section in your Squiffy source code can call javascript code if it precedes all other Squiffy script in that passage). You can copy/paste the following code into a new Squiffy project and it will run:

[code] [[Start]]: setTimeout(function () { squiffy.story.go("next"); }, 2000);

Hello Bob!

[[next]]: setTimeout(function () { squiffy.story.go("next2"); }, 2000); Bob, are you there??

[[next2]]: Hmm, Bob's not around... [/code]

Javascript has a function called setTimeout that allows us to run a function once after the specified interval of time. For instance, this code calls sayHi() after one second:

function sayHi() {
  alert('Hello');
}

setTimeout(sayHi, 1000);

ILMerge error

- Posted in Coding by

Sometimes you'll get “Unresolved assembly reference not allowed” when attempting to use ILMerge. To avoid this, specify the full path to the framework you're targeting, like this on the command line:

ilmerge /targetplatform:v4,"C:WindowsMicrosoft.NETFramework64v4.0.30319" /out:merged.exe myprogram.exe mylib1.dll mylib2.dll

Created specific sized file at the Windows command line

- Posted in Coding by

Create file of specific size at Windows command line:

fsutil file createnew filename number_of_bytes
Page 5 of 7