Oct 31, 2015

Change Creation Date of file to Modified Date using PowerShell

Use the following PowerShell command to change the Creation Date to the Modified Date of all files in a folder.

Get-ChildItem -recurse -filter *.JPG | % { $_.CreationTime = $_.LastWriteTime }

Oct 8, 2015

Rename all files replacing a text using PowerShell

Let's say you have a number of files at location C:\demo with text "OldValue" in it. And you want to replace text "OldValue" to "NewValue" in all files. To do that follow the steps below:

  1. Open Windows PowerShell.
  2. Navigate to location C:\demo
  3. Run the following Windows PowerShell command: 
    Get-ChildItem -Filter "*OldValue*" -Recurse | Rename-Item -NewName {$_.name -replace 'OldValue','NewValue' }
  4. All files will be renamed.

  • The command Get-ChildItem -Filter "*OldValue*" finds all files with the string "OldValue" anywhere in the name.
  • Get-ChildItem searches recursively through all subfolders.
  • | (the pipe character) instructs Windows PowerShell to take each item (object) found with the first command (Get-ChildItem) and pass it to the second command (Rename-Item)
  • Rename-Item renames files and other objects.
  • {$_.name -replace 'OldValue','NewValue' } instructs Rename-Item to find the string "OldValue" in the file name and replace it with "NewValue"

Sep 17, 2015

Printing all properties of an Object

To write all the properties and such of an object to the console (or log or to front end), use TypeDescriptor class.

foreach(System.ComponentModel.PropertyDescriptor descriptor in System.ComponentModel.TypeDescriptor.GetProperties(obj))
{
    string name=descriptor.Name;
    object value=descriptor.GetValue(obj);
    Console.WriteLine("{0}={1}",name,value);
}

Where obj is the class for which properties are to be printed.

Sep 15, 2015

Creating a custom class in C# for creating a log file

Code for the class to create log file:

Local SMTP server for Testing and Development on Windows

Use Papercut.

Download the application and run it. It will set up an SMTP server when it's running. Configure your application to use 'localhost' (or the machine where the server is running) as the SMTP server. If you need to use a non-default port number, you can configure it in Options.

As per the CodePlex webpage:
Papercut is a simplified SMTP server designed to only receive messages (not to send them on) with a GUI on top of it allowing you to see the messages it receives. It doesn't enforce any restrictions on addresses, it just takes the message and allows you see it. It is only active while it is running, and if you want it in the background, just minimize it to the system tray. When it receives a new message, a balloon message will show up to let you know.

May 28, 2015

Changing phpMyAdmin root password

To change the root password in phpMyAdmin follow these steps:


  1. Log in to the database directly using command:
    mysql -h <your_hostname> -u root
  2. Run the following SQL command:
    UPDATE mysql.user SET Password=PASSWORD('Your new Password') WHERE User='root';
  3. Open the following file:
    <XAMPP_INSTALLATION_FODLER>\phpMyAdmin\config.inc.php
  4. Change the following values:
    $cfg['Servers'][$i]['auth_type'] = 'config';
    to
    $cfg['Servers'][$i]['auth_type'] = 'cookie';
    and
    $cfg['Servers'][$i]['password'] = '';
    to
    $cfg['Servers'][$i]['password'] = 'new_password';

May 21, 2015

Easy Encrypt and Decrypt functionality for ASP.Net text fields

Some times you want to store some data into hidden fields and want to ensure that data is unreadable to humans but is only used by server side variables.

The easiest way it to utilize the RSACryptoServiceProvider class in System.Security.Cryptography.


Utilize the class shown below:


using System.Security.Cryptography;

namespace SampleNamespace
{
    public class EncryptDecrypt
    {
        static RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(2048);


        public EncryptDecrypt()
        {

        }


        public static string Encrypt(string text)
        {
            return Convert.ToBase64String(rsaProvider.Encrypt(System.Text.Encoding.UTF8.GetBytes(text), true));
        }

        public static string Decrypt(string text)
        {
            return System.Text.Encoding.UTF8.GetString(rsaProvider.Decrypt(Convert.FromBase64String(text), true));
        }
    }
}

Please note that this works only for smaller strings. You may get an error: Bad Length for longer strings. For longer string we need to use hybrid encryption alogrithm.

To encrypt longer string use the code below:

using System.Security.Cryptography;

namespace SampleNamespace
{
    /// This size of the IV (in bytes) must = (keysize / 8).  Default keysize is 256, so the IV must be
    /// 32 bytes long.  Using a 16 character string here gives us 32 bytes when converted to a byte array.
    private const string initVector = "E5IaHPeVT3Mvt5Lk";
    /// This constant is used to determine the keysize of the encryption algorithm
    private const int keysize = 256;
    /// Passpharase to be used for encryption and decryption
    private const string passPhrase = "QjM2vWxgat";

    /// <summary>
    /// Encrypts provided String
    /// </summary>
    /// <param name="plainText">Text to be encrypted</param>
    /// <returns>Encrypted String</returns>
    public static string EncryptString(string plainText)
    {
        byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
        byte[] keyBytes = password.GetBytes(keysize / 8);
        RijndaelManaged symmetricKey = new RijndaelManaged();
        symmetricKey.Mode = CipherMode.CBC;
        ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
        cryptoStream.FlushFinalBlock();
        byte[] cipherTextBytes = memoryStream.ToArray();
        memoryStream.Close();
        cryptoStream.Close();
        return Convert.ToBase64String(cipherTextBytes);
    }

    /// <summary>
    /// Decrypts provided String
    /// </summary>
    /// <param name="cipherText">Text to be decrypted</param>
    /// <returns>Decrypted String</returns>
    public static string DecryptString(string cipherText)
    {
        byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
        byte[] keyBytes = password.GetBytes(keysize / 8);
        RijndaelManaged symmetricKey = new RijndaelManaged();
        symmetricKey.Mode = CipherMode.CBC;
        ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
        MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
        CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
        byte[] plainTextBytes = new byte[cipherTextBytes.Length];
        int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
        memoryStream.Close();
        cryptoStream.Close();
        return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
    }
}