Showing posts with label Winforms. Show all posts
Showing posts with label Winforms. Show all posts

January 31, 2019

Batch file script - Get date-time value in string variable

Batch file is an important tool to automate different tasks, e.g. Copying files/folders, Archiving, Taking backups, Running builds and lot more... Often times we need to create date-time stamp in a string variable for different purposes. For example, I want to write a batch script which will copy a file to a destination folder, but before copying in destination folder I want it to append the date time stamp in target file name. In this post we will see how to pepare date time stamp as string variable in batch file. Here is the script.


::----------------------------------------------------------------------------------------------
::prepare date-string
::----------------------------------------------------------------------------------------------

:: Get day from current date, in variable name 'day'
SET day=%date:~7,2%

:: Get month from current date, in variable name 'month'
SET month=%date:~4,2%

:: Get year from current date, in variable name 'year'
SET year=%date:~10,4%

:: Set year+month+date for date-string, in variable name 'myDateFormat' 
SET myDateFormat=%day%-%month%-%year%

:: Trim myDateFormat to remove white spaces
SET myDateFormat=%myDateFormat: =%

::----------------------------------------------------------------------------------------------
::prepare time-string
::----------------------------------------------------------------------------------------------

:: Get hour from current time, in variable name 'hour'
SET hour=%time:~0,2%

:: Get minute from current time, in variable name 'minute'
SET minute=%time:~3,2%

:: Get second from current time, in variable name 'sec'
SET sec=%time:~6,2% 

:: Set hour+minute+second for time-string, in variable name 'myTimeFormat'
SET myTimeFormat=%hour%-%minute%-%sec%

:: Trim myTimeFormat to remove white spaces
SET myTimeFormat=%myTimeFormat: =%

::----------------------------------------------------------------------------------------------
::set targetFileName with string literal, and also append the date and time strings at the end.
::----------------------------------------------------------------------------------------------

SET targetFileName=CRM System Log-%myDateFormat%-%myTimeFormat%.txt

::copy file, using the variable targetFileName 
copy "C:\Test\CRM System Log.txt" "C:\Test\Destination\%targetFileName%"

I hope this helps some of you who get stuck with a similar problem.

January 17, 2018

How to validate only numbers in string variable in C#?

There are multiple ways to validate user input string in order to allow only numbers. Lets say we have a string in variable myInput, following are some tips you can use to check if the input string is only contains numbers.

Check for numbers while entering data

If you are using Winforms and want to validate user input, then you can use TextBox's KeyPress event.

private void txtNumber_KeyPress(object sender, KeyPressEventArgs e)
{
  if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
  {
    e.Handled = true;
  }
}

You can set e.Handled property to true if the character entered is not the desired one, it will suppress that key. You can use similar technique in JavaScript if you are working with ASP.NET.

Check for numbers if you have a string variable

In many cases, if you are not using Winforms application or you may need to inspect the string variable other than the KeyPress event, then you can use one of following methods.

If the string variable contains a value within valid integer range, then you can use int.TryParse() function to check if it has valid integer value.

private bool ValidateNumber(string myInput)
{
    int val;
    if (int.TryParse(myInput, out val))
    {
       return true;
    }
    else
    {
        return false;
    }
}

Note: This method has limitation that the input is being checked only for valid integers, which can have a maximum value of 2,147,483,647. For example, if you need to verify a string of 15 digits, then this method may not give you the desired result.

In order to validate a string with numbers having more digits, we can use the following options:

Char.IsDigit can be used to check if the character at any specified position in string is a digit, and here we are using Linq function All to our string, which will call Char.IsDigit function for each character in the string, and hence can get the required output.

 myInput.All(Char.IsDigit)

A more formal method can be used, i.e. Regular Expressions, which can give you more control in different scenarios. Here we are using Regular Expression "^[0-9]*$" to match for numbers in input string.

 System.Text.RegularExpressions.Regex.IsMatch(myInput, "^[0-9]*$")

I hope you find this post helpful, I welcome your comments or suggestions if you may find any more alternative(s) to validate numeric figures in a string.

November 26, 2017

C# Winforms - Localized translations using ResourceManager

In this post I will explain how to implement localization in Windows Forms Application using ResourceManager class. We will see an example application with Login form, and change the strings/labels with two different locales (in this example I am using English and Arabic locales). So lets start with this sample Login form.

We want to see the form display with English locale similar to the following screenshot

winforms english translations

And with Arabic locale, the form should display similar to this screenshot

winforms arabic translations

First we have to create separate resource files for separate locales (English and Arabic in this example)

Here is the resource file for English locale Messages.en.resx.

resource english strings

And here is the resource file for Arabic locale Messages.ar.resx.

resource arabic strings

Note that the resource file names are ended with .en and .ar and then the actual file extension .resx. Similarly if you want to create resource files for any other language, you have to create separate resource file with correct file name ending with .[locale-name]

In this example I have placed these two resources files in MyResources folder, solution explorer seems like this:

solution explorer resources

We have written the labels translations in resource files. Its time to write real C# code to use these resource files and display the target translated labels on corresponding controls. For this we are using ResourceManager class found in namespace System.Resources.

Lets create a function which accepts the lang argument, and set labels/controls texts with corresponding string translations from resource files by passing the target CultureInfo argument. To get the desired translated string, we are using helper method rm.GetString().

 private void ChangeLang(string lang)
 {
  CultureInfo ci = new CultureInfo(lang);

  System.Resources.ResourceManager rm = new System.Resources.ResourceManager("WindowsFormsApplication1.MyResources.Messages", typeof(Form1).Assembly);
  lblUserName.Text = rm.GetString("UserName", ci);
  lblPassword.Text = rm.GetString("Password", ci);
  btnLogin.Text = rm.GetString("Login", ci);
  rbEnglish.Text = rm.GetString("English", ci);
  rbArabic.Text = rm.GetString("Arabic", ci);
  this.Text = rm.GetString("Authentication", ci);
 }

Note that ResourceManager constructor accepts argument as the complete assembly name, folder, and resource file name concatenating with dots ("WindowsFormsApplication1.MyResources.Messages" in this case).

Now run the application and you should be able to see the login form displaying the strings/translations based on selected locales.

I hope you have found this article helpful, I welcome your comments and suggestions to analyze this technique, and find if there is any better alternative for implementing localization.