Example #1
0
        public static Dictionary<string, string> ParseCommandLine(string[] args)
        {
            var arguments = new Dictionary<string, string>();

              // App.Config Settings
              var appSettingKeys = ConfigurationManager.AppSettings.Keys;
              for (var i = 0; i < appSettingKeys.Count; i++)
              {
              var key = appSettingKeys[i];
              arguments.AddOrUpdate(key, ConfigurationManager.AppSettings[key]);
              }

              // Manual override through CLI.
              var p = new OptionSet()
                    {
                       {
                          "<>", v =>
                                   {
                                      if (!v.StartsWith("--"))
                                         return;
                                      var split = v.Split(new[] { '=' }, 2);
                                      if (split.Length != 2)
                                         return;
                                      arguments.AddOrUpdate(split[0].TrimStart('-'), split[1]);
                                   }
                          }
                    };

              p.Parse(args);
              return arguments;
        }
        public void AddOrUpdateOverloadOne()
        {
            var dictionary = new Dictionary<string, string>();
            Func<string, string, string> updater = (key, oldValue) =>
            {
                key.Should().Be("fookey");
                oldValue.Should().Be("foo");
                return "bar";
            };

            Func<string, string, string> nullUpdater = null;

            dictionary.AddOrUpdate(key: "fookey", addValue: "foo", updateValueFactory: updater).Should().Be("foo");
            dictionary["fookey"].Should().Be("foo");
            dictionary.AddOrUpdate(key: "fookey", addValue: "foo", updateValueFactory: updater).Should().Be("bar");
            dictionary["fookey"].Should().Be("bar");

            // Null argument checks
            Action action = action = () => dictionary.AddOrUpdate(key: null, addValue: null, updateValueFactory: nullUpdater);
            action.ShouldThrow<ArgumentNullException>()
                .And.ParamName.Should().Be("key");

            action = () => dictionary.AddOrUpdate(key: "foo", addValue: null, updateValueFactory: nullUpdater);
            action.ShouldThrow<ArgumentNullException>()
                .And.ParamName.Should().Be("updateValueFactory");

            dictionary = null;
            action.ShouldThrow<ArgumentNullException>()
                .And.ParamName.Should().Be("source");
        }
Example #3
0
        static void Main(string[] args)
        {
            var arguments = new Dictionary<string, string>();

             // App.Config Settings
             var appSettingKeys = ConfigurationManager.AppSettings.Keys;
             for (var i = 0; i < appSettingKeys.Count; i++)
             {
            var key = appSettingKeys[i];
            arguments.AddOrUpdate(key, ConfigurationManager.AppSettings[key]);
             }

             // Manual override through CLI.
             var p = new OptionSet()
                    {
                       {
                          "<>", v =>
                                   {
                                      if (!v.StartsWith("--"))
                                         return;
                                      var split = v.Split(new[] { '=' }, 2);
                                      if (split.Length != 2)
                                         return;
                                      arguments.AddOrUpdate(split[0].TrimStart('-'), split[1]);
                                   }
                          }
                    };

             p.Parse(args);

             var loader = new AssemblyLoader();
             var dbProvider = loader.CreateTypeFromAssembly<DbProvider>(arguments["dbp.provider"], arguments);
             var dbCodeFormatter = loader.CreateTypeFromAssembly<DbTraceCodeFormatter>(arguments["tcf.provider"], arguments);
             var codeHighlighter = loader.CreateTypeFromAssembly<HighlightCodeProvider>(arguments["hcp.provider"], arguments);
             var outputProvider = loader.CreateTypeFromAssembly<OutputProvider>(arguments["out.provider"], arguments);

             switch (arguments["app.mode"].ToLower().Trim())
             {
            case "generate":
               var generateCommand = new GenerateOutputCommand(dbProvider, dbCodeFormatter, codeHighlighter, outputProvider, arguments["app.traceName"]);
               generateCommand.Execute();
               break;

            case "start":
               var startCommand = new StartCommand(outputProvider, dbProvider, arguments["app.traceName"]);
               startCommand.Execute();
               break;

            case "stop":
               {
                  var stopCommand = new StopCommand(dbProvider, outputProvider, arguments["app.traceName"]);
                  stopCommand.Execute();
               }
               break;
             }
        }
Example #4
0
        public void AddOrUpdateTest_CommonValue_Exist()
        {
            IDictionary<string, string> dictionary = new Dictionary<string, string>();
            dictionary.AddOrUpdate("key", "value");

            Assert.AreEqual(1, dictionary.Count);
            dictionary.AddOrUpdate("key", "newValue");
            Assert.AreEqual(1, dictionary.Count);
            Assert.IsTrue(dictionary.ContainsKey("key"));
            Assert.AreEqual("newValue", dictionary["key"]);
        }
        public void AddOrUpdate()
        {
            // Type
            var @this = new Dictionary<string, string>();

            // Examples
            string value1 = @this.AddOrUpdate("Fizz", "Buzz"); // return "Buzz";
            string value2 = @this.AddOrUpdate("Fizz", "Buzz2"); // return "Buzz2";

            // Unit Test
            Assert.AreEqual("Buzz", value1);
            Assert.AreEqual("Buzz2", value2);
        }
Example #6
0
        public void AddOrUpdateTest_ListValue_Exist()
        {
            IDictionary<string, IList<string>> dictionary = new Dictionary<string, IList<string>>();
            dictionary.AddOrUpdate("key", "value");

            Assert.AreEqual(1, dictionary.Count);
            dictionary.AddOrUpdate("key", "newValue");
            Assert.AreEqual(1, dictionary.Count);
            Assert.IsTrue(dictionary.ContainsKey("key"));
            Assert.IsNotNull(dictionary["key"]);
            Assert.AreEqual(2, dictionary["key"].Count);
            Assert.AreEqual("value", dictionary["key"].First());
            Assert.AreEqual("newValue", dictionary["key"].Last());
        }
        public void AddOrUpdateTestCase1()
        {
            var key = RandomValueEx.GetRandomString();
            var pair = new KeyValuePair<String, String>( key, RandomValueEx.GetRandomString() );
            var dic = new Dictionary<String, String>();

            var result = dic.AddOrUpdate( pair );
            Assert.AreEqual( 1, dic.Count );
            Assert.AreEqual( pair.Value, result );

            pair = new KeyValuePair<String, String>( key, RandomValueEx.GetRandomString() );
            result = dic.AddOrUpdate( pair );
            Assert.AreEqual( 1, dic.Count );
            Assert.AreEqual( pair.Value, result );
        }
        public void AddOrUpdateTestCase2()
        {
            var key = RandomValueEx.GetRandomString();
            var dic = new Dictionary<String, String>();

            var valueToAdd = RandomValueEx.GetRandomString();
            var result = dic.AddOrUpdate( key, () => valueToAdd );
            Assert.AreEqual( 1, dic.Count );
            Assert.AreEqual( valueToAdd, result );

            valueToAdd = RandomValueEx.GetRandomString();
            result = dic.AddOrUpdate( key, () => valueToAdd );
            Assert.AreEqual( 1, dic.Count );
            Assert.AreEqual( valueToAdd, result );
        }
        protected override bool DoTryGetSourceControlInfo(string solutionFullPath, out IDictionary<string, object> properties)
        {
            properties = new Dictionary<string, object>();

            if (!EnsureInternalSetup(solutionFullPath, ref properties))
                return false;

            var head_path = (string)properties.GetValueOrDefault("git:headPath", () => "");

            if (!File.Exists(head_path))
                return false;

            var head_content = File.ReadAllText(head_path);
            var branch_match = GitBranchRegex.Match(head_content);

            if (!branch_match.Success)
                return false;

            var branch_group = branch_match.Groups["branchName"];

            if (!branch_group.Success)
                return false;

            var branch_name = branch_group.Value;
            properties.Add("git:head", branch_name);

            properties.AddOrUpdate(KnownProperties.BranchName, branch_name);

            return true;
        }
		public void Update()
		{
			var keyedValues = new Dictionary<string, Value> { { "a", new Value { Data = "b" } } };
			keyedValues.AddOrUpdate("a", null, _ => _.Data = "c");

			Assert.AreEqual("c", keyedValues["a"].Data);
		}
		public void Add()
		{
			var keyedValues = new Dictionary<string, Value>();
			keyedValues.AddOrUpdate("a", () => new Value { Data = "b" }, null);

			Assert.AreEqual("b", keyedValues["a"].Data);
		}
        public void TestRandomness(Func<List<int>> getRandomList, int rangeLength, int count)
        {
            var combinations = rangeLength.Factorial(rangeLength - count + 1);
            var iterations = combinations * 100;
            var ocurrences = new ConcurrentDictionary<long, int>(Environment.ProcessorCount, (int)combinations);

            var partitioner = Partitioner.Create(0, (long)iterations);
            Parallel.ForEach(partitioner, new ParallelOptions {MaxDegreeOfParallelism = Environment.ProcessorCount},
                range =>
                {
                    //hopefully having a private dictionary will help concurrency
                    var privateOcurrences = new Dictionary<long, int>();
                    for (long i = range.Item1; i < range.Item2; ++i)
                    {
                        var list = getRandomList();
                        //this will only work when numbers are between 0 and 88
                        long acc = list.Aggregate<int, long>(0, (current, value) => (value + 11) + current*100);
                        privateOcurrences.AddOrUpdate(acc, 1, v => v + 1);
                    }
                    foreach (var privateOcurrence in privateOcurrences)
                    {
                        ocurrences.AddOrUpdate(privateOcurrence.Key,
                            privateOcurrence.Value,
                            (k, v) => v + privateOcurrence.Value);
                    }
                });

            var averageOcurrences = iterations / (combinations * 1.0m);
            var currentAverage = ocurrences.Values.Average();
            Debug.WriteLine("The average ocurrences of this implementation is {0} comparing to {1} in the 'perfect' scenario", currentAverage, averageOcurrences);
            Assert.Less(currentAverage, averageOcurrences * 1.05m);
            Assert.Greater(currentAverage, averageOcurrences * 0.95m);
        }
        public void AddOrUpdate()
        {
            var dictionary = new Dictionary<string, string>();
            Action action = () => dictionary.AddOrUpdate(null, "");
            action.ShouldThrow<ArgumentNullException>()
                .And.ParamName.Should().Be("key");
            dictionary = null;
            action.ShouldThrow<ArgumentNullException>()
                .And.ParamName.Should().Be("source");

            var dictionaryTwo = new Dictionary<int, int>();
            dictionaryTwo.Add(1, 1);
            dictionaryTwo.AddOrUpdate(1, 2);
            dictionaryTwo[1].Should().Be(2);
            dictionaryTwo.AddOrUpdate(2, 3);
            dictionaryTwo[2].Should().Be(3);
        }
Example #14
0
        private static void FindAllListingsForProduct(Product product, List<Listing> listings, Dictionary<string, List<Listing>> allListingsOfProduct)
        {
            foreach (var listing in listings)
            {
                if (listing == null || listing.Picked || !ListingMatchesProduct(product.Tokens, listing.Tokens))
                    continue;

                listing.Picked = true;
                allListingsOfProduct.AddOrUpdate(product.ProductName, listing);
            }
        }
        protected override bool DoTryGetSourceControlInfo(string solutionFullPath, out IDictionary<string, object> properties)
        {
            properties = new Dictionary<string, object>();

            if (!TeamFoundationHelper.IsConnected())
                return false;

            var workspace = (Workspace) null;
            var branchObject = (BranchObject)null;

            var branchName = TeamFoundationHelper.GetBranchNameForItem(solutionFullPath, out workspace, out branchObject);

            if (branchName.IsNullOrEmpty())
                return false;

            properties.AddOrUpdate("tfs:workspace", workspace.Name);

            properties.AddOrUpdate(KnownProperties.BranchName, branchName);

            return true;
        }
Example #16
0
 private static void FindAllListingsForProductAsync(Product product, List<Listing> listings, Dictionary<string, List<Listing>> allListingsOfProduct)
 {
     Parallel.ForEach(listings, listing =>
                                    {
                                        if (
                                            !(listing == null || listing.Picked ||
                                              !ListingMatchesProduct(product.Tokens, listing.Tokens)))
                                        {
                                            listing.Picked = true;
                                            allListingsOfProduct.AddOrUpdate(product.ProductName, listing);
                                        }
                                    }
         );
 }
Example #17
0
        public void AddOrUpdate_KeyExists_KeyIsNotAddedAgain()
        {
            // Arrange
            var dictionary = new Dictionary<string, int> { };

            const string TestKey = "testKey";
            const int FirstValue = 1234;
            dictionary.Add(TestKey, FirstValue);

            // Act
            const int SecondValue = 4321;
            dictionary.AddOrUpdate(TestKey, SecondValue);

            // Assert
            Assert.Equal(1, dictionary.Count);
        }
Example #18
0
        public void AddOrUpdate_KeyDoesNotExist_NewKeyIsAdded()
        {
            // Arrange
            var dictionary = new Dictionary<string, int> { };

            const string TestKey = "testKey";
            const int FirstValue = 1234;
            dictionary.Add(TestKey, FirstValue);

            // Act
            const int SecondValue = 4321;
            dictionary.AddOrUpdate("newKey", SecondValue);

            // Assert
            Assert.Equal(2, dictionary.Count);
        }
Example #19
0
        public void AddOrUpdate_KeyExists_ValueIsUpdated()
        {
            // Arrange
            var dictionary = new Dictionary<string, int>();
            const string TestKey = "testKey";
            const int FirstValue = 1234;
            const int SecondValue = 4321;
            dictionary.Add(TestKey, FirstValue);

            // Act
            dictionary.AddOrUpdate(TestKey, SecondValue);
            int dictionaryValue;
            dictionary.TryGetValue(TestKey, out dictionaryValue);

            // Assert
            Assert.Equal(SecondValue, dictionaryValue);
        }
        protected override bool DoTryGetSourceControlInfo(string solutionFullPath, out IDictionary<string, object> properties)
        {
            properties = new Dictionary<string, object>();

            if (!EnsureInternalSetup(solutionFullPath, ref properties))
                return false;

            var branch_path = (string)properties.GetValueOrDefault("hg:branchPath", () => "");

            if (!File.Exists(branch_path))
                return false;

            var branch_name = File.ReadAllText(branch_path);

            if (branch_name.IsNullOrEmpty())
                return false;

            properties.Add("hg:head", branch_name);

            properties.AddOrUpdate(KnownProperties.BranchName, branch_name);

            return true;
        }
Example #21
0
        private static Dictionary<string, DataRow> InitializeSignalTypes()
        {
            Dictionary<string, DataRow> signalTypes;

            // It is expected that when a point tag is needing to be created that the database will be available
            using (AdoDataConnection database = new AdoDataConnection("systemSettings"))
            {
                signalTypes = new Dictionary<string, DataRow>(StringComparer.OrdinalIgnoreCase);

                foreach (DataRow row in database.Connection.RetrieveData(database.AdapterType, "SELECT * FROM SignalType").AsEnumerable())
                {
                    signalTypes.AddOrUpdate(row["Acronym"].ToString(), row);
                }
            }

            return signalTypes;
        }
Example #22
0
        /// <summary>
        /// This function refreshes a local set of objects that will hold your user's balances in memory for quick
        /// and more efficient fetching for your game UI.
        /// This way, we save many JNI or static calls to native platforms.
        /// 
        /// NOTE: You don't need to call this function as it's automatically called when the game initializes.
        /// NOTE: This is less useful when you work in editor.
        /// </summary>
        public static void RefreshLocalInventory()
        {
            SoomlaUtils.LogDebug(TAG, "Refreshing local inventory");

            localItemBalances = new Dictionary<string, int> ();
            localUpgrades = new Dictionary<string, LocalUpgrade>();
            localEquippedGoods = new HashSet<string>();

            foreach(VirtualCurrency item in StoreInfo.Currencies){
                localItemBalances[item.ItemId] = VirtualCurrencyStorage.GetBalance(item);
            }

            foreach(VirtualGood item in StoreInfo.Goods){
                localItemBalances[item.ItemId] =  VirtualGoodsStorage.GetBalance(item);

                UpgradeVG upgrade = VirtualGoodsStorage.GetCurrentUpgrade(item);
                if (upgrade != null) {
                    int upgradeLevel = GetGoodUpgradeLevel(item.ItemId);
                    localUpgrades.AddOrUpdate(item.ItemId, new LocalUpgrade { itemId = upgrade.ItemId, level = upgradeLevel });
                }

                if (item is EquippableVG) {
                    if (VirtualGoodsStorage.IsEquipped((EquippableVG)item)) {
                        localEquippedGoods.Add(item.ItemId);
                    }
                }
            }
        }
        public void UpdateConfiguration()
        {
            const int LabelLength = 16;

            PhasorType type;
            AnalogType analogType;
            char phase;
            string label, scale;
            uint scalingValue;
            int order;

            // Define a protocol independent configuration frame
            m_baseConfigurationFrame = new ConfigurationFrame(m_idCode, DateTime.UtcNow.Ticks, (ushort)base.FramesPerSecond);

            // Define configuration cells (i.e., PMU's that will appear in outgoing data stream)
            foreach (DataRow deviceRow in DataSource.Tables["OutputStreamDevices"].Select($"ParentID={ID}", "LoadOrder"))
            {
                try
                {
                    // Get device ID and ID code
                    int deviceID = int.Parse(deviceRow["ID"].ToString());
                    ushort idCode = ushort.Parse(deviceRow["IDCode"].ToString());

                    // If number was never assigned or is invalid, we fall back on unique database record ID
                    if (idCode == 0)
                        idCode = unchecked((ushort)deviceID);

                    // Create a new configuration cell
                    ConfigurationCell cell = new ConfigurationCell(m_baseConfigurationFrame, idCode);

                    // Assign user selected data and coordinate formats, derived classes can change
                    string formatString;

                    formatString = deviceRow["PhasorDataFormat"].ToNonNullString(m_dataFormat.ToString());
                    cell.PhasorDataFormat = (DataFormat)Enum.Parse(typeof(DataFormat), string.IsNullOrEmpty(formatString) ? m_dataFormat.ToString() : formatString, true);

                    formatString = deviceRow["FrequencyDataFormat"].ToNonNullString(m_dataFormat.ToString());
                    cell.FrequencyDataFormat = (DataFormat)Enum.Parse(typeof(DataFormat), string.IsNullOrEmpty(formatString) ? m_dataFormat.ToString() : formatString, true);

                    formatString = deviceRow["AnalogDataFormat"].ToNonNullString(m_dataFormat.ToString());
                    cell.AnalogDataFormat = (DataFormat)Enum.Parse(typeof(DataFormat), string.IsNullOrEmpty(formatString) ? m_dataFormat.ToString() : formatString, true);

                    formatString = deviceRow["CoordinateFormat"].ToNonNullString(m_coordinateFormat.ToString());
                    cell.PhasorCoordinateFormat = (CoordinateFormat)Enum.Parse(typeof(CoordinateFormat), string.IsNullOrEmpty(formatString) ? m_coordinateFormat.ToString() : formatString, true);

                    // Assign device identification labels
                    cell.IDLabel = deviceRow["Name"].ToString().TruncateRight(cell.IDLabelLength).Trim();
                    label = deviceRow["Acronym"].ToString().TruncateRight(cell.MaximumStationNameLength).Trim();

                    // Station name is serialized to configuration frame
                    cell.StationName = label;

                    // Define all the phasors configured for this device
                    foreach (DataRow phasorRow in DataSource.Tables["OutputStreamDevicePhasors"].Select($"OutputStreamDeviceID={deviceID}", "LoadOrder"))
                    {
                        order = int.Parse(phasorRow["LoadOrder"].ToNonNullString("0"));
                        label = phasorRow["Label"].ToNonNullString("Phasor " + order).Trim().TruncateRight(LabelLength);
                        type = phasorRow["Type"].ToNonNullString("V").Trim().ToUpper().StartsWith("V") ? PhasorType.Voltage : PhasorType.Current;
                        phase = phasorRow["Phase"].ToNonNullString("+").Trim().ToUpper()[0];
                        scale = phasorRow["ScalingValue"].ToNonNullString("0");

                        if (m_replaceWithSpaceChar != Char.MinValue)
                            label = label.Replace(m_replaceWithSpaceChar, ' ');

                        // Scale can be defined as a negative value in database, so check both formatting styles
                        if (!uint.TryParse(scale, out scalingValue))
                            scalingValue = unchecked((uint)int.Parse(scale));

                        // Choose stream defined default value if no scaling value was defined
                        if (scalingValue == 0)
                            scalingValue = (type == PhasorType.Voltage ? m_voltageScalingValue : m_currentScalingValue);

                        cell.PhasorDefinitions.Add(new PhasorDefinition(
                            cell,
                            GeneratePhasorLabel(label, phase, type),
                            scalingValue,
                            type,
                            null));
                    }

                    // Add frequency definition
                    label = $"{cell.IDLabel.TruncateRight(LabelLength - 5)} Freq".Trim();
                    cell.FrequencyDefinition = new FrequencyDefinition(cell, label);

                    // Optionally define all the analogs configured for this device
                    if (DataSource.Tables.Contains("OutputStreamDeviceAnalogs"))
                    {
                        foreach (DataRow analogRow in DataSource.Tables["OutputStreamDeviceAnalogs"].Select($"OutputStreamDeviceID={deviceID}", "LoadOrder"))
                        {
                            order = int.Parse(analogRow["LoadOrder"].ToNonNullString("0"));
                            label = analogRow["Label"].ToNonNullString("Analog " + order).Trim().TruncateRight(LabelLength);
                            analogType = (AnalogType)int.Parse(analogRow["Type"].ToNonNullString("0"));
                            scale = analogRow["ScalingValue"].ToNonNullString("0");

                            if (m_replaceWithSpaceChar != Char.MinValue)
                                label = label.Replace(m_replaceWithSpaceChar, ' ');

                            // Scale can be defined as a negative value in database, so check both formatting styles
                            if (!uint.TryParse(scale, out scalingValue))
                                scalingValue = unchecked((uint)int.Parse(scale));

                            cell.AnalogDefinitions.Add(new AnalogDefinition(
                                cell,
                                label,
                                scalingValue == 0 ? m_analogScalingValue : scalingValue,
                                analogType));
                        }
                    }

                    // Optionally define all the digitals configured for this device
                    if (DataSource.Tables.Contains("OutputStreamDeviceDigitals"))
                    {
                        foreach (DataRow digitalRow in DataSource.Tables["OutputStreamDeviceDigitals"].Select($"OutputStreamDeviceID={deviceID}", "LoadOrder"))
                        {
                            order = int.Parse(digitalRow["LoadOrder"].ToNonNullString("0"));
                            scale = digitalRow["MaskValue"].ToNonNullString("0");

                            // IEEE C37.118 digital labels are defined with all 16-labels (one for each bit) in one large formatted string
                            label = digitalRow["Label"].ToNonNullString("Digital " + order).Trim().TruncateRight(LabelLength * 16);

                            if (m_replaceWithSpaceChar != Char.MinValue)
                                label = label.Replace(m_replaceWithSpaceChar, ' ');

                            // Mask can be defined as a negative value in database, so check both formatting styles
                            if (!uint.TryParse(scale, out scalingValue))
                                scalingValue = unchecked((uint)int.Parse(scale));

                            cell.DigitalDefinitions.Add(new DigitalDefinition(
                                cell,
                                label,
                                scalingValue == 0 ? m_digitalMaskValue : scalingValue));
                        }
                    }

                    m_baseConfigurationFrame.Cells.Add(cell);
                }
                catch (Exception ex)
                {
                    OnProcessException(MessageLevel.Warning, new InvalidOperationException($"Failed to define output stream device \"{deviceRow["Acronym"].ToString().Trim()}\" due to exception: {ex.Message}", ex));
                }
            }

            OnStatusMessage(MessageLevel.Info, $"Defined {m_baseConfigurationFrame.Cells.Count:N0} output stream devices...");

            // Create new lookup table for signal references
            Dictionary<MeasurementKey, SignalReference[]> signalReferences = new Dictionary<MeasurementKey, SignalReference[]>();

            Dictionary<string, int> signalCellIndexes = new Dictionary<string, int>();
            SignalReference signal;
            SignalReference lastSignal = new SignalReference("__-UNKNOWN");
            MeasurementKey measurementKey;
            bool foundQualityFlagsMeasurement = false;
            bool isQualityFlagsMeasurement;

            IEnumerable<DataRow> measurementRows = DataSource.Tables["OutputStreamMeasurements"]
                .Select($"AdapterID={ID}")
                .Select(row => new { Row = row, SigRef = new SignalReference(row["SignalReference"].ToString()) })
                .OrderBy(obj => obj.SigRef.Acronym)
                .ThenBy(obj => obj.SigRef.Kind)
                .ThenBy(obj => obj.SigRef.Index)
                .Select(obj => obj.Row);

            // Define measurement to signals cross reference dictionary
            foreach (DataRow measurementRow in measurementRows)
            {
                isQualityFlagsMeasurement = false;

                try
                {
                    // Create a new signal reference
                    signal = new SignalReference(measurementRow["SignalReference"].ToString());

                    // See if this is the quality flags designation for this output stream 
                    if (signal.Kind == SignalKind.Quality)
                    {
                        if (Name.Equals(signal.Acronym, StringComparison.OrdinalIgnoreCase))
                        {
                            if (foundQualityFlagsMeasurement)
                                throw new Exception("Only one quality flags measurement can be assigned to an output stream - additional quality flags will be ignored.");

                            foundQualityFlagsMeasurement = true;
                            isQualityFlagsMeasurement = true;
                        }
                        else
                        {
                            throw new Exception($"Unexpected quality flags measurement assignment to \"{signal.Acronym}\". A single quality flags measurement can be assigned to output stream \"{Name}\".");
                        }
                    }
                    else
                    {
                        // Lookup cell index by acronym - doing this work upfront will save a huge amount of work during primary measurement sorting
                        if (!signalCellIndexes.TryGetValue(signal.Acronym, out signal.CellIndex))
                        {
                            // We cache these indices locally to speed up initialization as we'll be
                            // requesting them for the same devices over and over
                            signal.CellIndex = m_baseConfigurationFrame.Cells.IndexOfStationName(signal.Acronym);
                            signalCellIndexes.Add(signal.Acronym, signal.CellIndex);
                        }
                    }

                    // No need to define this measurement for sorting unless it has a destination in the outgoing frame
                    if (signal.CellIndex > -1 || isQualityFlagsMeasurement)
                    {
                        // Get historian field
                        string historian = measurementRow["Historian"].ToNonNullString();
                        string pointID = measurementRow["PointID"].ToString();

                        // Define measurement key
                        if (!string.IsNullOrEmpty(historian))
                        {
                            measurementKey = MeasurementKey.LookUpOrCreate(historian, uint.Parse(pointID));
                        }
                        else
                        {
                            DataTable activeMeasurements = DataSource.Tables["ActiveMeasurements"];
                            DataRow[] activeMeasurementRows = new DataRow[0];

                            object activeMeasurementSignalID = null;
                            object activeMeasurementID = null;

                            // OPTIMIZE: This select query will be slow on very large ActiveMeasurement implementations, consider optimization.
                            if ((object)activeMeasurements != null)
                                activeMeasurementRows = activeMeasurements.Select($"ID LIKE '*:{pointID}'");

                            if (activeMeasurementRows.Length == 1)
                            {
                                activeMeasurementSignalID = activeMeasurementRows[0]["SignalID"];
                                activeMeasurementID = activeMeasurementRows[0]["ID"];
                            }

                            // If we still can't find the measurement key, now is the time to give up
                            if ((object)activeMeasurementSignalID == null && (object)activeMeasurementID == null)
                                throw new Exception($"Cannot find measurement key for measurement with pointID {pointID}");

                            measurementKey = MeasurementKey.LookUpOrCreate(Guid.Parse(activeMeasurementRows[0]["SignalID"].ToString()), activeMeasurementID.ToString());
                        }

                        // Re-index signals at runtime in the
                        // same way phasors are indexed at runtime
                        if (signal.Index >= 1)
                        {
                            if (signal.Kind == lastSignal.Kind && signal.Acronym == lastSignal.Acronym)
                                signal.Index = lastSignal.Index + 1;
                            else
                                signal.Index = 1;
                        }

                        lastSignal = signal;

                        // It is possible, but not as common, that a single measurement will have multiple destinations
                        // within an outgoing data stream frame, hence the following
                        signalReferences.AddOrUpdate(measurementKey, key => new[] { signal }, (key, signals) =>
                        {
                            // Add a new signal to existing collection
                            Array.Resize(ref signals, signals.Length + 1);
                            signals[signals.Length - 1] = signal;
                            return signals;
                        });
                    }
                }
                catch (Exception ex)
                {
                    OnProcessException(MessageLevel.Warning, new InvalidOperationException($"Failed to associate measurement key to signal reference \"{measurementRow["SignalReference"].ToNonNullString()}\" due to exception: {ex.Message}", ex));
                }
            }

            // Update the m_signalReferences member variable so that configuration changes will begin to take effect
            Interlocked.Exchange(ref m_signalReferences, signalReferences);

            // Assign action adapter input measurement keys - this assigns the expected measurements per frame needed
            // by the concentration engine for preemptive publication 
            InputMeasurementKeys = signalReferences.Keys.ToArray();

            // Allow for spaces in output stream device names if a replacement character has been defined for spaces
            if (m_replaceWithSpaceChar != char.MinValue)
            {
                foreach (IConfigurationCell cell in m_baseConfigurationFrame.Cells)
                    cell.StationName = cell.StationName.Replace(m_replaceWithSpaceChar, ' ');
            }

            // Create a new protocol specific configuration frame
            m_configurationFrame = CreateNewConfigurationFrame(m_baseConfigurationFrame);

            // Cache new protocol specific configuration frame
            CacheConfigurationFrame(m_configurationFrame, Name);
        }
        void CollectThemeInfo()
        {
            var result = new Dictionary<string, object>();

            System.Windows.Media.Color accentColor = Colors.White;

            //if (Config.ShouldUseVisualStudioTheme)
            {
                var theme_color = ThemeInfo.GetThemeColor();

                accentColor = theme_color;

                result.AddOrUpdate(KnownProperties.AccentColor, accentColor);
            }

            CurrentThemeInfo.Clear();
            CurrentThemeInfo.AddOrUpdateFrom((IDictionary<string,object>)result);
        }
Example #25
0
    static private Dictionary<BoxedExpression, List<ProofObligation>> RemoveStrongerPremises(Dictionary<BoxedExpression, List<ProofObligation>> inferred)
    {
      var result = new Dictionary<BoxedExpression, List<ProofObligation>>();

      foreach (var pair in inferred)
      {
        BoxedExpression premise, condition;
        BinaryOperator bop;

        if (pair.Key.IsBinaryExpression(out bop, out premise, out condition) && bop == BinaryOperator.LogicalOr)
        {
          // premise || conddition, but we have already condition without premise
          if (inferred.ContainsKey(condition))
          {
            List<ProofObligation> obligations;

            // we already processed  "condition", so we update the proof obligation
            if (result.TryGetValue(condition, out obligations) || inferred.TryGetValue(condition, out obligations))
            {
              obligations.AddRange(pair.Value);
            }
            else
            {
              Contract.Assume(false, "Impossible case!");
            }


            // was: continue
            continue;
          }

          // premise || premise
          if (BoxedExpression.SimpleSyntacticEquality(premise, condition))
          {
            result.AddOrUpdate(premise, pair.Value);

            // was: result.Add(premise);
            continue;
          }

          // if cond ==> premise, remove the premise
          if (Implies(condition, premise))
          {
            result.AddOrUpdate(condition, pair.Value);
            // was: result.Add(condition);
            continue;
          }

          // a < b || a == b, becomes a <= b
          BoxedExpression joined;
          if (CanMergeTogether(condition, premise, out joined))
          {
            result.AddOrUpdate(joined, pair.Value);
            // result.Add(joined);
            continue;
          }

          // F: We depend on the order of the facts!!! We should iterate to a fixpoint or we should pre-sort the list of inferred facts

          // "premise && !premise || condition" becomes "premise && condition"
          BoxedExpression newPre;
          if(PremiseIsImpliedByOtherPreconditions(premise, condition, result.Keys, out newPre))
          {
            result.AddOrUpdate(newPre, pair.Value);
            continue;
          }
        }
        result.AddOrUpdate(pair.Key, pair.Value);
        // result.Add(pair);
      }

      return result;
    }
Example #26
0
        private static List<EventHistoryRecord> ParseEventHistoryRecords(string[] lines, ref int index)
        {
            List<EventHistoryRecord> histories = new List<EventHistoryRecord>();
            EventHistoryRecord eventHistory;
            string currentLine;

            List<Token> tokens;
            List<Token> headers;
            Dictionary<Token, Token> fields;
            Token fieldHeader;
            Token field;

            int eventNumber;
            DateTime dateTime;
            double faultLocation;
            double current;
            double frequency;
            int group;
            int shot;

            string date;
            string time;

            // Parse header
            headers = Split(lines[index++]);

            // Skip to the next nonblank line
            SkipBlanks(lines, ref index);

            while (index < lines.Length)
            {
                currentLine = lines[index];

                // Empty line indicates end of event histories
                if (string.IsNullOrWhiteSpace(currentLine))
                    break;

                // Create a new event history record
                eventHistory = new EventHistoryRecord();

                // Parse fields
                tokens = Split(currentLine);

                // Initialize date and time variables
                date = null;
                time = null;

                fields = new Dictionary<Token, Token>();

                foreach (Token token in tokens)
                {
                    fieldHeader = headers.MinBy(header => token.Distance(header));
                    fields.AddOrUpdate(fieldHeader, token, (key, value) => value.JoinWith(token));
                }
                
                foreach (Token header in headers)
                {
                    if (fields.TryGetValue(header, out field))
                    {

                        switch (header.Text.ToUpper())
                        {
                            case "#":
                            case "REC_NUM":
                                // Parse the field as an event number
                                if (int.TryParse(field.Text, out eventNumber))
                                    eventHistory.EventNumber = eventNumber;

                                break;

                            case "DATE":
                                // Parse the field as a date value
                                date = field.Text;

                                // If both date and time have been provided, parse them as a DateTime
                                if ((object)time != null && TryParseDateTime(string.Format("{0} {1}", date, time), out dateTime))
                                    eventHistory.Time = dateTime;

                                break;

                            case "TIME":
                                // Parse the field as a time value
                                time = field.Text;

                                // If both date and time have been provided, parse them as a DateTime
                                if ((object)date != null && TryParseDateTime(string.Format("{0} {1}", date, time), out dateTime))
                                    eventHistory.Time = dateTime;

                                break;

                            case "EVENT":
                                // Parse the field as an event type
                                eventHistory.EventType = field.Text;
                                break;

                            case "LOCAT":
                            case "LOCATION":
                                // Parse the field as a fault location value
                                if (double.TryParse(field.Text, out faultLocation))
                                    eventHistory.FaultLocation = faultLocation;

                                break;

                            case "CURR":
                                // Parse the field as a current magnitude
                                if (double.TryParse(field.Text, out current))
                                    eventHistory.Current = current;

                                break;

                            case "FREQ":
                                // Parse the field as a frequency value
                                if (double.TryParse(field.Text, out frequency))
                                    eventHistory.Frequency = frequency;

                                break;

                            case "GRP":
                            case "GROUP":
                                // Parse the field as a group number
                                if (int.TryParse(field.Text, out group))
                                    eventHistory.Group = group;

                                break;

                            case "SHOT":
                                // Parse the field as a shot number
                                if (int.TryParse(field.Text, out shot))
                                    eventHistory.Shot = shot;

                                break;

                            case "TARGETS":
                                // Parse the field as targets
                                eventHistory.Targets = field.Text;
                                break;
                        }
                    }
                }

                // Add history record to the list of histories
                histories.Add(eventHistory);

                // Advance to the next line
                index++;
            }

            return histories;
        }
Example #27
0
    static private Dictionary<BoxedExpression, List<ProofObligation>> RemoveCoveringPremises(Dictionary<BoxedExpression, List<ProofObligation>> original)
    {
      Contract.Requires(original != null);
      Contract.Ensures(Contract.Result<Dictionary<BoxedExpression, List<ProofObligation>>>() != null);

      var result = new Dictionary<BoxedExpression, List<ProofObligation>>();

      // we look for premise ==> cond
      // so the dictionary contains cond --> (premise ==> cond)
      var cached = new Dictionary<BoxedExpression, Tuple<BoxedExpression, List<ProofObligation>>>(original.Count);

      foreach (var pair in original)
      {
        BinaryOperator bop;
        BoxedExpression premise, cond;
        if (pair.Key.IsBinaryExpression(out bop, out premise, out cond) && bop == BinaryOperator.LogicalOr)
        {
          Tuple<BoxedExpression, List<ProofObligation>> prev;
          if (cached.TryGetValue(cond, out prev))
          {
            Contract.Assume(prev != null);
            BoxedExpression prevPremise, prevCond;
            if (prev.Item1.IsBinaryExpression(out bop, out prevPremise, out prevCond) && bop == BinaryOperator.LogicalOr)
            {
              Contract.Assume(prevCond.Equals(cond));

              cached.Remove(cond);

              if (premise.Negate().Equals(prevPremise))
              {
                result.AddOrUpdate(cond, pair.Value);
              }
              else
              {
                result.AddOrUpdate(pair.Key, pair.Value);
                result.AddOrUpdate(prev.Item1, prev.Item2);
              }
            }
            else
            {
              Contract.Assume(false);
            }
          }
          else
          {
            cached[cond] = new Tuple<BoxedExpression,List<ProofObligation>>(pair.Key, pair.Value);
          }
        }
        else
        {
          result.AddOrUpdate(pair.Key, pair.Value);
        }
      }

      foreach (var pairs in cached)
      {
        result.AddOrUpdate(pairs.Value.Item1, pairs.Value.Item2);
      }

      return result;
    }
Example #28
0
        public override void Write(byte[] buffer, int offset, int count)
        {
            var bodyStart = 0;

            if (!_headersRead)
            {
                var streamData = Encoding.UTF8.GetString(buffer, 0, count);
                _headerData += streamData;
                bodyStart = _headerData.IndexOf(CrLf + CrLf, StringComparison.Ordinal);
                if (bodyStart >= 0)
                {
                    _headersRead = true;
                    _headerData = _headerData.Substring(0, bodyStart);
                }
            }

            if (_headersRead)
            {
                var httpLines = _headerData.Split(new[] { CrLf }, StringSplitOptions.None);
                if (httpLines.Length > 0)
                {
                    var requestLine = httpLines[0];
                    var splitRequest = requestLine.Split(' ');

                    Method = splitRequest.Length > 0 ? splitRequest[0] : string.Empty;
                    Uri = splitRequest.Length > 1 ? splitRequest[1] : string.Empty;
                    HttpVersion = splitRequest.Length > 2 ? splitRequest[2] : string.Empty;
                }

                if (httpLines.Length > 1)
                {
                    Headers = new Dictionary<string, string>(StringComparer.Ordinal);

                    for (int headerLineIndex = 1; headerLineIndex < httpLines.Length; headerLineIndex++)
                    {
                        if (string.IsNullOrEmpty(httpLines[headerLineIndex])) // The start of the body
                            break;

                        var header = httpLines[headerLineIndex];

                        Headers.AddOrUpdate(
                            header.Split(':')[0],
                            header.Split(':')[1].Trim());
                    }
                }
            }

            if (bodyStart >= 0 && count - (bodyStart + 4) > 0)
            {
                _bodyStream.Write(buffer, (bodyStart + 4), count - (bodyStart + 4));
            }
        }