Utility Methods

Object Comparison

 
      public static bool DeepEquals(object a, object b) {
            if (a != null && b != null)
            {
                Type type = a.GetType();
                if (ReferenceEquals(a, b))
                    return true;
                if (type == typeof(string) || type == typeof(int) /* || ... */)
                    return Equals(a, b);
                BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy;
                foreach (FieldInfo field in type.GetFields(flags)) {
                    if (!DeepEquals(field.GetValue(a), field.GetValue(b)))
                        return false;
                }
                return true;
            }
            return false;
        }

String Decode

        /// <summary>
        /// converts  into their character code equivalents
        /// </summary>
        /// <param name="inputValue">string to decode</param>
        /// <returns>returns a string with basic decoding</returns>
        public static string StringDecode(string inputValue)
        {
            inputValue = HttpUtility.UrlDecode(inputValue);
            inputValue = inputValue.Replace("<", "&lt;");
            inputValue = inputValue.Replace(">", "&gt;");
            return inputValue;
        }

String Encode

        /// <summary>
        /// converts &lt; &gt; into their character equivalents
        /// </summary>
        /// <param name="inputValue">string to encode</param>
        /// <returns>returns a string with basic encoding</returns>
        public static string StringEncode(string inputValue) 
        {
            inputValue = inputValue.Replace("&lt;", "<");
            inputValue = inputValue.Replace("&gt;", ">");
            return HttpUtility.UrlEncode(inputValue);
        }

String Decode From Base64

        /// <summary>
        /// Decodes a base 64 string
        /// </summary>
        /// <param name="encodedData">string to decode</param>
        /// <returns>decoded string</returns>
        public static string DecodeFrom64(string encodedData) 
        {
            byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
            string returnValue = System.Text.Encoding.UTF8.GetString(encodedDataAsBytes);
            return returnValue;
        }

String Encode to Base64

        /// <summary>
        /// Encodes a base 64 string
        /// </summary>
        /// <param name="toEncode">string to encode</param>
        /// <returns>encoded string</returns>
        public static string EncodeTo64(string toEncode) 
        {
            byte[] toEncodeAsBytes = System.Text.Encoding.UTF8.GetBytes(toEncode);
            string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
            return returnValue;
        }

Get Average

        public static TimeSpan AverageThis(this Action p, int numberOfTimesToRun)
        {
            var spans = new TimeSpan[numberOfTimesToRun];
            for (int i = 0; i < numberOfTimesToRun; i++)
            {
                spans[i] = TimeThis(p).Elapsed;
            }

            double vAverage = (from timeSpan in spans
                                select timeSpan).Average(pSpan => pSpan.TotalSeconds);
            return TimeSpan.FromSeconds(vAverage);
        }

        public static Stopwatch TimeThis(this Action p)
        {
            Stopwatch vStopWatch = Stopwatch.StartNew();
            p();
            vStopWatch.Stop();
            return vStopWatch;
        }

File Permissions Check

    public static bool CheckAccess(WindowsIdentity user, string path, FileSystemRights expectedRights)
        {
            AuthorizationRuleCollection acl = null;

            if (Directory.Exists(path))
            {
                DirectoryInfo di = new DirectoryInfo(path);
                acl = di.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));
            }
            else
            {
                if (File.Exists(path))
                {
                    FileInfo fi = new FileInfo(path);
                    acl = fi.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));
                }
                else
                {
                    try
                    {
                        FileSystemRights fileRights = FileSystemRights.CreateFiles | FileSystemRights.Write;
                        FileSystemAccessRule accessRules = new FileSystemAccessRule(WindowsIdentity.GetCurrent().User, fileRights, AccessControlType.Allow);
                        FileSecurity fileSecurity = new FileSecurity();
                        fileSecurity.SetAccessRule(accessRules);
                        File.Create(path, 1, FileOptions.SequentialScan, fileSecurity);
                    }
                    catch { return false; }
                }
            }
            return CheckAccessRights(user, acl, expectedRights);
        }

        private static bool CheckAccessRights(WindowsIdentity user, AuthorizationRuleCollection acl, FileSystemRights expectedRights)
        {
            if (acl != null)
            {
                // gets rules that concern the user and his groups
                IEnumerable<AuthorizationRule> userRules = from AuthorizationRule rule in acl
                                                           where user.User.Equals(rule.IdentityReference)
                                                           || user.Groups.Contains(rule.IdentityReference)
                                                           select rule;

                FileSystemRights denyRights = 0;
                FileSystemRights allowRights = 0;

                // iterates on rules to compute denyRights and allowRights
                foreach (FileSystemAccessRule rule in userRules)
                {
                    if (rule.AccessControlType.Equals(AccessControlType.Deny))
                    {
                        denyRights = denyRights | rule.FileSystemRights;
                    }
                    else if (rule.AccessControlType.Equals(AccessControlType.Allow))
                    {
                        allowRights = allowRights | rule.FileSystemRights;
                    }
                }

                // allowRights = allowRights - denyRights
                allowRights = allowRights & ~denyRights;

                // are rights sufficient?
                return (allowRights & expectedRights) == expectedRights;
            }
            return false;
        }

Input Defaults

public T Defaults<T>(object input, T defaultValue)
{
    try
    {
        if (input != null)
        {
            return (T)Convert.ChangeType(input, typeof(T));
        }
        else
        {
            return defaultValue;
        }
    }
    catch {
        return default(T);
    }
}

Steam To Byte Array


public static byte[] ReadToEnd(System.IO.Stream stream) {
    long originalPosition = stream.Position;
    stream.Position = 0;

    try {
        byte[] readBuffer = new byte[4096];

        int totalBytesRead = 0;
        int bytesRead;

        while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0) {
            totalBytesRead += bytesRead;

            if (totalBytesRead == readBuffer.Length) {
                int nextByte = stream.ReadByte();
                if (nextByte != -1) {
                    byte[] temp = new byte[readBuffer.Length * 2];
                    Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                    Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                    readBuffer = temp;
                    totalBytesRead++;
                }
            }
        }

        byte[] buffer = readBuffer;
        if (readBuffer.Length != totalBytesRead) {
            buffer = new byte[totalBytesRead];
            Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
        }
        return buffer;
    } finally {
        stream.Position = originalPosition;
    }
}

Basic String Encryption

private static string EncryptString(string inputString, int dwKeySize, string xmlString) {
            RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider(dwKeySize);
            rsaCryptoServiceProvider.FromXmlString(xmlString);
            int keySize = dwKeySize / 8;
            byte[] bytes = Encoding.UTF32.GetBytes(inputString);

            int maxLength = keySize - 42;
            int dataLength = bytes.Length;
            int iterations = dataLength / maxLength;
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i <= iterations; i++) {
                byte[] tempBytes = new byte[(dataLength - maxLength * i > maxLength) ? maxLength : dataLength - maxLength * i];
                Buffer.BlockCopy(bytes, maxLength * i, tempBytes, 0, tempBytes.Length);
                byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt(tempBytes,true);
                Array.Reverse(encryptedBytes);
                stringBuilder.Append(Convert.ToBase64String(encryptedBytes));
            }
            return stringBuilder.ToString();
        }

        private static string DecryptString(string inputString, int dwKeySize,string xmlString) {

            RSACryptoServiceProvider rsaCryptoServiceProvider= new RSACryptoServiceProvider(dwKeySize);
            rsaCryptoServiceProvider.FromXmlString(xmlString);
            int base64BlockSize = ((dwKeySize / 8 ) % 3 != 0) ? (((dwKeySize / 8 ) / 3 ) * 4 ) + 4 : ((dwKeySize / 8 ) / 3) * 4;
            int iterations = inputString.Length / base64BlockSize;
            ArrayList arrayList = new ArrayList();
            for (int i = 0; i < iterations; i++) {
                byte[] encryptedBytes = Convert.FromBase64String(inputString.Substring(base64BlockSize * i, base64BlockSize));
                Array.Reverse(encryptedBytes);
                arrayList.AddRange(rsaCryptoServiceProvider.Decrypt(encryptedBytes, true));
            }
            return Encoding.UTF32.GetString(arrayList.ToArray(Type.GetType("System.Byte")) as byte[]);
        }
        /// <summary>
        /// Generates a Crypto Key (in Xml format)
        /// </summary>
        /// <param name="ContainerName"></param>
        /// <param name="KeyLength">Default Key Length is 1024</param>
        /// <param name="outputFile">file path to the output file + the filename </param>
        public static XmlDocument GenerateCryptoKeyFile(string ContainerName, int KeyLength = 1024, string outputFile = null, CspParameters parameters = null){
            CspParameters cp = null;
            if (parameters != null) {
                cp = parameters;
            } else {
                 cp = new CspParameters();
            }

            cp.KeyContainerName = ContainerName;
            cp.Flags = CspProviderFlags.UseMachineKeyStore;
            cp.KeyNumber = 1;

            //Build the full file path thats been specified.
            if (!string.IsNullOrEmpty(outputFile)) {
                IO.BuildPath(Path.GetFullPath(outputFile));
            }

            XmlDocument rsaXml = null;
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(KeyLength, cp))
            {
                if (!string.IsNullOrEmpty(outputFile)) {
                    using (FileStream fs = new FileStream(outputFile, FileMode.Create)) {
                        using (StreamWriter sw = new StreamWriter(fs)) {
                            sw.WriteLine(rsa.ToXmlString(true));
                        }
                    }
                }else{
                   rsaXml = new XmlDocument();
rsaXml.LoadXml(rsa.ToXmlString(true));
                }
            }
            return rsaXml;
}

4 Comments

  1. Consequently, after investing much time on the internet
    at past We’ve found anyone that definitely does know very well what they’re speaking about thank
    you very much fantastic article.

    Feel free to surf to my blog … plumbers Aberdeen (Daniel)

Leave a Reply

Your email address will not be published.





7 × = thirty five