Thursday 18 December 2014

C# code to system restore from code behind

private void CreateRestorePoint(string description)
{
    ManagementScope oScope = new ManagementScope("\\\\localhost\\root\\default");
    ManagementPath oPath = new ManagementPath("SystemRestore");
    ObjectGetOptions oGetOp = new ObjectGetOptions();
    ManagementClass oProcess = new ManagementClass(oScope, oPath, oGetOp);

    ManagementBaseObject oInParams =
         oProcess.GetMethodParameters("CreateRestorePoint");
    oInParams["Description"] = description;
    oInParams["RestorePointType"] = 12; // MODIFY_SETTINGS
    oInParams["EventType"] = 100;

    ManagementBaseObject oOutParams =
         oProcess.InvokeMethod("CreateRestorePoint", oInParams, null);
}

Note: Add reference of system.managment

C# Concat (Merge list)

  Merged_All_Lists = Merged_All_Lists.Concat(list1).ToList();

C# Install software (.MSI) silently (Hiddenly)

        
        private Process mv_prcInstaller = new Process();    
        
        private void installSoftware(object sender, EventArgs e)
        {
            if (txtPath.Text.Length < 1)
            {
                MessageBox.Show("Please select a .msi file");
            }

            //Sentence to install -> /i
            manipulateSoftware("/i");
        }

        private void uninstallSoftware(object sender, EventArgs e)
        {
            if (txtPath.Text.Length < 1)
            {
                MessageBox.Show("Please select a .msi file");
            }

            //Sentence to uninstall -> /x
            manipulateSoftware("/x");
        }

        private void manipulateSoftware(string p_strAccion)
        {
            //The Argument will be like this
            mv_prcInstaller.StartInfo.FileName = "msiexec.exe";
            mv_prcInstaller.StartInfo.Arguments = p_strAccion + "\"" + txtPath.Text + "\"" +"/qn";
            mv_prcInstaller.Start();
        }

C# Get current date and time from internet

public static DateTime GetFastestNISTDate()
        {
            var result = DateTime.MinValue;

            // Initialize the list of NIST time servers
            string[] servers = new string[] {
        "nist1-ny.ustiming.org",
        "nist1-nj.ustiming.org",
        "nist1-pa.ustiming.org",
        "time-a.nist.gov",
        "time-b.nist.gov",
        "nist1-chi.ustiming.org",
        "nist.expertsmi.com",
};

            // Try 5 servers in random order to spread the load
            Random rnd = new Random();
            foreach (string server in servers.OrderBy(s => rnd.NextDouble()).Take(5))
            {
                try
                {
                    // Connect to the server (at port 13) and get the response
                    string serverResponse = string.Empty;
                    using (var reader = new StreamReader(new System.Net.Sockets.TcpClient(server, 13).GetStream()))
                    {
                        serverResponse = reader.ReadToEnd();
                    }

                    // If a response was received
                    if (!string.IsNullOrEmpty(serverResponse))
                    {
                        // Split the response string ("55596 11-02-14 13:54:11 00 0 0 478.1 UTC(NIST) *")
                        string[] tokens = serverResponse.Split(' ');

                        // Check the number of tokens
                        if (tokens.Length >= 6)
                        {
                            // Check the health status
                            string health = tokens[5];
                            if (health == "0")
                            {
                                // Get date and time parts from the server response
                                string[] dateParts = tokens[1].Split('-');
                                string[] timeParts = tokens[2].Split(':');

                                // Create a DateTime instance
                                DateTime utcDateTime = new DateTime(
                                    Convert.ToInt32(dateParts[0]) + 2000,
                                    Convert.ToInt32(dateParts[1]), Convert.ToInt32(dateParts[2]),
                                    Convert.ToInt32(timeParts[0]), Convert.ToInt32(timeParts[1]),
                                    Convert.ToInt32(timeParts[2]));

                                // Convert received (UTC) DateTime value to the local timezone
                                result = utcDateTime.ToLocalTime();

                                return result;
                                // Response successfully received; exit the loop

                            }
                        }

                    }

                }
                catch
                {
                    // Ignore exception and try the next server
                }
            }
            return result;
        }

C# get last time of file accessed

​File.GetLastAccessTime(path);

Note: NtfsDisableLastAccessUpdate must be enable in regedit
HKLM\SYSTEM\CurrentControlSet\Control\FileSystem

C# Password protected encryption and decryption

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace EncryptStringSample
{
    public static class StringCipher
    {
        // This constant string is used as a "salt" value for the PasswordDeriveBytes function calls.
        // 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 static readonly byte[] initVectorBytes = Encoding.ASCII.GetBytes("tu89geji340t89u2");

        // This constant is used to determine the keysize of the encryption algorithm.
        private const int keysize = 256;

        public static string Encrypt(string plainText, string passPhrase)
        {
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
            {
                byte[] keyBytes = password.GetBytes(keysize / 8);
                using (RijndaelManaged symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.Mode = CipherMode.CBC;
                    using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes))
                    {
                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                                cryptoStream.FlushFinalBlock();
                                byte[] cipherTextBytes = memoryStream.ToArray();
                                return Convert.ToBase64String(cipherTextBytes);
                            }
                        }
                    }
                }
            }
        }

        public static string Decrypt(string cipherText, string passPhrase)
        {
            byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
            using(PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
            {
                byte[] keyBytes = password.GetBytes(keysize / 8);
                using(RijndaelManaged symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.Mode = CipherMode.CBC;
                    using(ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
                    {
                        using(MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                        {
                            using(CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                            {
                                byte[] plainTextBytes = new byte[cipherTextBytes.Length];
                                int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                            }
                        }
                    }
                }
            }
        }
    }
}

C# : Get Domain Name from url without www.

string myLocalLink  = "https://www.mail.google.com/mail/u/1/#inbox";

  myLocalLink = (new Uri(myLocalLink)).Host;

                        if (myLocalLink.ToString().StartsWith("www."))
                        {
                            myLocalLink = myLocalLink.ToString().Substring(4, myLocalLink.ToString().Length - 4);
                        }
                       


result: mail.google.com