Example #1
0
        public bool InitiateIntegrityUpdate()
        {
            //lock (lockObj)
            {
                ModelResourcesDesc modelResourcesDesc = new ModelResourcesDesc();

                List <ModelCode>           properties = new List <ModelCode>(20);
                List <ResourceDescription> retList    = new List <ResourceDescription>(5);

                int    iteratorId        = 0;
                int    resourcesLeft     = 0;
                int    numberOfResources = 2;
                string message           = string.Empty;

                #region getting Generators

                try
                {
                    // get all generators from NMS
                    properties = modelResourcesDesc.GetAllPropertyIds(ModelCode.GENERATOR);

                    iteratorId    = NetworkModelGDAProxy.Instance.GetExtentValues(ModelCode.GENERATOR, properties);
                    resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorId);

                    while (resourcesLeft > 0)
                    {
                        List <ResourceDescription> rds = NetworkModelGDAProxy.Instance.IteratorNext(numberOfResources, iteratorId);
                        retList.AddRange(rds);
                        resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorId);
                    }
                    NetworkModelGDAProxy.Instance.IteratorClose(iteratorId);

                    // add synchronous machines to internal collection
                    internalGenerators.Clear();
                    internalGenerators.AddRange(retList);
                }
                catch (Exception e)
                {
                    message = string.Format("Getting extent values method failed for {0}.\n\t{1}", ModelCode.GENERATOR, e.Message);
                    Console.WriteLine(message);
                    CommonTrace.WriteTrace(CommonTrace.TraceError, message);

                    Console.WriteLine("Trying again...");
                    CommonTrace.WriteTrace(CommonTrace.TraceError, "Trying again...");
                    NetworkModelGDAProxy.Instance = null;
                    Thread.Sleep(1000);
                    InitiateIntegrityUpdate();
                }

                message = string.Format("Integrity update: Number of {0} values: {1}", ModelCode.GENERATOR.ToString(), internalGenerators.Count.ToString());
                CommonTrace.WriteTrace(CommonTrace.TraceInfo, message);
                Console.WriteLine("Integrity update: Number of {0} values: {1}", ModelCode.GENERATOR.ToString(), internalGenerators.Count.ToString());

                // clear retList for getting new model from NMS
                retList.Clear();

                properties.Clear();
                iteratorId    = 0;
                resourcesLeft = 0;

                #endregion getting Generators

                #region getting EnergyConsumer

                try
                {
                    // third get all enenrgy consumers from NMS
                    properties = modelResourcesDesc.GetAllPropertyIds(ModelCode.ENERGY_CONSUMER);

                    iteratorId    = NetworkModelGDAProxy.Instance.GetExtentValues(ModelCode.ENERGY_CONSUMER, properties);
                    resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorId);

                    while (resourcesLeft > 0)
                    {
                        List <ResourceDescription> rds = NetworkModelGDAProxy.Instance.IteratorNext(numberOfResources, iteratorId);
                        retList.AddRange(rds);
                        resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorId);
                    }
                    NetworkModelGDAProxy.Instance.IteratorClose(iteratorId);

                    // add energy consumer to internal collection
                    internalEnergyConsumers.Clear();
                    internalEnergyConsumers.AddRange(retList);
                }
                catch (Exception e)
                {
                    message = string.Format("Getting extent values method failed for {0}.\n\t{1}", ModelCode.ENERGY_CONSUMER, e.Message);
                    Console.WriteLine(message);
                    CommonTrace.WriteTrace(CommonTrace.TraceError, message);
                    return(false);
                }

                message = string.Format("Integrity update: Number of {0} values: {1}", ModelCode.ENERGY_CONSUMER.ToString(), internalEnergyConsumers.Count.ToString());
                CommonTrace.WriteTrace(CommonTrace.TraceInfo, message);
                Console.WriteLine("Integrity update: Number of {0} values: {1}", ModelCode.ENERGY_CONSUMER.ToString(), internalEnergyConsumers.Count.ToString());

                // clear retList
                retList.Clear();

                #endregion getting EnergyConsumer

                FillData();
                FillInitialCommandedGenerators();

                FillInitialDiscreteCounters();

                return(true);
            }
        }
Example #2
0
        public bool InitiateIntegrityUpdate()
        {
            List <ModelCode> properties         = new List <ModelCode>(10); //analog has 10 properties
            List <ModelCode> propertiesDiscrete = new List <ModelCode>(10);
            ModelCode        modelCode          = ModelCode.ANALOG;
            ModelCode        modelCodeDiscrete  = ModelCode.DISCRETE;

            int resourcesLeft     = 0;
            int numberOfResources = 2;

            List <ResourceDescription> retList         = new List <ResourceDescription>(5);
            List <ResourceDescription> retListDiscrete = new List <ResourceDescription>(5);

            try
            {
                properties         = modelResourcesDesc.GetAllPropertyIds(modelCode);
                propertiesDiscrete = modelResourcesDesc.GetAllPropertyIds(modelCodeDiscrete);

                var iteratorId = NetworkModelGDAProxy.Instance.GetExtentValues(modelCode, properties);
                resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorId);

                while (resourcesLeft > 0)
                {
                    List <ResourceDescription> rds = NetworkModelGDAProxy.Instance.IteratorNext(numberOfResources, iteratorId);
                    retList.AddRange(rds);
                    resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorId);
                }
                NetworkModelGDAProxy.Instance.IteratorClose(iteratorId);

                var iteratorIdDiscrete = NetworkModelGDAProxy.Instance.GetExtentValues(modelCodeDiscrete, propertiesDiscrete);
                resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorIdDiscrete);

                while (resourcesLeft > 0)
                {
                    List <ResourceDescription> rds = NetworkModelGDAProxy.Instance.IteratorNext(numberOfResources, iteratorIdDiscrete);
                    retListDiscrete.AddRange(rds);
                    resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorIdDiscrete);
                }
                NetworkModelGDAProxy.Instance.IteratorClose(iteratorIdDiscrete);
            }
            catch (Exception e)
            {
                NetworkModelGDAProxy.Instance = null;
                Thread.Sleep(1000);
                InitiateIntegrityUpdate();

                return(false);
            }

            try
            {
                foreach (ResourceDescription rd in retList)
                {
                    Analog analog = ResourcesDescriptionConverter.ConvertTo <Analog>(rd);

                    if ((DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(analog.PowerSystemResource) == DMSType.ENERGY_CONSUMER)
                    {
                        energyConsumerAnalogs.Add(new AnalogLocation()
                        {
                            Analog        = analog,
                            StartAddress  = Int32.Parse(analog.ScadaAddress.Split('_')[1]),
                            Length        = 2,
                            LengthInBytes = 4
                        });
                    }
                    else
                    {
                        generatorAnalogs.Add(new AnalogLocation()
                        {
                            Analog        = analog,
                            StartAddress  = Int32.Parse(analog.ScadaAddress.Split('_')[1]),
                            Length        = 2,
                            LengthInBytes = 4
                        });
                    }
                }

                foreach (ResourceDescription rd in retListDiscrete)
                {
                    Discrete discrete = ResourcesDescriptionConverter.ConvertTo <Discrete>(rd);

                    if ((DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(discrete.PowerSystemResource) == DMSType.ENERGY_CONSUMER)
                    {
                        energyConsumerDiscretes.Add(new DiscreteLocation()
                        {
                            Discrete      = discrete,
                            StartAddress  = Int32.Parse(discrete.ScadaAddress.Split('_')[1]),
                            Length        = 1,
                            LengthInBytes = 2
                        });
                    }
                    else
                    {
                        generatorDscretes.Add(new DiscreteLocation()
                        {
                            Discrete      = discrete,
                            StartAddress  = Int32.Parse(discrete.ScadaAddress.Split('_')[1]),
                            Length        = 1,
                            LengthInBytes = 2
                        });
                    }
                }
            }
            catch (Exception e)
            {
                var message1 = string.Format("Conversion to Analog object failed.\n\t{0}", e.Message);
                Console.WriteLine(message1);
                CommonTrace.WriteTrace(CommonTrace.TraceError, message1);
                return(false);
            }

            var message = string.Format("Integrity update: Number of {0} values: {1}", modelCode.ToString(), retList.Count.ToString());

            CommonTrace.WriteTrace(CommonTrace.TraceInfo, message);
            Console.WriteLine("Integrity update: Number of {0} values: {1}", modelCode.ToString(), retList.Count.ToString());

            Console.WriteLine("EnergyConsumer:");
            foreach (AnalogLocation al in energyConsumerAnalogs)
            {
                Console.WriteLine(al.Analog.Mrid + " " + al.Analog.NormalValue);
                var dic = energyConsumerDiscretes.Find(x => x.Discrete.PowerSystemResource == al.Analog.PowerSystemResource);
                Console.WriteLine(dic.Discrete.Mrid + " " + dic.Discrete.NormalValue);
            }
            Console.WriteLine("Generator:");
            foreach (AnalogLocation al in generatorAnalogs)
            {
                Console.WriteLine(al.Analog.Mrid + " " + al.Analog.NormalValue);
                var dic = generatorDscretes.Find(x => x.Discrete.PowerSystemResource == al.Analog.PowerSystemResource);
                Console.WriteLine(dic.Discrete.Mrid + " " + dic.Discrete.NormalValue);
            }

            return(true);
        }
Example #3
0
        /// <summary>
        /// Metoda koja na osnovu gid-a vraca substation
        /// </summary>
        /// <param name="gid"></param>
        /// <returns></returns>
        public Substation GetSubstation(long gid)
        {
            Substation substation = null;

            try
            {
                List <ModelCode> properties = modelResourcesDesc.GetAllPropertyIds(ModelCode.SUBSTATION);

                ResourceDescription rd = GdaQueryProxy.GetValues(gid, properties);
                substation = new Substation(rd.Id);
                substation.ConvertFromRD(rd);
                CommonTrace.WriteTrace(CommonTrace.TraceError, "Getting extent values method successfully finished.");
            }
            catch (Exception e)
            {
                string message = string.Format("Getting extent values method failed for {0}.\n\t{1}", ModelCode.ANALOGVALUE, e.Message);
                Console.WriteLine(message);
                CommonTrace.WriteTrace(CommonTrace.TraceError, message);
            }

            return(substation);
        }
Example #4
0
        /// <summary>
        /// Method implements integrity update logic for scada cr component
        /// </summary>
        /// <returns></returns>
        public bool InitiateIntegrityUpdate()
        {
            List <ModelCode> properties         = new List <ModelCode>(10);
            List <ModelCode> propertiesDiscrete = new List <ModelCode>(10);
            ModelCode        modelCode          = ModelCode.ANALOG;
            ModelCode        modelCodeDiscrete  = ModelCode.DISCRETE;
            int iteratorId        = 0;
            int resourcesLeft     = 0;
            int numberOfResources = 2;

            List <ResourceDescription> retList         = new List <ResourceDescription>(5);
            List <ResourceDescription> retListDiscrete = new List <ResourceDescription>(5);

            try
            {
                properties         = modelResourcesDesc.GetAllPropertyIds(modelCode);
                propertiesDiscrete = modelResourcesDesc.GetAllPropertyIds(modelCodeDiscrete);

                iteratorId    = NetworkModelGDAProxy.Instance.GetExtentValues(modelCode, properties);
                resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorId);

                while (resourcesLeft > 0)
                {
                    List <ResourceDescription> rds = NetworkModelGDAProxy.Instance.IteratorNext(numberOfResources, iteratorId);
                    retList.AddRange(rds);
                    resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorId);
                }
                NetworkModelGDAProxy.Instance.IteratorClose(iteratorId);


                var iteratorIdDiscrete = NetworkModelGDAProxy.Instance.GetExtentValues(modelCodeDiscrete, propertiesDiscrete);
                resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorIdDiscrete);

                while (resourcesLeft > 0)
                {
                    List <ResourceDescription> rds = NetworkModelGDAProxy.Instance.IteratorNext(numberOfResources, iteratorIdDiscrete);
                    retListDiscrete.AddRange(rds);
                    resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorIdDiscrete);
                }
                NetworkModelGDAProxy.Instance.IteratorClose(iteratorIdDiscrete);
            }
            catch (Exception e)
            {
                message = string.Format("Getting extent values method failed for {0}.\n\t{1}", modelCode, e.Message);
                Console.WriteLine(message);

                Console.WriteLine("Trying again...");
                CommonTrace.WriteTrace(CommonTrace.TraceError, "Trying again...");
                NetworkModelGDAProxy.Instance = null;
                Thread.Sleep(1000);
                InitiateIntegrityUpdate();
                return(false);
            }

            listOfAnalog.Clear();

            try
            {
                foreach (ResourceDescription rd in retList)
                {
                    Analog analog = ResourcesDescriptionConverter.ConvertTo <Analog>(rd);

                    if ((DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(analog.PowerSystemResource) == DMSType.ENERGY_CONSUMER)
                    {
                        listOfAnalog.Add(new AnalogLocation()
                        {
                            Analog        = analog,
                            StartAddress  = Int32.Parse(analog.ScadaAddress.Split('_')[1]),
                            Length        = 2,
                            LengthInBytes = 4
                        });
                    }
                    else
                    {
                        listOfAnalog.Add(new AnalogLocation()
                        {
                            Analog        = analog,
                            StartAddress  = Int32.Parse(analog.ScadaAddress.Split('_')[1]),
                            Length        = 2,
                            LengthInBytes = 4
                        });
                    }
                }


                foreach (ResourceDescription rd in retListDiscrete)
                {
                    Discrete discrete = ResourcesDescriptionConverter.ConvertTo <Discrete>(rd);

                    if ((DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(discrete.PowerSystemResource) == DMSType.ENERGY_CONSUMER)
                    {
                        listOfDiscretes.Add(new DiscreteLocation()
                        {
                            Discrete      = discrete,
                            StartAddress  = Int32.Parse(discrete.ScadaAddress.Split('_')[1]),
                            Length        = 1,
                            LengthInBytes = 2
                        });
                    }
                    else
                    {
                        listOfDiscretes.Add(new DiscreteLocation()
                        {
                            Discrete      = discrete,
                            StartAddress  = Int32.Parse(discrete.ScadaAddress.Split('_')[1]),
                            Length        = 1,
                            LengthInBytes = 2
                        });
                    }
                }
            }
            catch (Exception e)
            {
                message = string.Format("Conversion to Analog object failed.\n\t{0}", e.Message);
                Console.WriteLine(message);
                CommonTrace.WriteTrace(CommonTrace.TraceError, message);
                return(false);
            }

            message = string.Format("Integrity update: Number of {0} values: {1}", modelCode.ToString(), listOfAnalog.Count.ToString());
            CommonTrace.WriteTrace(CommonTrace.TraceInfo, message);
            Console.WriteLine("Integrity update: Number of {0} values: {1}", modelCode.ToString(), listOfAnalog.Count.ToString());
            return(true);
        }
        public bool TryGetAllModelEntities(
            out Dictionary <long, ITopologyElement> topologyElements,
            out Dictionary <long, List <long> > elementConnections,
            out HashSet <long> reclosers,
            out List <long> energySources)
        {
            TopologyElements.Clear();
            Measurements.Clear();
            EnergySources.Clear();
            ElementConnections.Clear();
            MeasurementToConnectedTerminalMap.Clear();
            TerminalToConnectedElementsMap.Clear();
            BaseVoltages.Clear();
            Reclosers.Clear();

            bool success = true;

            try
            {
                logger.LogInfo("Getting all network model elements and converting them...");
                GetBaseVoltages().Wait();
                Parallel.For(0, ConcreteModels.Count, (i) =>
                {
                    var model = ConcreteModels.ElementAt(i);
                    if (model != ModelCode.BASEVOLTAGE)
                    {
                        List <ModelCode> properties = modelResourcesDesc.GetAllPropertyIds(model);
                        var elements = networkModelGDA.GetExtentValues(model, properties).Result;
                        foreach (var element in elements)
                        {
                            TransformToTopologyElement(element);
                        }
                    }
                });

                foreach (var measurement in Measurements.Values)
                {
                    PutMeasurementsInElements(measurement);
                    Provider.Instance.MeasurementProvider.AddMeasurementElementPair(measurement.Id, measurement.ElementId);
                }

                foreach (var element in TopologyElements.Values)
                {
                    if (element.Measurements.Count == 0)
                    {
                        CreateNoScadaMeasurement(element);
                    }
                }

                topologyElements   = TopologyElements;
                elementConnections = ElementConnections;
                reclosers          = Reclosers;
                energySources      = EnergySources;
            }
            catch (Exception ex)
            {
                logger.LogError($"[NMSManager] Failed in get all network model elements. Exception message: {ex.Message}");
                topologyElements   = null;
                elementConnections = null;
                reclosers          = null;
                energySources      = null;
                success            = false;
            }
            return(success);
        }
        public async Task <bool> Prepare()
        {
            bool success;

            try
            {
                Logger.LogDebug("Enter prepare method");
                this.unitOfWork = new UnitOfWork();
                List <Consumer> consumerDbEntities = this.unitOfWork.ConsumerRepository.GetAll().ToList();

                var resourceDescriptions = await GetExtentValues(ModelCode.ENERGYCONSUMER, modelResourcesDesc.GetAllPropertyIds(ModelCode.ENERGYCONSUMER));

                var modelChangesEnumerable = await HistoryModelChanges.GetEnumerableDictionaryAsync();


                List <OutageEntity> activeOutages = this.unitOfWork.OutageRepository.GetAllActive().ToList();

                this.unitOfWork.OutageRepository.RemoveRange(activeOutages);

                //this.unitOfWork.OutageRepository.RemoveAll();
                //this.unitOfWork.EquipmentRepository.RemoveAll();
                //this.unitOfWork.EquipmentHistoricalRepository.RemoveAll();
                //this.unitOfWork.ConsumerHistoricalRepository.RemoveAll();

                foreach (Consumer consumer in consumerDbEntities)
                {
                    if (modelChangesEnumerable[(byte)DeltaOpType.Delete].Contains(consumer.ConsumerId))
                    {
                        this.unitOfWork.ConsumerRepository.Remove(consumer);
                    }
                    else if (modelChangesEnumerable[(byte)DeltaOpType.Update].Contains(consumer.ConsumerId))
                    {
                        consumer.ConsumerMRID = resourceDescriptions[consumer.ConsumerId].GetProperty(ModelCode.IDOBJ_MRID).AsString();
                        consumer.FirstName    = resourceDescriptions[consumer.ConsumerId].GetProperty(ModelCode.ENERGYCONSUMER_FIRSTNAME).AsString();
                        consumer.LastName     = resourceDescriptions[consumer.ConsumerId].GetProperty(ModelCode.ENERGYCONSUMER_LASTNAME).AsString();
                        consumer.Type         = (EnergyConsumerType)resourceDescriptions[consumer.ConsumerId].GetProperty(ModelCode.ENERGYCONSUMER_TYPE).AsEnum();
                        consumer.Outages.Clear();

                        this.unitOfWork.ConsumerRepository.Update(consumer);
                    }
                }

                foreach (long gid in modelChangesEnumerable[(byte)DeltaOpType.Insert])
                {
                    ModelCode type = modelResourcesDesc.GetModelCodeFromId(gid);

                    if (type != ModelCode.ENERGYCONSUMER)
                    {
                        continue;
                    }

                    ResourceDescription resourceDescription = resourceDescriptions[gid];

                    if (resourceDescription == null)
                    {
                        Logger.LogWarning($"Consumer with gid 0x{gid:X16} is not in network model");
                        continue;
                    }

                    Consumer consumer = new Consumer
                    {
                        ConsumerId   = resourceDescription.Id,
                        ConsumerMRID = resourceDescription.GetProperty(ModelCode.IDOBJ_MRID).AsString(),
                        FirstName    = resourceDescription.GetProperty(ModelCode.ENERGYCONSUMER_FIRSTNAME).AsString(),
                        LastName     = resourceDescription.GetProperty(ModelCode.ENERGYCONSUMER_LASTNAME).AsString(),
                        Type         = (EnergyConsumerType)resourceDescriptions[resourceDescription.Id].GetProperty(ModelCode.ENERGYCONSUMER_TYPE).AsEnum(),
                    };

                    if (this.unitOfWork.ConsumerRepository.Get(consumer.ConsumerId) == null)
                    {
                        this.unitOfWork.ConsumerRepository.Add(consumer);
                    }
                    else
                    {
                        Logger.LogWarning($"{baseLogString} Prepare => Consumer with gid 0x{consumer.ConsumerId:X16} already exists in DB. Delta Operation: {DeltaOpType.Insert}. Potential fixes: " +
                                          $"{Environment.NewLine}If MongoDB is empty => Delte rows from Consumer Table. " +
                                          $"{Environment.NewLine}If Mongo contains stored NetworkModel => Ignore this warn as it is part of initialization (part of the first distributed transaction).");
                    }
                }

                success = true;
            }
            catch (Exception e)
            {
                string message = $"{baseLogString} Prepare => Exception: {e.Message}";
                Logger.LogError(message, e);
                success = false;
                this.unitOfWork.Dispose();
            }

            return(success);
        }
Example #7
0
        //TAB2
        #region tab2
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            ispis1.Text = string.Empty;
            lista_getExVal.Clear();
            richTextBox2.Text = string.Empty;
            comboBox8.Items.Clear();

            switch (comboBox2.SelectedItem.ToString())
            {
            case "TERMINAL":
                lista_getExVal = gda.GetExtentValues(ModelCode.TERMINAL);
                break;

            case "PHASEIMPENDENCEDATA":
                lista_getExVal = gda.GetExtentValues(ModelCode.PHASEIMPDTA);
                break;

            case "PERLENGTHSEQUENCEIMPEDENCE":
                lista_getExVal = gda.GetExtentValues(ModelCode.PERLNGTSEQIMPD);
                break;

            case "PERLENGTHPHASEIMPEDENCE":
                lista_getExVal = gda.GetExtentValues(ModelCode.PERLNGTPHSIMPD);
                break;

            case "SERIESCOMPENSATOR":
                lista_getExVal = gda.GetExtentValues(ModelCode.SERIESCMPNSTR);
                break;

            case "ACLINESEGMENT":
                lista_getExVal = gda.GetExtentValues(ModelCode.ACLINESGMNT);
                break;

            case "DCLINESEGMENT":
                lista_getExVal = gda.GetExtentValues(ModelCode.DCLINESGMNT);
                break;
            }

            pomocna.Clear();

            foreach (var v in lista_getExVal)
            {
                short type = ModelCodeHelper.ExtractTypeFromGlobalId(v);
                properties = modelRD.GetAllPropertyIds((DMSType)type);
                listaString.Clear();
                foreach (ModelCode p in properties)
                {
                    listaString.Add(p.ToString());
                }
                pomocna.Add(v);
            }

            distinct = listaString.Distinct().ToList();
            foreach (string d in distinct)
            {
                comboBox8.Items.Add(d);
            }

            comboBox8.Enabled = true;
            button4.Enabled   = true;
        }
        private void InitializeEnergyConsumers(UnitOfWork db)
        {
            List <ResourceDescription> energyConsumers = GetExtentValues(ModelCode.ENERGYCONSUMER, modelResourcesDesc.GetAllPropertyIds(ModelCode.ENERGYCONSUMER));

            int i = 0;     //TODO: delete, for first/last name placeholder

            foreach (ResourceDescription energyConsumer in energyConsumers)
            {
                Consumer consumer = new Consumer
                {
                    ConsumerId   = energyConsumer.GetProperty(ModelCode.IDOBJ_GID).AsLong(),
                    ConsumerMRID = energyConsumer.GetProperty(ModelCode.IDOBJ_MRID).AsString(),
                    FirstName    = $"FirstName{i}", //TODO: energyConsumer.GetProperty(ModelCode.ENERGYCONSUMER_FIRSTNAME).AsString();
                    LastName     = $"LastName{i}"   //TODO: energyConsumer.GetProperty(ModelCode.ENERGYCONSUMER_LASTNAME).AsString();
                };


                i++;
                if (db.ConsumerRepository.Get(consumer.ConsumerId) == null)
                {
                    db.ConsumerRepository.Add(consumer);
                    Logger.LogDebug($"Add consumer: {consumer.ConsumerMRID}");
                }
            }



            db.Complete();
            Logger.LogDebug("Init energy consumers: SaveChanges()");
        }
        public async Task <IModelDelta> TryGetAllModelEntitiesAsync()
        {
            string verboseMessage = $"{baseLogString} entering TryGetAllModelEntities method.";

            Logger.LogVerbose(verboseMessage);

            while (!ReliableDictionariesInitialized)
            {
                await Task.Delay(1000);
            }

            ModelDelta modelDelta = new ModelDelta();

            try
            {
                //var clearTasks = new List<Task>
                //{
                await TopologyElements.ClearAsync();

                await Measurements.ClearAsync();

                await EnergySources.ClearAsync();

                await ElementConnections.ClearAsync();

                await MeasurementToConnectedTerminalMap.ClearAsync();

                await TerminalToConnectedElementsMap.ClearAsync();

                await BaseVoltages.ClearAsync();

                await Reclosers.ClearAsync();

                //};

                //Task.WaitAll(clearTasks.ToArray());

                await energySources.SetAsync(ReliableDictionaryNames.EnergySources, new List <long>());

                await reclosers.SetAsync(ReliableDictionaryNames.Reclosers, new HashSet <long>());

                Logger.LogDebug($"{baseLogString} TryGetAllModelEntities => Getting all network model elements and converting them.");

                await GetBaseVoltagesAsync();

                foreach (var model in ConcreteModels)
                {
                    if (model != ModelCode.BASEVOLTAGE)
                    {
                        List <ModelCode> properties = modelResourcesDesc.GetAllPropertyIds(model);
                        var elements = await networkModelGda.GetExtentValuesAsync(model, properties);

                        foreach (var element in elements)
                        {
                            try
                            {
                                await TransformToTopologyElementAsync(element);
                            }
                            catch (Exception e)
                            {
                                Logger.LogError($"{baseLogString} TryGetAllModelEntitiesAsync failed." +
                                                $" {Environment.NewLine} {e.Message} " +
                                                $"{Environment.NewLine} {e.StackTrace}");
                            }
                        }
                    }
                }


                //Parallel.For(0, ConcreteModels.Count, async (i) =>
                //{
                //	var model = ConcreteModels.ElementAt(i);
                //	if (model != ModelCode.BASEVOLTAGE)
                //	{
                //		List<ModelCode> properties = modelResourcesDesc.GetAllPropertyIds(model);
                //		var elements = await networkModelGda.GetExtentValuesAsync(model, properties);
                //		foreach (var element in elements)
                //		{
                //			try
                //			{
                //				await TransformToTopologyElementAsync(element);
                //			}
                //			catch (Exception e)
                //			{
                //				Logger.LogError($"{baseLogString} TryGetAllModelEntitiesAsync failed." +
                //					$" {Environment.NewLine} {e.Message} " +
                //					$"{Environment.NewLine} {e.StackTrace}");
                //			}
                //		}
                //	}
                //});

                var enumerableMeasurements = await Measurements.GetEnumerableDictionaryAsync();

                List <IMeasurement> updatedMeasurements = new List <IMeasurement>(enumerableMeasurements.Count);
                foreach (var measurement in enumerableMeasurements.Values)
                {
                    var elementId = await PutMeasurementsInElements(measurement);

                    var measurementProviderClient = MeasurementProviderClient.CreateClient();
                    await measurementProviderClient.AddMeasurementElementPair(measurement.Id, elementId);

                    updatedMeasurements.Add(measurement);
                }

                foreach (var updatedMeas in updatedMeasurements)
                {
                    await Measurements.SetAsync(updatedMeas.Id, updatedMeas);
                }

                var enumerableTopologyElements = await TopologyElements.GetEnumerableDictionaryAsync();

                List <ITopologyElement> updatedElements = new List <ITopologyElement>(enumerableTopologyElements.Count);
                foreach (var element in enumerableTopologyElements.Values)
                {
                    if (element.Measurements.Count == 0)
                    {
                        await CreateNoScadaMeasurementAsync(element);

                        updatedElements.Add(element);
                    }
                }

                foreach (var updatedEl in updatedElements)
                {
                    await TopologyElements.SetAsync(updatedEl.Id, updatedEl);
                }

                modelDelta.TopologyElements   = enumerableTopologyElements;
                modelDelta.ElementConnections = await ElementConnections.GetEnumerableDictionaryAsync();

                var reclosersResult = await Reclosers.TryGetValueAsync(ReliableDictionaryNames.Reclosers);

                if (reclosersResult.HasValue)
                {
                    modelDelta.Reclosers = reclosersResult.Value;
                }
                else
                {
                    Logger.LogWarning($"{baseLogString} Reliable collection '{ReliableDictionaryNames.Reclosers}' was not defined yet. Handling...");
                    await Reclosers.SetAsync(ReliableDictionaryNames.Reclosers, new HashSet <long>());

                    modelDelta.Reclosers = new HashSet <long>();
                }

                var enegySourcesResult = await EnergySources.TryGetValueAsync(ReliableDictionaryNames.EnergySources);

                if (reclosersResult.HasValue)
                {
                    modelDelta.EnergySources = enegySourcesResult.Value;
                }
                else
                {
                    Logger.LogWarning($"{baseLogString} Reliable collection '{ReliableDictionaryNames.EnergySources}' was not defined yet. Handling...");
                    await EnergySources.SetAsync(ReliableDictionaryNames.EnergySources, new List <long>());

                    modelDelta.EnergySources = new List <long>();
                }
            }
            catch (Exception e)
            {
                string message = $"{baseLogString} TryGetAllModelEntities => Failed in get all network model elements." +
                                 $"{Environment.NewLine} Exception message: {e.Message}" +
                                 $"{Environment.NewLine} Stack trace: {e.StackTrace}";
                Logger.LogError(message);
                throw new Exception(message);
            }

            return(modelDelta);
        }
        private async Task <Dictionary <long, IScadaModelPointItem> > CreatePointItemsFromNetworkModelMeasurements(Dictionary <byte, List <long> > modelChanges)
        {
            Dictionary <long, IScadaModelPointItem> pointItems = new Dictionary <long, IScadaModelPointItem>();

            INetworkModelGDAContract nmsGdaClient = NetworkModelGdaClient.CreateClient();

            int iteratorId;
            int resourcesLeft;
            int numberOfResources = 10000;

            List <ModelCode> props;

            //TOOD: change service contract IModelUpdateNotificationContract to receive types of all changed elements from NMS
            var changedTypesHashSet = new HashSet <ModelCode>();

            foreach (var gids in modelChanges.Values)
            {
                foreach (var gid in gids)
                {
                    ModelCode type = modelResourceDesc.GetModelCodeFromId(gid);
                    changedTypesHashSet.Add(type);
                }
            }

            foreach (ModelCode type in changedTypesHashSet)
            {
                if (type != ModelCode.ANALOG && type != ModelCode.DISCRETE)
                {
                    continue;
                }

                props = modelResourceDesc.GetAllPropertyIds(type);

                try
                {
                    iteratorId = await nmsGdaClient.GetExtentValues(type, props);

                    resourcesLeft = await nmsGdaClient.IteratorResourcesLeft(iteratorId);

                    while (resourcesLeft > 0)
                    {
                        List <ResourceDescription> resources = await nmsGdaClient.IteratorNext(numberOfResources, iteratorId);

                        foreach (ResourceDescription rd in resources)
                        {
                            if (pointItems.ContainsKey(rd.Id))
                            {
                                string message = $"{baseLogString} CreatePointItemsFromNetworkModelMeasurements => Trying to create point item for resource that already exists in model. Gid: 0x{rd.Id:X16}";
                                Logger.LogError(message);
                                throw new ArgumentException(message);
                            }

                            IScadaModelPointItem point;

                            //change service contract IModelUpdateNotificationContract => change List<long> to Hashset<long>
                            if (modelChanges[(byte)DeltaOpType.Update].Contains(rd.Id) || modelChanges[(byte)DeltaOpType.Insert].Contains(rd.Id))
                            {
                                point = CreatePointItemFromResource(rd);
                                pointItems.Add(rd.Id, point);
                            }
                        }

                        resourcesLeft = await nmsGdaClient.IteratorResourcesLeft(iteratorId);
                    }

                    await nmsGdaClient.IteratorClose(iteratorId);
                }
                catch (Exception ex)
                {
                    string errorMessage = $"{baseLogString} CreatePointItemsFromNetworkModelMeasurements => Failed with error: {ex.Message}";
                    Logger.LogError(errorMessage, ex);
                }
            }

            return(pointItems);
        }
        private async Task <bool> ImportAnalog()
        {
            bool             success;
            int              numberOfResources = 1000;
            List <ModelCode> props             = modelResourceDesc.GetAllPropertyIds(ModelCode.ANALOG);

            try
            {
                var nmsGdaClient = NetworkModelGdaClient.CreateClient();
                int iteratorId   = await nmsGdaClient.GetExtentValues(ModelCode.ANALOG, props);

                int resourcesLeft = await nmsGdaClient.IteratorResourcesLeft(iteratorId);

                while (resourcesLeft > 0)
                {
                    List <ResourceDescription> rds = await nmsGdaClient.IteratorNext(numberOfResources, iteratorId);

                    for (int i = 0; i < rds.Count; i++)
                    {
                        if (rds[i] == null)
                        {
                            continue;
                        }

                        long      gid  = rds[i].Id;
                        ModelCode type = modelResourceDesc.GetModelCodeFromId(gid);

                        AnalogPointItem analogPoint = new AnalogPointItem(AlarmConfigDataHelper.GetAlarmConfigData());

                        string debugMessage = $"{baseLogString} ImportAnalog => Before Initialization => Gid: 0x{analogPoint.Gid:X16}, Address: {analogPoint.Address}, CurrentRawValue: {analogPoint.CurrentRawValue}, Alarm: {analogPoint.Alarm}, ScalingFactor: {analogPoint.ScalingFactor}, Deviation: {analogPoint.Deviation}, MinRawValue: {analogPoint.MinRawValue}, MaxRawValue: {analogPoint.MaxRawValue}, NormalValue: {analogPoint.NormalValue}, RegisterType: {analogPoint.RegisterType}, Name: {analogPoint.Name}, Initialized: {analogPoint.Initialized}";
                        Logger.LogDebug(debugMessage);

                        pointItemHelper.InitializeAnalogPointItem(analogPoint, rds[i].Properties, ModelCode.ANALOG, enumDescs);

                        debugMessage = $"{baseLogString} ImportAnalog => After Initialization => Gid: 0x{analogPoint.Gid:X16}, Address: {analogPoint.Address}, CurrentRawValue: {analogPoint.CurrentRawValue}, Alarm: {analogPoint.Alarm}, ScalingFactor: {analogPoint.ScalingFactor}, Deviation: {analogPoint.Deviation}, MinRawValue: {analogPoint.MinRawValue}, MaxRawValue: {analogPoint.MaxRawValue}, NormalValue: {analogPoint.NormalValue}, RegisterType: {analogPoint.RegisterType}, Name: {analogPoint.Name}, Initialized: {analogPoint.Initialized}";
                        Logger.LogDebug(debugMessage);

                        if (await GidToPointItemMap.ContainsKeyAsync(gid))
                        {
                            string errorMessage = $"{baseLogString} ImportAnalog => SCADA model is invalid => Gid: 0x{gid:16} belongs to more than one entity.";
                            Logger.LogError(errorMessage);
                            throw new InternalSCADAServiceException(errorMessage);
                        }

                        await GidToPointItemMap.SetAsync(gid, analogPoint);

#if DEBUG
                        var pointItemResult = await GidToPointItemMap.TryGetValueAsync(gid);

                        if (pointItemResult.HasValue)
                        {
                            AnalogPointItem controlPointItem = pointItemResult.Value as AnalogPointItem;
                            debugMessage = $"{baseLogString} ImportAnalog => Control after CurrentGidToPointItemMap.SetAsync => Gid: 0x{controlPointItem.Gid:X16}, Address: {controlPointItem.Address}, CurrentRawValue: {controlPointItem.CurrentRawValue}, Alarm: {controlPointItem.Alarm}, ScalingFactor: {controlPointItem.ScalingFactor}, Deviation: {controlPointItem.Deviation}, MinRawValue: {controlPointItem.MinRawValue}, MaxRawValue: {controlPointItem.MaxRawValue}, NormalValue: {controlPointItem.NormalValue}, RegisterType: {controlPointItem.RegisterType}, Name: {controlPointItem.Name}, Initialized: {controlPointItem.Initialized}";
                            Logger.LogDebug(debugMessage);
                        }
                        else
                        {
                            string warningMessage = $"{baseLogString} ImportAnalog => Control after CurrentGidToPointItemMap.SetAsync => Gid: 0x{gid:X16} was not found in reliable collection '{ReliableDictionaryNames.GidToPointItemMap}' after the value was supposedly set.";
                            Logger.LogWarning(warningMessage);
                        }
#endif

                        short registerType = (short)analogPoint.RegisterType;
                        if (!(await AddressToGidMap.ContainsKeyAsync(registerType)))
                        {
                            await AddressToGidMap.SetAsync(registerType, new Dictionary <ushort, long>());
                        }

                        var addressToGidDictionaryResult = await AddressToGidMap.TryGetValueAsync(registerType);

                        if (!addressToGidDictionaryResult.HasValue)
                        {
                            string message = $"{baseLogString} ImportAnalog => reliable collection '{ReliableDictionaryNames.AddressToGidMap}' is not initialized properly.";
                            Logger.LogError(message);
                            throw new InternalSCADAServiceException(message);
                        }

                        var addressToGidDictionary = addressToGidDictionaryResult.Value;

                        if (addressToGidDictionary.ContainsKey(analogPoint.Address))
                        {
                            string message = $"{baseLogString} ImportAnalog => SCADA model is invalid => Address: {analogPoint.Address} (RegType: {registerType}) belongs to more than one entity.";
                            Logger.LogError(message);
                            throw new InternalSCADAServiceException(message);
                        }

                        addressToGidDictionary.Add(analogPoint.Address, rds[i].Id);
                        await AddressToGidMap.SetAsync(registerType, addressToGidDictionary);

                        debugMessage = $"{baseLogString} ImportAnalog => ANALOG measurement added to SCADA model [Gid: 0x{gid:X16}, Address: {analogPoint.Address}]";
                        Logger.LogDebug(debugMessage);
                    }

                    resourcesLeft = await nmsGdaClient.IteratorResourcesLeft(iteratorId);
                }

                await nmsGdaClient.IteratorClose(iteratorId);

                success = true;
            }
            catch (Exception ex)
            {
                success = false;
                string errorMessage = $"{baseLogString} ImportAnalog => failed with error: {ex.Message}";
                Trace.WriteLine(errorMessage);
                Logger.LogError(errorMessage, ex);
            }

            return(success);
        }