Home ProgrammingC# Programming: Tips & Tricks (Part I)

Programming: Tips & Tricks (Part I)

by Kliment Andreev
5.1K views

pass variables between two forms in Visual C++

This example will show you how to pass variables between two forms in Visual C++. We’ll create two forms, drop a button and a text box on the first form and a label box on the second form. When we start the program, we can type something in the text box. Once we click the button, the second form will show up with the label containing the text from the text box that’s on the first form.
First, let’s create a project in VC++ 2008. Click File | New, then Visual C++ and then Windows Forms Application. From the Toolbox, drag and drop, a button and a text box. Next, from the Solution Explorer on the right, right-click the name of your project, choose Add, New Item and then Windows Form. When the second form appears, drag and drop a label on the form. Save all files. Open the source for the first form (probably Form1.h) and right after the #pragma statement insert:

#include "Form2.h"
// Make sure that the source file name is correct

Then, switch to the design mode for the first form, double-click the button control and put the following lines between the brackets. This is an event-handler that runs when the button is clicked.

Form2^ newform = gcnew Form2;
newform -> strSomething = textBox1->Text
if (newform->ShowDialog(this) == ::DialogResult::OK) delete newform;

Switch to the source of the second form and define the string strSomething as shown. That’s the variable that we are using to pass values.

public:
		Form2(void)
		{
			InitializeComponent();
			//
			//TODO: Add the constructor code here
			//
		}    

		        String^ strSomething;

	protected:
		///

Now, switch to the desing mode of the second form, double-click anywhere on the form to invoke the event-handler that runs when the form is loaded. Here, insert the following statement.

label1->Text = strSomething;

As you can probably see, we created the second form with an extra parameter of string type. When we created this form within the source of the first form, we passed the value of textBox1 to that parameter and then in the second form, we take that value and assign it to the label. We can’t use something like this:

newform->label1->Text = textBox1->Text;

That’s because label1 is a private member of the Form2 class and strSomething is a public member.

System uptime – Visual C++ utility

It’s been a while when I was programming in C, maybe more than 15 years. I decided to refresh my memory and create a small console application that will give me the system uptime and the date and time when the OS was installed. This small app should work on all platforms after Windows 2000.

I used Visual C++ 2008 and this program compiles without any errors or warnings. While I was browsing for the solutions implemented in this program, I found that some of the proposed solutions won’t compile on VC 2008.

Start VC2008, choose File | New | Project. For Project Types choose Win32 and then Win32 Console Application. You can copy and paste the whole source below. This is a simple console application and there are no extra header files or any resource files. You can also, download the executable that’s attached.

#include "stdafx.h"
#include <windows.h>       

char* GetUptime()
{
   int tickCount, nTime[5];
   static char szUptime [1000];
   tickCount = GetTickCount();
   nTime[0] = tickCount / 1000 % 60; // Seconds
   nTime[1] = tickCount / 1000 / 60 % 60; // Minutes
   nTime[2] = tickCount / 1000 / 60 / 60 % 24; // Hours
   nTime[3] = tickCount / 1000 / 60 / 60 / 24 % 7; // Days
   nTime[4] = tickCount / 1000 / 60 / 60 / 24 / 7 % 52; // Weeks
   memset(szUptime, 0, sizeof(szUptime));       

   for(int i = 4; i >= 0; i--)
   {
      char* szLabel;
      char tmpUptime[3];       

      if (i == 4) (nTime[4] > 1 || nTime[4] == 0) ? szLabel = " Weeks, " : szLabel = " Week, ";
      else if (i == 3) (nTime[3] > 1 || nTime[3] == 0) ? szLabel = " Days, " : szLabel = " Day, ";
      else if (i == 2) (nTime[2] > 1 || nTime[2] == 0) ? szLabel = " Hours, " : szLabel = " Hour, ";
      else if (i == 1) (nTime[1] > 1 || nTime[1] == 0) ? szLabel = " Minutes, " : szLabel = " Minute, ";
      else if (i == 0) (nTime[0] > 1 || nTime[0] == 0) ? szLabel = " Seconds" : szLabel = " Second";
      memset(tmpUptime, 0, sizeof(tmpUptime));
      _itoa_s(nTime[i], tmpUptime, 3, 10);
      strcat_s(szUptime, 1000, tmpUptime);
      strcat_s(szUptime, 1000, szLabel);
      }       

   return szUptime;
}       

char* GetInstalled()
{
   HANDLE hFile;
   WIN32_FIND_DATA FileInformation;
   SYSTEMTIME st;
   char tmpChar[12];
   char* month = "";
   char* comma = ", ";
   char* space = " ";
   char* colon = ":";
   TCHAR winDir[MAX_PATH];
   static char szInstalled[1000];
   GetWindowsDirectory(winDir, MAX_PATH);
   hFile = ::FindFirstFile(winDir, &FileInformation);
   FileTimeToSystemTime(&FileInformation.ftCreationTime, &st);
   switch (st.wMonth)
   {
      case 1:
      month = "January ";
      break;
      case 2:
      month ="February ";
      break;
      case 3:
      month = "March ";
      break;
      case 4:
      month ="April ";
      break;
      case 5:
      month = "May ";
      break;
      case 6:
      month ="June ";
      break;
      case 7:
      month = "July ";
      break;
      case 8:
      month ="August ";
      break;
      case 9:
      month = "September ";
      break;
      case 10:
      month ="October ";
      break;
      case 11:
      month = "November ";
      break;
      case 12:
      month ="December ";
      break;
      default:
      break;
   }       

   strcat_s(szInstalled, 1000, month);
   _itoa_s(st.wDay, tmpChar, 12, 10);
   strcat_s(szInstalled, 1000, tmpChar);
   strcat_s(szInstalled, 1000, comma);
   _itoa_s(st.wYear, tmpChar, 12, 10);
   strcat_s(szInstalled, 1000, tmpChar);
   strcat_s(szInstalled, 1000, space);
   _itoa_s(st.wHour, tmpChar, 12, 10);
   strcat_s(szInstalled, 1000, tmpChar);
   strcat_s(szInstalled, 1000, colon);
   _itoa_s(st.wMinute, tmpChar, 12, 10);
   strcat_s(szInstalled, 1000, tmpChar);
   strcat_s(szInstalled, 1000, colon);
   _itoa_s(st.wSecond, tmpChar, 12, 10);
   strcat_s(szInstalled, 1000, tmpChar);
   return szInstalled;
}
int _tmain(int argc, _TCHAR* argv[])
{
      char* upTime;
      char* installed;
      printf("%s\n", "-----------------------------------------------------------------");
      printf("%s\n", "KInfo v0.1 -- Program by Kliment Andreev -- Public Domain -- 2009");
      printf("%s\n", "-----------------------------------------------------------------");
      upTime = GetUptime();
      printf("%s%s"," System Uptime: ", upTime);
      installed = GetInstalled();
      printf("\n%s%s\n","System Installed: ", installed);
      return 0;
}

kinfo2

Enumerating files and folders in Visual C++

This is a program that will enumerate all files, folders and sub-folders under a given folder. Folders with no access will be skipped and an *ERROR* message will be recorded on the console. Attached is the executable file (link at the bottom).

#include "stdafx.h"    

using namespace System;
using namespace System::Collections;
using namespace System::IO;    

int main(array ^args)
{
	array^ strSubFolders = gcnew array(20);
	array^ strFiles = gcnew array(20);
	Stack^ objFolders = gcnew Stack;
	Object^ objItem;
	String^ strSourceFolder;
	String^ strCurrentFolder;
	String^ strEachFile;
	String^ strEachFolder;
	String^ strArgs;
	int ArgsCounter=0,
		FileCounter=0,
		FolderCounter=0,
		ErrorCounter=0;    

	for each (strArgs in args) ArgsCounter++;    

	if (ArgsCounter==0) {
		Console::WriteLine("Usage: eff , enumerates all files and folders under ");
		Console::WriteLine("Public domain - Program by Kliment Andreev, 2009");
		return 0;
	}    

	strSourceFolder = args[0];    

	if (!System::IO::Directory::Exists(strSourceFolder)) {
		Console::WriteLine("Folder doesn't exist!");
		return 0;
	}    

	objFolders->Push(strSourceFolder);	    

	while (objFolders->Count > 0) {
		objItem = objFolders->Pop();
		strCurrentFolder = safe_cast(objItem);
		Console::WriteLine("{0}",strCurrentFolder);    

		try {
			strSubFolders = Directory::GetDirectories(strCurrentFolder);
			strFiles = Directory::GetFiles(strCurrentFolder);    

			for each (strEachFile in strFiles){
				FileInfo^ fi = gcnew FileInfo(strEachFile);
				Console::WriteLine("{0}\\{1} ",fi-&gt;DirectoryName,fi->Name);
				FileCounter++;
			}    

			for each (strEachFolder in strSubFolders) {
				objFolders->Push(strEachFolder);
				FolderCounter++;
			}    

		}    

		catch(System::Exception ^ex) {
			Console::WriteLine("*ERROR* {0}",ex->Message);
			ErrorCounter++;
		}
	}    

	Console::WriteLine("\nTotal: {0} files, {1} folders and {2} errors.", \ 
FileCounter, FolderCounter, ErrorCounter);    

    return 0;
}

eff

C#: Recreate directory structure

I made this small utility to help me recreate a directory structure for a project that I was working on. For example, you want to create the same directory structure as C:\Windows but under the D:\ drive. In order to do that, you have to export the directory structure to a file (dirstruct -r c:\windows > file.txt) and then create the directory structure using dirstruct -w file.txt d:\. Expand for the source.

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;

namespace dirstruct
{
    class Program
    {
        static void Main(string[] args)
        {
            void PrintUsage()
            {
                string strDash = new String('-', 98);
                Console.WriteLine(strDash);
                Console.WriteLine("dirstruct -r <directory>        - Lists all directories and subdirectories.");
                Console.WriteLine("                                  If no <directory> is given, uses the current directory.");
                Console.WriteLine("dirstruct -w <file> <directory> - Recreates the directory structure under the specified directory.");
                Console.WriteLine("                                  If no <directory> is given, uses the current directory.");
                Console.WriteLine(strDash);
                Console.WriteLine("Examples:  dirstruct -r C:\\users > mydirs.txt");
                Console.WriteLine("           dirstruct -w mydirs.txt D:\\");
                Console.WriteLine("           Recreates the structure C:\\users under D:\\");
                Console.WriteLine("           You'll get D:\\users structure same as C:\\users");
                Console.WriteLine(strDash);
                Console.WriteLine("dirstruct : Kliment Andreev - 2020 - Simplified BSD License");
            }

            void CreateDirectories(string strFN, string strEP)
            {
                string strLine;
                System.IO.StreamReader file = new System.IO.StreamReader(@strFN);
                while ((strLine = file.ReadLine()) != null)
                {
                    string strDirectoryName = strEP + strLine.Substring(2);
                    try
                    {
                        DirectoryInfo di = Directory.CreateDirectory(strDirectoryName);
                        Console.WriteLine(strDirectoryName);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("The process failed: {0}", e.ToString());
                    }
                }
                file.Close();
            }

            string strEntryPath = @"";
            string strFileName = @"";
            string strOperation = "";
            int intErr = 0;
            if (args.Length == 0)
            {
                PrintUsage();
                intErr = 0;
                Environment.Exit(intErr);
            }
            if (args.Length > 3)
            {
                PrintUsage();
                intErr = 1;
                Environment.Exit(intErr);
            }
            if (args[0].Length != 2)
            {
                PrintUsage();
                intErr = 1;
                Environment.Exit(intErr);
            }
            switch (args[0].Substring(0, 2))
            {
                case "-r":
                    if (args.Length == 1)
                    {
                        strEntryPath = Directory.GetCurrentDirectory();
                    }
                    if (args.Length == 2)
                    {
                        strEntryPath = args[1];
                    }
                    if (args.Length == 3)
                    {
                        Console.WriteLine("Too many arguments.");
                        intErr = 1;
                    }
                    strOperation = "R";
                    break;
                case "-w":
                    if (args.Length == 1)
                    {
                        intErr = 1;
                        Console.WriteLine("File name missing.");
                    }
                    if (args.Length == 2)
                    {
                        strFileName = args[1];                        
                    }
                    if (args.Length == 3)
                    {
                        strFileName = args[1];
                        strEntryPath = args[2];
                    }
                    strOperation = "W";
                    break;
                case "-h":
                    PrintUsage();
                    break;
                default:
                    Console.WriteLine("Unknown argument.");
                    intErr = 1;
                    break;
            }
            if (intErr == 1) Environment.Exit(intErr);
            if ((!Directory.Exists(@strEntryPath)) & (strEntryPath !=""))
            {
                Console.WriteLine(@strEntryPath + " does not exists or incorrect.");
                intErr = 1;
            }
            if ((!File.Exists(@strFileName)) & (strOperation == "W"))
            {
                Console.WriteLine(@strFileName + " does not exists or incorrect.");
                intErr = 1;
            }
            if (intErr == 1) Environment.Exit(intErr);
            if (strOperation == "R")
            {
                List<string> listDirs = ListDirectories.GetDirectories(@strEntryPath);
                foreach (string strDirectory in listDirs)
                {
                    Console.WriteLine(strDirectory);
                }
            }
            if ((strOperation == "W") && (args.Length == 2))
            {
                Console.WriteLine("You will create a directory structure in the current directory.");
                Console.WriteLine("Are you sure you want to continue (Y/N)?");
                string strYN = Console.ReadLine().ToUpper();
                if (strYN == "Y")
                {
                    strEntryPath = Directory.GetCurrentDirectory();
                    CreateDirectories(strFileName, strEntryPath);
                }
                else
                {
                    Console.WriteLine("Exiting. No changes were made.");
                    Environment.Exit(0);
                }
            }
            if ((strOperation == "W") && (args.Length == 3))
            {
                Console.WriteLine("You will create a directory structure under " + strEntryPath);
                Console.WriteLine("Are you sure you want to continue (Y/N)?");
                string strYN = Console.ReadLine().ToUpper();                
                if (strYN == "Y")
                {
                    CreateDirectories(strFileName, strEntryPath);
                }
                else
                {
                    Console.WriteLine("Exiting. No changes were made.");
                    Environment.Exit(0);
                }
            }

        }
    }
    public class ListDirectories
    {
        public static List<string> GetDirectories(string strPath, string strSearchPattern = "*",
            SearchOption searchOption = SearchOption.AllDirectories)
        {
            if (searchOption == SearchOption.TopDirectoryOnly)
                return Directory.GetDirectories(strPath, strSearchPattern).ToList();

            List<string> listDirectories = new List<string>(GetDirectories(strPath, strSearchPattern));

            for (var i = 0; i < listDirectories.Count; i++)
                listDirectories.AddRange(GetDirectories(listDirectories[i], strSearchPattern));

            return listDirectories;
            
        }

        private static List<string> GetDirectories(string strPath, string searchPattern)
        {
            try
            {
                return Directory.GetDirectories(strPath, searchPattern).ToList();
            }
            catch (UnauthorizedAccessException)
            {
                return new List<string>();
            }
        }
    }
}

Dockerize a Node.js application

My Node.js app has index.html, server.js and styles.css files. First, initialize the app and enter the values for the app.

npm init

Install all the dependent modules for the app.

npm install express socket.io --save

Create the Dockerfile.

FROM node:18

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

# Bundle app source
COPY . .

EXPOSE 3000
CMD [ "node", "server.js" ]

Create a .dockerignore file to omit some of the files that are not necessary.

cat <<EOF > .dockerignore
node_modules
npm-debug.log
EOF

Build the image.

docker build . -t <your username>/node-web-app

Check the image.

docker images

Test the image.

docker run -p 3000:3000 -d <your username>/node-web-app

Is the container running?

docker ps

Check the logs for the container.

docker logs <container id>

If needed, attach to the shell of the running container.

docker exec -it <container id> /bin/bash

HTML/CSS/JavaSccript boilerplate

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>HTML 5 Boilerplate</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <p>HTML</p>
    <script src="script.js"></script>
  </body>
</html>

style.css

p {
  background-color: yellow;
}

script.js

'use strict';

console.log('JavaScript');

Related Articles

2 comments

Winton April 15, 2014 - 12:53 PM

Hi Dude, I’m a bit of a Visual C++ novice, but I mostly understand your post. There appear to be few bits of HTML code showing that shouldn’t, and I’m wondering if they are causing me enough confusion not to get the code shown working. I don’t see an error message though – just the second form doesn’t load. Any chance you can clearup the HTML?
Regardos,
Winton.

Kliment Andreev April 15, 2014 - 8:54 PM

I had some old HTML tags.

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More