Esempio n. 1
0
        /// <summary>
        /// Encodes the data given into a dictionary containing tags into standard format(JSON)
        /// </summary>
        /// <param name="tagDict"> Dictionary containing Tags to be encoded</param>
        /// <returns> Encoded data in string format</returns>
        public string Encode(Dictionary <string, string> tagDict)
        {
            if (tagDict == null)
            {
                MastiDiagnostics.LogError(string.Format(CultureInfo.CurrentCulture, "Data given to encode is empty"));
                throw new ArgumentNullException(nameof(tagDict));
            }

            Dictionary <string, string> .KeyCollection keys = tagDict.Keys;
            string encodedData = string.Empty;

            MastiDiagnostics.LogInfo(string.Format(CultureInfo.CurrentCulture, "Encoding started"));

            // inserting the Type tag into encoding data
            encodedData = EncodeTo64("type") + ':' + EncodeTo64("ImageProcessing") + ';';
            foreach (string key in keys)
            {
                encodedData += EncodeTo64(key) + ':' + EncodeTo64(tagDict[key]) + ";";
            }

            MastiDiagnostics.LogInfo("Hash is calculated and appended for sanity check in future");

            // calculating hash of encoded data and append hash of it at the end of encoded data
            encodedData = encodedData + "Hash:" + ComputeSha256Hash(encodedData);
            MastiDiagnostics.LogSuccess(string.Format(CultureInfo.CurrentCulture, "Data encoded successfully"));
            return(encodedData);
        }
Esempio n. 2
0
        /// <summary>
        /// Encodes data obtained from a dictionary to a string
        /// </summary>
        /// <param name="tagDict">Dictionary containing tag to be encoded</param>
        /// <returns>Encoded string of data from dictionary</returns>
        public string Encode(Dictionary <string, string> tagDict)
        {
            if (tagDict == null)
            {
                MastiDiagnostics.LogError(string.Format(CultureInfo.CurrentCulture, "Null is not accepted to encode"));
                throw new ArgumentNullException(nameof(tagDict));
            }

            Dictionary <string, string> .KeyCollection keys = tagDict.Keys;
            string result = string.Empty;

            MastiDiagnostics.LogInfo(string.Format(CultureInfo.CurrentCulture, "Encoding started"));

            // inserting the Type tag into encoding data
            result = EncodeTo64("type") + ':' + EncodeTo64("Messaging") + ';';
            foreach (string key in keys)
            {
                result += EncodeTo64(key) + ':' + EncodeTo64(tagDict[key]) + ";";
            }

            // calculating hash of encoded data and append hash of it at the end of encoded data
            result = result + "Hash:" + ComputeSha256Hash(result);
            MastiDiagnostics.LogInfo("Hash calculation successful. Appended to data for sanity check.");
            return(result);
        }
Esempio n. 3
0
        /// <summary>
        /// Function where execution starts.
        /// </summary>
        /// <param name="args">Command line arguments if any.</param>
        public static void Main(string[] args)
        {
            // Get ready to sell some fruits.
            Fruit fruit = new Fruit();

            // Sell some fruits.
            try
            {
                Console.WriteLine("How many fruits do you want to sell?");
                var soldQuantity = int.Parse(Console.ReadLine());
                fruit.SellFruit(soldQuantity);
                MastiDiagnostics.LogSuccess(string.Format(CultureInfo.CurrentCulture, "Sold {0} fruits.", soldQuantity));
            }
            catch (Exception e)
            {
                // For exceptions that you can handle, use LogWarning.
                // For exceptions that you cannot handle, use LogError.
                // Use LogSuccess to log successful execution of operations.
                // Use LogInfo to record other information.
                // What logs need to be committed depends on the settings in
                // QualityAssurance.Properties.Settings
                // This ensures that log is always committed to file.
                MastiDiagnostics.LogError(string.Format(CultureInfo.CurrentCulture, "Failed to sell. {0}", e.Message));
                Console.WriteLine("Failed to sell fruits!!");
            }

            // Sell some more fruits.
            try
            {
                Console.WriteLine("How many fruits do you want to sell now?");
                var soldQuantity = int.Parse(Console.ReadLine());
                fruit.SellFruit(soldQuantity);
                MastiDiagnostics.LogSuccess(string.Format(CultureInfo.CurrentCulture, "Sold {0} fruits.", soldQuantity));
            }
            catch (Exception e)
            {
                MastiDiagnostics.LogError(string.Format(CultureInfo.CurrentCulture, "Failed to sell. {0}", e.Message));
                Console.WriteLine("Failed to sell fruits!!");
            }

            // This method commits logs to file.
            // You are not required to use this explicitly anywhere.
            MastiDiagnostics.WriteLog();

            // That's enough. Now commit telemetry info.
            // Info stored by all modules get committed.
            // This needs to be called by module which handles Masti's exit (UI).
            // Others needn't.
            TelemetryCollector.Instance.StoreTelemetry();

            MastiDiagnostics.LogInfo("Closing shop. Go elsewhere.");

            // To illustrate mailing facility, let's mail the logs to the specified developer.
            // Mailing details can also be changed in the settings file under QualityAssurance.Properties.
            MastiDiagnostics.MailLog();
        }
Esempio n. 4
0
        /// <summary>
        /// Decodes the string and returns as key-value pair in a dictionary
        /// </summary>
        /// <param name="data">Encoded data in string format</param>
        /// <param name="partialDecoding">> Boolean if true just returns type of data (ImageProcessing or Messaging)</param>
        /// <returns> Dictionary containing key-value pairs of the encoded data</returns>
        public IDictionary <string, string> Decode(string data, bool partialDecoding)
        {
            if (data == null)
            {
                MastiDiagnostics.LogError(string.Format(CultureInfo.CurrentCulture, "Null data given to decode"));
                throw new ArgumentNullException(nameof(data));
            }

            Dictionary <string, string> tagDict = new Dictionary <string, string>();

            MastiDiagnostics.LogInfo(string.Format(CultureInfo.CurrentCulture, "Starting data decoding"));

            // extracting hash for the given data
            string[] keyValues         = data.Split(';');
            int      numberOfKeyValues = keyValues.Length;
            string   hashOfEncodedData = keyValues[numberOfKeyValues - 1];

            // collecting all string array without hash
            string encodedDataWithoutHash = string.Empty;

            for (int index = 0; index < numberOfKeyValues - 1; index++)
            {
                encodedDataWithoutHash += keyValues[index] + ";";
            }

            MastiDiagnostics.LogInfo(string.Format(CultureInfo.CurrentCulture, "Checking the validity of data (sanity check)"));
            if ("Hash:" + ComputeSha256Hash(encodedDataWithoutHash) != hashOfEncodedData)
            {
                MastiDiagnostics.LogError("Data given is corrupted");
                throw new ArgumentException("Corrupted data");
            }

            MastiDiagnostics.LogInfo(string.Format(CultureInfo.CurrentCulture, "Sanity check passed"));

            // for partial decoding returning the dictionary only containing type of data (ImageProcessing/Messaging)
            if (partialDecoding == true)
            {
                MastiDiagnostics.LogInfo(string.Format(CultureInfo.CurrentCulture, "Partial decoding started"));
                string[] type = keyValues[0].Split(':');

                // type is the first tag inserted into data while encoding.
                if (DecodeFrom64(type[0]) == "type")
                {
                    tagDict.Add(DecodeFrom64(type[0]), DecodeFrom64(type[1]));
                }
                else
                {
                    MastiDiagnostics.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid data given to decode which does not contain type"));
                    throw new System.ArgumentException("Data is corrupted as it does not contain the type(tag) of data", nameof(data));
                }

                MastiDiagnostics.LogSuccess(string.Format(CultureInfo.CurrentCulture, "Decoded Successfully"));
                return(tagDict);
            }

            // fully decoding if the partialDecoding is false and adding into the dictionary
            foreach (string keyValue in keyValues)
            {
                tagDict.Add(DecodeFrom64(keyValue.Split(':')[0]), DecodeFrom64(keyValue.Split(':')[1]));
            }

            tagDict.Remove("type");
            MastiDiagnostics.LogInfo(string.Format(CultureInfo.CurrentCulture, "Data decoded successfully"));
            return(tagDict);
        }
Esempio n. 5
0
        /// <summary>
        /// Function used to parse string data to convert into JSON format
        /// </summary>
        /// <param name="data">Encoded string</param>
        /// <param name="partialDecoding">Flag used to partially decode data to get object type (ImageProcessing/Messaging)</param>
        /// <returns>Dictionary of tags of encoded data</returns>
        public IDictionary <string, string> Decode(string data, bool partialDecoding)
        {
            Dictionary <string, string> tagDict = new Dictionary <string, string>();

            if (data == null)
            {
                MastiDiagnostics.LogError(string.Format(CultureInfo.CurrentCulture, "Null data cannot be decoded."));
                throw new ArgumentNullException(nameof(data));
            }

            MastiDiagnostics.LogInfo(string.Format(CultureInfo.CurrentCulture, "Decoding started."));
            string[] keyValues         = data.Split(';');
            int      numberOfKeyValues = keyValues.Length;
            string   hashOfEncodedData = keyValues[numberOfKeyValues - 1];

            // collecting all string array without hash
            string encodedDataWithoutHash = string.Empty;

            for (int index = 0; index < numberOfKeyValues - 1; index++)
            {
                encodedDataWithoutHash += keyValues[index] + ";";
            }

            MastiDiagnostics.LogInfo(string.Format(CultureInfo.CurrentCulture, "Performing sanity check by comparing hash."));
            if ("Hash:" + ComputeSha256Hash(encodedDataWithoutHash) != hashOfEncodedData)
            {
                MastiDiagnostics.LogError("Data sent and received do not match.");
                throw new ArgumentException("Corrupted data");
            }

            MastiDiagnostics.LogInfo(string.Format(CultureInfo.CurrentCulture, "Sanity check successful."));

            // for partial decoding returning the dictionary only containing type of data give (Image/Message/Other)
            if (partialDecoding == true)
            {
                MastiDiagnostics.LogInfo(string.Format(CultureInfo.CurrentCulture, "Partial decoding started"));
                string[] type = keyValues[0].Split(':');

                // Obtaining type of tag (Image/Message/Other)
                if (DecodeFrom64(type[0]) == "type")
                {
                    tagDict.Add(DecodeFrom64(type[0]), DecodeFrom64(type[1]));
                }
                else
                {
                    MastiDiagnostics.LogError(string.Format(CultureInfo.CurrentCulture, "Type tag not found. Partial decoding failed."));
                    throw new System.ArgumentException("Data has no type tag. Partial decoding failed.", nameof(data));
                }

                MastiDiagnostics.LogSuccess(string.Format(CultureInfo.CurrentCulture, "Partial decoding successful"));
                return(tagDict);
            }

            // Complete decoding of the message and returning the dictionary
            foreach (string keyValue in keyValues)
            {
                tagDict.Add(DecodeFrom64(keyValue.Split(':')[0]), DecodeFrom64(keyValue.Split(':')[1]));
            }

            tagDict.Remove("type");
            MastiDiagnostics.LogInfo(string.Format(CultureInfo.CurrentCulture, "Data decoding successful"));
            return(tagDict);
        }