public void ReadFromResourceDescription(ResourceDescription rd)
 {
     try { this.GID = rd.GetProperty(ModelCode.IDOBJ_GID).AsLong(); } catch { }
     try { this.MRID = rd.GetProperty(ModelCode.IDOBJ_MRID).AsString(); } catch { }
     try { this.Name = rd.GetProperty(ModelCode.IDOBJ_NAME).AsString(); } catch { }
     try { this.Psr = rd.GetProperty(ModelCode.MEASUREMENT_PSR).AsLong(); } catch { }
 }
        private async Task <List <long> > GetAllReferencedElements(ResourceDescription element)
        {
            string verboseMessage = $"{baseLogString} entering GetAllReferencedElements method.";

            Logger.LogVerbose(verboseMessage);

            List <long> elements = new List <long>();
            DMSType     type     = GetDMSTypeOfTopologyElement(element.Id);

            foreach (var property in GetAllReferenceProperties(type))
            {
                if (property == ModelCode.POWERTRANSFORMER_TRANSFORMERWINDINGS ||
                    property == ModelCode.CONDUCTINGEQUIPMENT_TERMINALS ||
                    property == ModelCode.CONNECTIVITYNODE_TERMINALS ||
                    property == ModelCode.BASEVOLTAGE_CONDUCTINGEQUIPMENTS ||
                    property == ModelCode.TERMINAL_MEASUREMENTS)
                {
                    elements.AddRange(element.GetProperty(property).AsReferences());
                }
                else
                {
                    var elementGid = element.GetProperty(property).AsReference();
                    if (elementGid != 0)
                    {
                        elements.Add(elementGid);
                    }
                }
            }

            if (type == DMSType.TERMINAL)
            {
                await TerminalToConnectedElementsMap.SetAsync(element.Id, new List <long>(elements));
            }
            return(elements);
        }
Beispiel #3
0
        private void AddBranch(Dictionary <long, ResourceDescription> cimTerminals, Dictionary <long, MPBranch> branches, Dictionary <long, MPNode> nodes, long branchId, List <long> terminalsID)
        {
            if (terminalsID.Count < 1)
            {
                string message = "Invalid CIM model. Connectivity node must have at least one terminal";
                Logger.LogError(message);
                throw new Exception(message);
            }
            //TODO: za sada, slucaj kada ima vise
            ResourceDescription firstTerminal  = cimTerminals[terminalsID[0]];
            ResourceDescription secondTerminal = cimTerminals[terminalsID[1]];

            EPhaseCode phaseCode    = (EPhaseCode)firstTerminal.GetProperty(ModelCode.TERMINAL_PHASES).AsEnum();
            long       firstNodeId  = firstTerminal.GetProperty(ModelCode.TERMINAL_CONNECTIVITYNODE).AsLong();
            long       secondNodeId = secondTerminal.GetProperty(ModelCode.TERMINAL_CONNECTIVITYNODE).AsLong();

            if (nodes.ContainsKey(firstNodeId) && nodes.ContainsKey(secondNodeId))
            {
                MPLine branch = new MPLine(branchId, phaseCode, firstNodeId, secondNodeId);

                branches.Add(branchId, branch);
            }
            else
            {
                string message = $"Invalid CIM model. There is(are) not node(s) with specific lid(s). First node: {firstNodeId}, Second node {secondNodeId}";
                Logger.LogError(message);
                throw new Exception(message);
            }
        }
Beispiel #4
0
 public new void ReadFromResourceDescription(ResourceDescription rd)
 {
     try { this.Value = rd.GetProperty(ModelCode.ANALOG_NORMVAL).AsFloat(); } catch { }
     try { this.MeasurementType = rd.GetProperty(ModelCode.MEASUREMENT_TYPE).AsString(); } catch { }
     try { this.UnitSymbol = (UnitSymbol)rd.GetProperty(ModelCode.MEASUREMENT_UNITSYMB).AsEnum(); } catch { }
     base.ReadFromResourceDescription(rd);
 }
        private List <long> GetAllReferencedElements(ResourceDescription element)
        {
            List <long> elements = new List <long>();
            DMSType     type     = GetDMSTypeOfTopologyElement(element.Id);

            foreach (var property in GetAllReferenceProperties(type))
            {
                if (property == ModelCode.POWERTRANSFORMER_TRANSFORMERWINDINGS ||
                    property == ModelCode.CONDUCTINGEQUIPMENT_TERMINALS ||
                    property == ModelCode.CONNECTIVITYNODE_TERMINALS ||
                    property == ModelCode.BASEVOLTAGE_CONDUCTINGEQUIPMENTS ||
                    property == ModelCode.TERMINAL_MEASUREMENTS)
                {
                    elements.AddRange(element.GetProperty(property).AsReferences());
                }
                else
                {
                    var elementGid = element.GetProperty(property).AsReference();
                    if (elementGid != 0)
                    {
                        elements.Add(elementGid);
                    }
                }
            }

            if (type == DMSType.TERMINAL)
            {
                TerminalToConnectedElementsMap.Add(element.Id, new List <long>(elements));
            }
            return(elements);
        }
        public bool CheckIfBreakerIsRecloser(long elementId)
        {
            bool isRecloser = false;

            try
            {
                using (NetworkModelGDAProxy gda = proxyFactory.CreateProxy <NetworkModelGDAProxy, INetworkModelGDAContract>(EndpointNames.NetworkModelGDAEndpoint))
                {
                    ResourceDescription resourceDescription = gda.GetValues(elementId, new List <ModelCode>()
                    {
                        ModelCode.BREAKER_NORECLOSING
                    });

                    Property property = resourceDescription.GetProperty(ModelCode.BREAKER_NORECLOSING);

                    if (property != null)
                    {
                        isRecloser = !property.AsBool();
                    }
                    else
                    {
                        throw new Exception($"Element with id 0x{elementId:X16} is not a breaker.");
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return(isRecloser);
        }
Beispiel #7
0
        public void ReadConnectivityNodes(Dictionary <long, ResourceDescription> cimConnNodes, Dictionary <long, ResourceDescription> cimTerminals)
        {
            Dictionary <long, MPNode> nodes = internalModel.Nodes;


            foreach (ResourceDescription node in cimConnNodes.Values)
            {
                if (!nodes.ContainsKey(node.Id))
                {
                    //TODO: svi treba da imaju istu faznost
                    List <long> terminalsID = node.GetProperty(ModelCode.CONNECTIVITYNODE_TERMINALS).AsReferences();

                    if (terminalsID.Count < 1)
                    {
                        string message = "Invalid CIM model. Connectivity node must have at least one terminal";
                        Logger.LogError(message);
                        throw new Exception(message);
                    }
                    ResourceDescription firstTerminal = cimTerminals[terminalsID[0]];
                    EPhaseCode          phaseCode     = (EPhaseCode)firstTerminal.GetProperty(ModelCode.TERMINAL_PHASES).AsEnum();

                    MPBusNode newNode = new MPBusNode(node.Id, phaseCode);

                    nodes.Add(node.Id, newNode);
                }
                else
                {
                    string errMessage = $"Invalid CIM model. There is already node with same key: {node.Id:X16}";
                    Logger.LogError(errMessage);
                    throw new Exception(errMessage);
                }
            }

            isNodesInitialized = true;
        }
        private async Task <AnalogMeasurement> GetPopulatedAnalogMeasurement(ResourceDescription rs)
        {
            string verboseMessage = $"{baseLogString} entering GetPopulatedAnalogMeasurement method.";

            Logger.LogVerbose(verboseMessage);

            AnalogMeasurement measurement = new AnalogMeasurement();

            try
            {
                measurement.Id            = rs.Id;
                measurement.Address       = rs.GetProperty(ModelCode.MEASUREMENT_ADDRESS).AsString();
                measurement.IsInput       = rs.GetProperty(ModelCode.MEASUREMENT_ISINPUT).AsBool();
                measurement.CurrentValue  = rs.GetProperty(ModelCode.ANALOG_CURRENTVALUE).AsFloat();
                measurement.MaxValue      = rs.GetProperty(ModelCode.ANALOG_MAXVALUE).AsFloat();
                measurement.MinValue      = rs.GetProperty(ModelCode.ANALOG_MINVALUE).AsFloat();
                measurement.NormalValue   = rs.GetProperty(ModelCode.ANALOG_NORMALVALUE).AsFloat();
                measurement.Deviation     = rs.GetProperty(ModelCode.ANALOG_DEVIATION).AsFloat();
                measurement.ScalingFactor = rs.GetProperty(ModelCode.ANALOG_SCALINGFACTOR).AsFloat();
                measurement.SignalType    = (AnalogMeasurementType)rs.GetProperty(ModelCode.ANALOG_SIGNALTYPE).AsEnum();

                var connection = await GetAllReferencedElements(rs);

                if (connection.Count < 0)
                {
                    Logger.LogError($"{baseLogString} GetPopulatedAnalogMeasurement => Analog measurement with GID: {rs.Id:X16} is not connected to any element.");
                }
                else if (connection.Count > 1)
                {
                    Logger.LogWarning($"{baseLogString} GetPopulatedAnalogMeasurement => Analog measurement with GID: {rs.Id:X16} is connected to more then one element.");

                    if (!await MeasurementToConnectedTerminalMap.ContainsKeyAsync(rs.Id))
                    {
                        await MeasurementToConnectedTerminalMap.SetAsync(rs.Id, connection.First());
                    }
                }
                else
                {
                    if (!await MeasurementToConnectedTerminalMap.ContainsKeyAsync(rs.Id))
                    {
                        await MeasurementToConnectedTerminalMap.SetAsync(rs.Id, connection.First());
                    }
                }
            }
            catch (Exception e)
            {
                Logger.LogError($"{baseLogString} GetPopulatedAnalogMeasurement => Failed to populate analog measurement with GID {rs.Id:X16}." +
                                $"{Environment.NewLine} Exception message: {e.Message}" +
                                $"{Environment.NewLine} Stack trace: {e.StackTrace}");
            }
            return(measurement);
        }
Beispiel #9
0
        public void ReadSwitches(Dictionary <long, ResourceDescription> cimSwitches, Dictionary <long, ResourceDescription> cimTerminals)
        {
            if (!isRootsInitialized || !isBranchesInitialized || !isNodesInitialized)
            {
                return;
            }

            Dictionary <long, MPBranch>       branches = internalModel.Branches;
            Dictionary <long, MPNode>         nodes    = internalModel.Nodes;
            Dictionary <long, MPSwitchDevice> switches = internalModel.SwitchDevices;

            foreach (ResourceDescription cimSwitch in cimSwitches.Values)
            {
                long switchId = cimSwitch.Id;
                if (!branches.ContainsKey(switchId))
                {
                    List <long> terminalsID = cimSwitch.GetProperty(ModelCode.CONDEQ_TERMINALS).AsReferences();
                    AddBranch(cimTerminals, branches, nodes, switchId, terminalsID);
                    if (!switches.ContainsKey(switchId))
                    {
                        ResourceDescription firstTerminal = cimTerminals[terminalsID[0]];
                        long       nodeId       = firstTerminal.GetProperty(ModelCode.TERMINAL_CONNECTIVITYNODE).AsReference();
                        EPhaseCode switchPhases = (EPhaseCode)firstTerminal.GetProperty(ModelCode.TERMINAL_PHASES).AsEnum();
                        EPhaseCode switchState  = GetSwitchState(switchPhases, cimSwitch.GetProperty(ModelCode.SWITCH_NORMALOPEN).AsBool());

                        MPSwitchDevice newSwitch = new MPSwitchDevice(switchId, switchId, nodeId, switchPhases, switchState);

                        switches.Add(switchId, newSwitch);
                    }
                    else
                    {
                        string errMessage = $"Switch with id {switchId} already exists in intenal model.";
                        Logger.LogError(errMessage);
                        throw new Exception(errMessage);
                    }
                }
                else
                {
                    string errMessage = $"Switch (branch) with id {switchId} already exists in intenal model.";
                    Logger.LogError(errMessage);
                    throw new Exception(errMessage);
                }
            }

            isSwitchesInitialized = true;
        }
 public new void ReadFromResourceDescription(ResourceDescription rd)
 {
     try
     {
         var temp = rd.GetProperty(ModelCode.DISCRETE_NORMVAL).AsInt();
         this.State = (OMSSCADACommon.States)Enum.GetValues(typeof(OMSSCADACommon.States)).GetValue(temp);
     } catch { }
     base.ReadFromResourceDescription(rd);
 }
Beispiel #11
0
        public void ReadSources(Dictionary <long, ResourceDescription> cimSources, Dictionary <long, ResourceDescription> cimTerminals)
        {
            Dictionary <long, MPNode>   nodes    = internalModel.Nodes;
            Dictionary <long, MPRoot>   roots    = internalModel.Roots;
            Dictionary <long, MPBranch> branches = internalModel.Branches;

            foreach (ResourceDescription source in cimSources.Values)
            {
                long        rootId      = source.Id;
                List <long> terminalsID = source.GetProperty(ModelCode.CONDEQ_TERMINALS).AsReferences();

                if (terminalsID.Count < 1)
                {
                    string message = "Invalid CIM model. Root must have at least one terminal";
                    Logger.LogError(message);
                    throw new Exception(message);
                }
                //TODO: svi treba da imaju istu faznost
                ResourceDescription firstTerminal = cimTerminals[terminalsID[0]];

                EPhaseCode phaseCode = (EPhaseCode)firstTerminal.GetProperty(ModelCode.TERMINAL_PHASES).AsEnum();
                if (nodes.ContainsKey(rootId))
                {
                    string message = $"Bad input file. There is already root node with specific gid ({rootId:X16}).";
                    Logger.LogError(message);
                    throw new Exception(message);
                }

                if (!roots.ContainsKey(rootId))
                {
                    MPRootNode rootNode = new MPRootNode(rootId, rootId, phaseCode);
                    nodes.Add(rootId, rootNode);

                    MPRoot root = new MPRoot(rootId, rootId);
                    roots.Add(rootId, root);

                    long     rootConnNode = firstTerminal.GetProperty(ModelCode.TERMINAL_CONNECTIVITYNODE).AsReference();
                    MPBranch rootBranch   = new MPLine(rootId, phaseCode, rootId, rootConnNode);
                    branches.Add(rootId, rootBranch);
                }
            }

            isRootsInitialized = true;
        }
Beispiel #12
0
        public bool Prepare()
        {
            bool success = false;

            transactionDbContext = new UnitOfWork();
            Dictionary <long, ResourceDescription> resourceDescriptions = GetExtentValues(ModelCode.ENERGYCONSUMER, modelResourcesDesc.GetAllPropertyIds(ModelCode.ENERGYCONSUMER));

            List <Consumer> consumerDbEntities = transactionDbContext.ConsumerRepository.GetAll().ToList();

            foreach (Consumer consumer in consumerDbEntities)
            {
                if (modelChanges[DeltaOpType.Delete].Contains(consumer.ConsumerId))
                {
                    transactionDbContext.ConsumerRepository.Remove(consumer);
                }
                else if (modelChanges[DeltaOpType.Update].Contains(consumer.ConsumerId))
                {
                    consumer.ConsumerMRID = resourceDescriptions[consumer.ConsumerId].GetProperty(ModelCode.IDOBJ_MRID).AsString(); //TODO other prop, when added in model
                }
            }

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

                if (type == ModelCode.ENERGYCONSUMER)
                {
                    ResourceDescription resourceDescription = resourceDescriptions[gid];

                    if (resourceDescription != null)
                    {
                        Consumer consumer = new Consumer
                        {
                            ConsumerId   = resourceDescription.Id,
                            ConsumerMRID = resourceDescription.GetProperty(ModelCode.IDOBJ_MRID).AsString(),
                            FirstName    = "Added",   //TODO: resourceDescription.GetProperty(ModelCode.ENERGYCONSUMER_FIRSTNAME).AsString()
                            LastName     = "Consumer" //TODO: resourceDescription.GetProperty(ModelCode.ENERGYCONSUMER_LASTNAME).AsString() other prop, when added in model
                        };

                        transactionDbContext.ConsumerRepository.Add(consumer);
                    }
                    else
                    {
                        Logger.LogWarn($"Consumer with gid 0x{gid:X16} is not in network model");
                    }
                }
            }

            success = true;

            return(success);
        }
Beispiel #13
0
 private bool CompareResourceDescriptions(ResourceDescription rd1, ResourceDescription rd2)
 {
     foreach (var prop in rd1.Properties)
     {
         var rd2prop = rd2.GetProperty(prop.Id);
         if (rd2prop != null)
         {
             if (!rd2prop.PropertyValue.Equals(prop.PropertyValue))
             {
                 return(true);
             }
         }
     }
     return(false);
 }
        private async Task <DiscreteMeasurement> GetPopulatedDiscreteMeasurement(ResourceDescription rs)
        {
            string verboseMessage = $"{baseLogString} entering GetPopulatedDiscreteMeasurement method.";

            Logger.LogVerbose(verboseMessage);

            DiscreteMeasurement measurement = new DiscreteMeasurement();

            try
            {
                measurement.Id              = rs.Id;
                measurement.Address         = rs.GetProperty(ModelCode.MEASUREMENT_ADDRESS).AsString();
                measurement.IsInput         = rs.GetProperty(ModelCode.MEASUREMENT_ISINPUT).AsBool();
                measurement.CurrentOpen     = rs.GetProperty(ModelCode.DISCRETE_CURRENTOPEN).AsBool();
                measurement.MaxValue        = rs.GetProperty(ModelCode.DISCRETE_MAXVALUE).AsInt();
                measurement.MinValue        = rs.GetProperty(ModelCode.DISCRETE_MINVALUE).AsInt();
                measurement.NormalValue     = rs.GetProperty(ModelCode.DISCRETE_NORMALVALUE).AsInt();
                measurement.MeasurementType = (DiscreteMeasurementType)rs.GetProperty(ModelCode.DISCRETE_MEASUREMENTTYPE).AsEnum();

                var connection = await GetAllReferencedElements(rs);

                if (connection.Count < 0)
                {
                    Logger.LogError($"{baseLogString} GetPopulatedDiscreteMeasurement => Discrete measurement with GID {rs.Id:X16} is not connected to any element.");
                }
                else if (connection.Count > 1)
                {
                    Logger.LogWarning($"{baseLogString} GetPopulatedDiscreteMeasurement => Discrete measurement with GID {rs.Id:X16} is connected to more then one element.");
                    if (!await MeasurementToConnectedTerminalMap.ContainsKeyAsync(rs.Id))
                    {
                        await MeasurementToConnectedTerminalMap.SetAsync(rs.Id, connection.First());
                    }
                }
                else
                {
                    if (!await MeasurementToConnectedTerminalMap.ContainsKeyAsync(rs.Id))
                    {
                        await MeasurementToConnectedTerminalMap.SetAsync(rs.Id, connection.First());
                    }
                }
            }
            catch (Exception e)
            {
                Logger.LogError($"[NMSManager] Failed to populate discrete measurement with GID: {rs.Id:X16}." +
                                $"{Environment.NewLine} Exception message: {e.Message}" +
                                $"{Environment.NewLine} Stack trace: {e.StackTrace}");
            }
            return(measurement);
        }
        private AnalogMeasurement GetPopulatedAnalogMeasurement(ResourceDescription rs)
        {
            AnalogMeasurement measurement = new AnalogMeasurement();

            try
            {
                measurement.Id            = rs.Id;
                measurement.Address       = rs.GetProperty(ModelCode.MEASUREMENT_ADDRESS).AsString();
                measurement.IsInput       = rs.GetProperty(ModelCode.MEASUREMENT_ISINPUT).AsBool();
                measurement.CurrentValue  = rs.GetProperty(ModelCode.ANALOG_CURRENTVALUE).AsFloat();
                measurement.MaxValue      = rs.GetProperty(ModelCode.ANALOG_MAXVALUE).AsFloat();
                measurement.MinValue      = rs.GetProperty(ModelCode.ANALOG_MINVALUE).AsFloat();
                measurement.NormalValue   = rs.GetProperty(ModelCode.ANALOG_NORMALVALUE).AsFloat();
                measurement.Deviation     = rs.GetProperty(ModelCode.ANALOG_DEVIATION).AsFloat();
                measurement.ScalingFactor = rs.GetProperty(ModelCode.ANALOG_SCALINGFACTOR).AsFloat();
                measurement.SignalType    = (AnalogMeasurementType)rs.GetProperty(ModelCode.ANALOG_SIGNALTYPE).AsEnum();

                var connection = GetAllReferencedElements(rs);
                if (connection.Count < 0)
                {
                    logger.LogWarn($"Analog measurement with GID: 0x{rs.Id:X16} is not connected to any element.");
                }
                else if (connection.Count > 1)
                {
                    logger.LogWarn($"Analog measurement with GID: 0x{rs.Id:X16} is connected to more then one element.");
                    MeasurementToConnectedTerminalMap.Add(rs.Id, connection.First());
                }
                else
                {
                    MeasurementToConnectedTerminalMap.Add(rs.Id, connection.First());
                }
            }
            catch (Exception)
            {
                logger.LogDebug($"Failed to populate analog measurement with GID: 0x{rs.Id:X16}.");
            }
            return(measurement);
        }
        public void ChangeOnSCADAAnalog(string mrID, float value)
        {
            ModelGdaDMS gda = new ModelGdaDMS();

            List <ResourceDescription> analogMeasurements = gda.GetExtentValuesExtended(ModelCode.ANALOG);
            ResourceDescription        rdDMeasurement     = analogMeasurements.Where(r => r.GetProperty(ModelCode.IDOBJ_MRID).AsString() == mrID).FirstOrDefault();

            // if measurement exists here! if result is null it exists only on scada, but not in .data
            if (rdDMeasurement != null)
            {
                long measGid = rdDMeasurement.GetProperty(ModelCode.IDOBJ_GID).AsLong();


                // to do: cuvanje u bazi promene za analogne, bla bla. Inicijalno uopste nije bilo planirano da se propagiraju promene za analogne,
                // receno je da te vrednosti samo zakucamo :D, zato tu implementaciju ostavljam za svetlu buducnost!

                // ovde sad mogu neke kalkulacije opasne da se racunaju, kao ako je ta neka vrednost to se npr. ne uklapa sa
                // izracunatom vrednoscu za taj customer..ma bla bla...to nama ne treba xD

                List <UIUpdateModel> networkChange = new List <UIUpdateModel>();
                networkChange.Add(new UIUpdateModel()
                {
                    Gid = measGid, AnValue = value
                });

                Publisher publisher = new Publisher();
                if (networkChange.Count > 0)
                {
                    publisher.PublishUpdateAnalog(networkChange);
                }
            }
            else
            {
                Console.WriteLine("ChangeOnScada()-> element with mrid={0} do not exist in OMS.", mrID);
            }
        }
        private DiscreteMeasurement GetPopulatedDiscreteMeasurement(ResourceDescription rs)
        {
            DiscreteMeasurement measurement = new DiscreteMeasurement();

            try
            {
                measurement.Id              = rs.Id;
                measurement.Address         = rs.GetProperty(ModelCode.MEASUREMENT_ADDRESS).AsString();
                measurement.IsInput         = rs.GetProperty(ModelCode.MEASUREMENT_ISINPUT).AsBool();
                measurement.CurrentOpen     = rs.GetProperty(ModelCode.DISCRETE_CURRENTOPEN).AsBool();
                measurement.MaxValue        = rs.GetProperty(ModelCode.DISCRETE_MAXVALUE).AsInt();
                measurement.MinValue        = rs.GetProperty(ModelCode.DISCRETE_MINVALUE).AsInt();
                measurement.NormalValue     = rs.GetProperty(ModelCode.DISCRETE_NORMALVALUE).AsInt();
                measurement.MeasurementType = (DiscreteMeasurementType)rs.GetProperty(ModelCode.DISCRETE_MEASUREMENTTYPE).AsEnum();

                var connection = GetAllReferencedElements(rs);
                if (connection.Count < 0)
                {
                    logger.LogWarn($"[NMSManager] Discrete measurement with GID: 0x{rs.Id:X16} is not connected to any element.");
                }
                else if (connection.Count > 1)
                {
                    logger.LogWarn($"[NMSManager] Discrete measurement with GID: 0x{rs.Id:X16} is connected to more then one element.");
                    MeasurementToConnectedTerminalMap.Add(rs.Id, connection.First());
                }
                else
                {
                    MeasurementToConnectedTerminalMap.Add(rs.Id, connection.First());
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"[NMSManager] Failed to populate discrete measurement with GID: 0x{rs.Id:X16}. Exception message: {ex.Message}");
            }
            return(measurement);
        }
        public void ChangeOnSCADADigital(string mrID, OMSSCADACommon.States state)
        {
            ModelGdaDMS gda = new ModelGdaDMS();

            List <ResourceDescription> discreteMeasurements = gda.GetExtentValuesExtended(ModelCode.DISCRETE);
            ResourceDescription        rdDMeasurement       = discreteMeasurements.Where(r => r.GetProperty(ModelCode.IDOBJ_MRID).AsString() == mrID).FirstOrDefault();

            // if measurement exists here! if result is null it exists only on scada, but not in .data
            if (rdDMeasurement != null)
            {
                // find PSR element associated with measurement
                long rdAssociatedPSR = rdDMeasurement.GetProperty(ModelCode.MEASUREMENT_PSR).AsLong();

                List <UIUpdateModel> networkChange = new List <UIUpdateModel>();

                Element DMSElementWithMeas;
                Console.WriteLine("Change on scada Digital Instance.Tree");
                DMSService.Instance.Tree.Data.TryGetValue(rdAssociatedPSR, out DMSElementWithMeas);
                Switch sw = DMSElementWithMeas as Switch;

                if (sw != null)
                {
                    bool           isIncident = false;
                    IncidentReport incident   = new IncidentReport()
                    {
                        MrID = sw.MRID
                    };
                    incident.Crewtype = CrewType.Investigation;

                    ElementStateReport elementStateReport = new ElementStateReport()
                    {
                        MrID = sw.MRID, Time = DateTime.UtcNow, State = (int)state
                    };

                    if (state == OMSSCADACommon.States.OPENED)
                    {
                        isIncident = true;

                        sw.Incident = true;
                        sw.State    = SwitchState.Open;
                        sw.Marker   = false;
                        networkChange.Add(new UIUpdateModel(sw.ElementGID, false, OMSSCADACommon.States.OPENED));

                        // treba mi objasnjenje sta se ovde radi? ne kotnam ove ScadaupdateModele sta se kad gde dodaje, sta je sta
                        // uopste, summary iznad tih propertija u dms modelu
                        Node n = (Node)DMSService.Instance.Tree.Data[sw.End2];
                        n.Marker = false;
                        networkChange.Add(new UIUpdateModel(n.ElementGID, false));
                        // pojasnjenje mi treba, komentari u ovom algoritmu i slicno, da ne debagujem sve redom, nemam vremena sad za to xD
                        networkChange = EnergizationAlgorithm.TraceDown(n, networkChange, false, false, DMSService.Instance.Tree);
                    }
                    else if (state == OMSSCADACommon.States.CLOSED)
                    {
                        sw.Incident   = false;
                        sw.CanCommand = false;
                        sw.State      = SwitchState.Closed;

                        // i ovde takodje pojasnjenje
                        if (EnergizationAlgorithm.TraceUp((Node)DMSService.Instance.Tree.Data[sw.End1], DMSService.Instance.Tree))
                        {
                            networkChange.Add(new UIUpdateModel(sw.ElementGID, true, OMSSCADACommon.States.CLOSED));
                            sw.Marker = true;

                            Node n = (Node)DMSService.Instance.Tree.Data[sw.End2];
                            n.Marker = true;
                            networkChange.Add(new UIUpdateModel(n.ElementGID, true));
                            networkChange = EnergizationAlgorithm.TraceDown(n, networkChange, true, false, DMSService.Instance.Tree);
                        }
                        else
                        {
                            networkChange.Add(new UIUpdateModel(sw.ElementGID, false, OMSSCADACommon.States.CLOSED));
                        }
                    }

                    //do
                    //{
                    //    try
                    //    {
                    //        if (IMSClient.State == CommunicationState.Created)
                    //        {
                    //            IMSClient.Open();
                    //        }

                    //        if (IMSClient.Ping())
                    //            break;
                    //    }
                    //    catch (Exception e)
                    //    {
                    //        //Console.WriteLine(e);
                    //        Console.WriteLine("ProcessCrew() -> IMS is not available yet.");
                    //        if (IMSClient.State == CommunicationState.Faulted)
                    //        {
                    //            NetTcpBinding binding = new NetTcpBinding();
                    //            binding.CloseTimeout = TimeSpan.FromMinutes(10);
                    //            binding.OpenTimeout = TimeSpan.FromMinutes(10);
                    //            binding.ReceiveTimeout = TimeSpan.FromMinutes(10);
                    //            binding.SendTimeout = TimeSpan.FromMinutes(10);
                    //            binding.MaxReceivedMessageSize = Int32.MaxValue;
                    //            IMSClient = new IMSClient(new EndpointAddress("net.tcp://localhost:6090/IncidentManagementSystemService"), binding);
                    //        }
                    //    }

                    //    Thread.Sleep(1000);
                    //} while (true);

                    // report changed state of the element
                    _IMServiceFabricClient.InvokeWithRetry(c => c.Channel.AddElementStateReport(elementStateReport));

                    // ni ovo ne kontam, tj. nemam vremena da kontam previse xD
                    Source s = (Source)DMSService.Instance.Tree.Data[DMSService.Instance.Tree.Roots[0]];
                    networkChange.Add(new UIUpdateModel(s.ElementGID, true));

                    Publisher publisher = new Publisher();
                    if (networkChange.Count > 0)
                    {
                        publisher.PublishUpdate(networkChange);
                    }
                    if (isIncident)
                    {
                        List <long> gids = new List <long>();
                        networkChange.ForEach(x => gids.Add(x.Gid));
                        List <long> listOfConsumersWithoutPower = gids.Where(x => (DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(x) == DMSType.ENERGCONSUMER).ToList();
                        foreach (long gid in listOfConsumersWithoutPower)
                        {
                            ResourceDescription resDes = DMSService.Instance.Gda.GetValues(gid);
                            try { incident.LostPower += resDes.GetProperty(ModelCode.ENERGCONSUMER_PFIXED).AsFloat(); } catch { }
                        }
                        _IMServiceFabricClient.InvokeWithRetry(c => c.Channel.AddReport(incident));
                        publisher.PublishIncident(incident);
                    }
                }
            }
            else
            {
                Console.WriteLine("ChangeOnScada()-> element with mrid={0} do not exist in OMS.", mrID);
            }
        }
Beispiel #19
0
        /// <summary>
        /// call je gid EC
        /// </summary>
        public void TraceUpAlgorithm()
        {
            List <NodeLink> maxDepthCheck = new List <NodeLink>();

            possibleBreakers = new List <List <long> >();

            Task.Factory.StartNew(() => Timer());

            int       callsNum        = 0;
            Publisher pub             = new Publisher();
            long?     incidentBreaker = null;

            while (true)
            {
                //zakljucavamo pozive klijenata i pronalazimo zajednicke prekidace
                if (callsNum != clientsCall.Count)
                {
                    callsNum = clientsCall.Count;

                    lock (sync)
                    {
                        foreach (long call in clientsCall)
                        {
                            Consumer c      = (Consumer)DMSServiceHost.Instance.Tree.Data[call];
                            Node     upNode = (Node)DMSServiceHost.Instance.Tree.Data[c.End1];
                            UpToSource(upNode, DMSServiceHost.Instance.Tree);
                            if (allBrekersUp.Count > 0)
                            {
                                List <long> pom = new List <long>();
                                foreach (var item in allBrekersUp)
                                {
                                    Switch s = (Switch)DMSServiceHost.Instance.Tree.Data[item];
                                    if (s.UnderSCADA == false)
                                    {
                                        pom.Add(s.ElementGID);
                                    }
                                }
                                possibleBreakers.Add(pom);
                                allBrekersUp.Clear();
                            }
                        }
                    }
                    //ako lista ima vise clanova onda se bira prekidac koji je dublje u mrezi
                    int         numOfConsumers = possibleBreakers.Count;
                    List <long> intesection    = possibleBreakers.Aggregate((previousList, nextList) => previousList.Intersect(nextList).ToList());
                    maxDepthCheck = new List <NodeLink>();
                    foreach (long breaker in intesection)
                    {
                        maxDepthCheck.Add(DMSServiceHost.Instance.Tree.Links.Values.FirstOrDefault(x => x.Parent == breaker));
                    }
                    NodeLink possibileIncident = maxDepthCheck.FirstOrDefault(x => x.Depth == maxDepthCheck.Max(y => y.Depth));
                    incidentBreaker = possibileIncident.Parent;

                    if (waitForMoreCalls)
                    {
                        pub.PublishUIBreaker(false, (long)incidentBreaker);

                        //Thread.Sleep(37000);
                    }
                }

                if (!waitForMoreCalls)
                {
                    lock (sync)
                    {
                        if (/*callsNum == clientsCall.Count || */ waitForMoreCalls == false)
                        {
                            //publishujes incident
                            string         mrid     = DMSServiceHost.Instance.Tree.Data[(long)incidentBreaker].MRID;
                            IncidentReport incident = new IncidentReport()
                            {
                                MrID = mrid
                            };
                            incident.Crewtype = CrewType.Investigation;

                            // to do: BUG -> ovo state opened srediti
                            SwitchStateReport elementStateReport = new SwitchStateReport()
                            {
                                MrID = mrid, Time = DateTime.UtcNow, State = 1
                            };
                            //ElementStateReport elementStateReport = new ElementStateReport() { MrID = mrid, Time = DateTime.UtcNow, State = "OPENED" };

                            IMSProxy.AddElementStateReport(elementStateReport);
                            pub.PublishUIBreaker(true, (long)incidentBreaker);

                            List <UIUpdateModel> networkChange = new List <UIUpdateModel>();
                            Switch sw;
                            try
                            {
                                sw = (Switch)DMSServiceHost.Instance.Tree.Data[(long)incidentBreaker];
                            }
                            catch (Exception)
                            {
                                return;
                            }
                            sw.IsEnergized = false;
                            sw.State       = SwitchState.Open;
                            sw.Incident    = true;
                            networkChange.Add(new UIUpdateModel(sw.ElementGID, false, OMSSCADACommon.States.OPEN));
                            Node n = (Node)DMSServiceHost.Instance.Tree.Data[sw.End2];
                            n.IsEnergized = false;
                            networkChange.Add(new UIUpdateModel(n.ElementGID, false));
                            networkChange = EnergizationAlgorithm.TraceDown(n, networkChange, false, false, DMSServiceHost.Instance.Tree);

                            Source s = (Source)DMSServiceHost.Instance.Tree.Data[DMSServiceHost.Instance.Tree.Roots[0]];
                            networkChange.Add(new UIUpdateModel(s.ElementGID, true));


                            List <long> gids = new List <long>();
                            networkChange.ForEach(x => gids.Add(x.Gid));
                            List <long> listOfConsumersWithoutPower = gids.Where(x => (DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(x) == DMSType.ENERGCONSUMER).ToList();
                            foreach (long gid in listOfConsumersWithoutPower)
                            {
                                ResourceDescription resDes = DMSServiceHost.Instance.Gda.GetValues(gid);
                                try { incident.LostPower += resDes.GetProperty(ModelCode.ENERGCONSUMER_PFIXED).AsFloat(); } catch { }
                            }
                            IMSProxy.AddReport(incident);

                            Thread.Sleep(3000);

                            //pub.PublishUpdateDigital(s.MRID, true);
                            pub.PublishIncident(incident);

                            clientsCall.Clear();
                            return;
                        }
                    }
                }
            }
        }
        private void ButtonGetRelatedValues_Click(object sender, RoutedEventArgs e)
        {
            if (SelectedProperty == null)
            {
                return;
            }

            List <ModelCode> selectedProperties = new List <ModelCode>();

            foreach (var child in PropertiesInRelated.Children)
            {
                CheckBox checkBox;
                if (child is CheckBox && (child as CheckBox).IsChecked.Value)
                {
                    checkBox = child as CheckBox;
                    foreach (KeyValuePair <ModelCode, string> keyValuePair in propertiesDesc)
                    {
                        if (keyValuePair.Value.Equals(checkBox.Content))
                        {
                            selectedProperties.Add(keyValuePair.Key);
                        }
                    }
                }
            }

            StringBuilder sb = new StringBuilder();

            sb.Append("Returned entities" + Environment.NewLine + Environment.NewLine);

            ////////////////////////////////////////////
            List <long>         gidReferences = new List <long>();
            ResourceDescription rd            = tgda.GetValues(SelectedGID.GID, new List <ModelCode>()
            {
                SelectedProperty.Property
            });

            if (rd != null)
            {
                Property prop = rd.GetProperty(SelectedProperty.Property);

                if ((short)(unchecked ((long)SelectedProperty.Property & (long)ModelCodeMask.MASK_ATTRIBUTE_TYPE)) == (short)PropertyType.Reference)
                {
                    gidReferences.Add(prop.AsReference());
                }
                else if ((short)(unchecked ((long)SelectedProperty.Property & (long)ModelCodeMask.MASK_ATTRIBUTE_TYPE)) == (short)PropertyType.ReferenceVector)
                {
                    gidReferences.AddRange(prop.AsReferences());
                }
            }

            HashSet <DMSType> referencedDmsTypes = new HashSet <DMSType>();

            if (gidReferences.Count > 0)
            {
                foreach (long gidReference in gidReferences)
                {
                    DMSType dmsType = (DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(gidReference);
                    if (!referencedDmsTypes.Contains(dmsType))
                    {
                        referencedDmsTypes.Add(dmsType);
                    }
                }
            }
            ////////////////////////////////////////////////////////

            try
            {
                if (SelectedDmsType != null)
                {
                    Association association = new Association(SelectedProperty.Property, modelResourcesDesc.GetModelCodeFromType(SelectedDmsType.DmsType));
                    List <long> gids        = tgda.GetRelatedValues(SelectedGID.GID, selectedProperties, association, sb);
                }
                else
                {
                    /////////////////////////////////////////////////////////////
                    HashSet <ModelCode> referencedDmsTypesProperties      = new HashSet <ModelCode>(modelResourcesDesc.GetAllPropertyIds(referencedDmsTypes.First()));
                    List <ModelCode>    toBeRemovedFormSelectedProperties = new List <ModelCode>();
                    foreach (ModelCode property in selectedProperties)
                    {
                        if (!referencedDmsTypesProperties.Contains(property))
                        {
                            toBeRemovedFormSelectedProperties.Add(property);
                        }
                    }

                    foreach (ModelCode property in toBeRemovedFormSelectedProperties)
                    {
                        selectedProperties.Remove(property);
                    }

                    foreach (var child in PropertiesInRelated.Children)
                    {
                        CheckBox checkBox;
                        if (child is CheckBox && (child as CheckBox).IsChecked.Value)
                        {
                            checkBox = child as CheckBox;
                            foreach (KeyValuePair <ModelCode, string> keyValuePair in propertiesDesc)
                            {
                                if (keyValuePair.Value.Equals(checkBox.Content) && toBeRemovedFormSelectedProperties.Contains(keyValuePair.Key))
                                {
                                    checkBox.IsChecked = false;
                                }
                            }
                        }
                    }

                    CheckAllBtn.IsEnabled = true;
                    /////////////////////////////////////////////////////////////

                    Association association = new Association(SelectedProperty.Property, 0x0000000000000000);
                    List <long> gids        = tgda.GetRelatedValues(SelectedGID.GID, selectedProperties, association, sb);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "GetRelatedValues", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            RelatedValues.Document.Blocks.Clear();
            RelatedValues.AppendText(sb.ToString());
        }
 public new void ReadFromResourceDescription(ResourceDescription rd)
 {
     try { this.Length = rd.GetProperty(ModelCode.CONDUCTOR_LEN).AsFloat(); } catch { }
     base.ReadFromResourceDescription(rd);
 }
        private ITopologyElement GetPopulatedElement(ResourceDescription rs)
        {
            string           errorMessage    = $"[NMSManager] Failed to populate element with GID 0x{rs.Id:X16}. ";
            ITopologyElement topologyElement = new TopologyElement(rs.Id);

            try
            {
                DMSType type = GetDMSTypeOfTopologyElement(rs.Id);
                topologyElement.Mrid        = rs.GetProperty(ModelCode.IDOBJ_MRID).AsString();
                topologyElement.Name        = rs.GetProperty(ModelCode.IDOBJ_NAME).AsString();
                topologyElement.Description = rs.GetProperty(ModelCode.IDOBJ_DESCRIPTION).AsString();
                topologyElement.DmsType     = type.ToString();

                if (rs.ContainsProperty(ModelCode.CONDUCTINGEQUIPMENT_ISREMOTE))
                {
                    topologyElement.IsRemote = rs.GetProperty(ModelCode.CONDUCTINGEQUIPMENT_ISREMOTE).AsBool();
                }
                else
                {
                    topologyElement.IsRemote = false;
                }

                if (rs.ContainsProperty(ModelCode.BREAKER_NORECLOSING))
                {
                    topologyElement.NoReclosing = rs.GetProperty(ModelCode.BREAKER_NORECLOSING).AsBool();
                    if (!topologyElement.NoReclosing)
                    {
                        topologyElement = new Recloser(topologyElement);
                    }
                }
                else
                {
                    topologyElement.NoReclosing = true;
                }

                if (rs.ContainsProperty(ModelCode.CONDUCTINGEQUIPMENT_BASEVOLTAGE))
                {
                    long baseVoltageGid = rs.GetProperty(ModelCode.CONDUCTINGEQUIPMENT_BASEVOLTAGE).AsLong();
                    if (BaseVoltages.TryGetValue(baseVoltageGid, out float voltage))
                    {
                        topologyElement.NominalVoltage = voltage;
                    }
                    else if (baseVoltageGid == 0)
                    {
                        logger.LogError($"{errorMessage} BaseVoltage with GID 0x{baseVoltageGid.ToString("X16")} does not exist in baseVoltages collection.");
                    }
                }
                else
                {
                    topologyElement.NominalVoltage = 0;
                }

                if (rs.ContainsProperty(ModelCode.BREAKER_NORECLOSING) && !rs.GetProperty(ModelCode.BREAKER_NORECLOSING).AsBool())
                {
                    Reclosers.Add(topologyElement.Id);
                }

                if (rs.ContainsProperty(ModelCode.ENERGYCONSUMER_TYPE))
                {
                    topologyElement = new EnergyConsumer(topologyElement)
                    {
                        Type = (EnergyConsumerType)rs.GetProperty(ModelCode.ENERGYCONSUMER_TYPE).AsEnum()
                    };
                }

                if (type == DMSType.SYNCHRONOUSMACHINE)
                {
                    topologyElement = new SynchronousMachine(topologyElement);

                    if (rs.ContainsProperty(ModelCode.SYNCHRONOUSMACHINE_CAPACITY))
                    {
                        ((SynchronousMachine)topologyElement).Capacity = rs.GetProperty(ModelCode.SYNCHRONOUSMACHINE_CAPACITY).AsFloat();
                    }

                    if (rs.ContainsProperty(ModelCode.SYNCHRONOUSMACHINE_CURRENTREGIME))
                    {
                        ((SynchronousMachine)topologyElement).CurrentRegime = rs.GetProperty(ModelCode.SYNCHRONOUSMACHINE_CURRENTREGIME).AsFloat();
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"{errorMessage} Could not get all properties.Excepiton message: {ex.Message}");
            }
            return(topologyElement);
        }
        public void ChangeOnSCADA(string mrID, OMSSCADACommon.States state)
        {
            ModelGdaDMS gda = new ModelGdaDMS();

            List <ResourceDescription> discreteMeasurements = gda.GetExtentValuesExtended(ModelCode.DISCRETE);
            ResourceDescription        rdDMeasurement       = discreteMeasurements.Where(r => r.GetProperty(ModelCode.IDOBJ_MRID).AsString() == mrID).FirstOrDefault();

            // if measurement exists here! if result is null it exists only on scada, but not in .data
            if (rdDMeasurement != null)
            {
                // find PSR element associated with measurement
                long rdAssociatedPSR = rdDMeasurement.GetProperty(ModelCode.MEASUREMENT_PSR).AsLong();

                List <SCADAUpdateModel> networkChange = new List <SCADAUpdateModel>();

                Element DMSElementWithMeas;
                Console.WriteLine("Change on scada Instance.Tree");
                DMSService.Instance.Tree.Data.TryGetValue(rdAssociatedPSR, out DMSElementWithMeas);
                Switch sw = (Switch)DMSElementWithMeas;

                bool           isIncident = false;
                IncidentReport incident   = new IncidentReport()
                {
                    MrID = sw.MRID
                };

                Random rand  = new Random();
                Array  crews = Enum.GetValues(typeof(CrewType));
                incident.Crewtype = (CrewType)crews.GetValue(rand.Next(0, crews.Length));

                ElementStateReport elementStateReport = new ElementStateReport()
                {
                    MrID = sw.MRID, Time = DateTime.UtcNow, State = (int)state
                };

                bool isImsAvailable = false;
                do
                {
                    try
                    {
                        if (IMSClient.State == CommunicationState.Created)
                        {
                            IMSClient.Open();
                        }

                        isImsAvailable = IMSClient.Ping();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ChangeOnScada() -> IMS is not available yet.");
                        if (IMSClient.State == CommunicationState.Faulted)
                        {
                            IMSClient = new IMSClient(new EndpointAddress("net.tcp://localhost:6090/IncidentManagementSystemService"));
                        }
                    }
                    Thread.Sleep(1000);
                } while (!isImsAvailable);


                if (state == OMSSCADACommon.States.OPENED)
                {
                    IMSClient.AddReport(incident);
                    isIncident = true;

                    sw.Marker = false;
                    sw.State  = SwitchState.Open;
                    networkChange.Add(new SCADAUpdateModel(sw.ElementGID, false, OMSSCADACommon.States.OPENED));
                    Node n = (Node)DMSService.Instance.Tree.Data[sw.End2];
                    n.Marker = false;
                    networkChange.Add(new SCADAUpdateModel(n.ElementGID, false));
                    networkChange = EnergizationAlgorithm.TraceDown(n, networkChange, false, false, DMSService.Instance.Tree);
                }
                else if (state == OMSSCADACommon.States.CLOSED)
                {
                    sw.State = SwitchState.Closed;
                    if (EnergizationAlgorithm.TraceUp((Node)DMSService.Instance.Tree.Data[sw.End1], DMSService.Instance.Tree))
                    {
                        networkChange.Add(new SCADAUpdateModel(sw.ElementGID, true, OMSSCADACommon.States.CLOSED));
                        sw.Marker = true;
                        Node n = (Node)DMSService.Instance.Tree.Data[sw.End2];
                        n.Marker = true;
                        networkChange.Add(new SCADAUpdateModel(n.ElementGID, true));
                        networkChange = EnergizationAlgorithm.TraceDown(n, networkChange, true, false, DMSService.Instance.Tree);
                    }
                    else
                    {
                        networkChange.Add(new SCADAUpdateModel(sw.ElementGID, false, OMSSCADACommon.States.CLOSED));
                    }
                }

                // report changed state of the element
                IMSClient.AddElementStateReport(elementStateReport);

                Source s = (Source)DMSService.Instance.Tree.Data[DMSService.Instance.Tree.Roots[0]];
                networkChange.Add(new SCADAUpdateModel(s.ElementGID, true));

                Publisher publisher = new Publisher();
                if (networkChange.Count > 0)
                {
                    publisher.PublishUpdate(networkChange);
                }
                if (isIncident)
                {
                    //Thread.Sleep(1000);
                    List <long> gids = new List <long>();
                    networkChange.ForEach(x => gids.Add(x.Gid));
                    List <long> listOfConsumersWithoutPower = gids.Where(x => (DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(x) == DMSType.ENERGCONSUMER).ToList();
                    foreach (long gid in listOfConsumersWithoutPower)
                    {
                        ResourceDescription resDes = DMSService.Instance.Gda.GetValues(gid);
                        incident.LostPower += resDes.GetProperty(ModelCode.ENERGCONSUMER_PFIXED).AsFloat();
                    }
                    publisher.PublishIncident(incident);
                }
            }
            else
            {
                Console.WriteLine("ChangeOnScada()-> element with mrid={0} do not exist in OMS.", mrID);
            }
        }
 public new void ReadFromResourceDescription(ResourceDescription rd)
 {
     try { this.Pfixed = rd.GetProperty(ModelCode.ENERGCONSUMER_PFIXED).AsFloat(); } catch { }
     base.ReadFromResourceDescription(rd);
 }
        private static void ExecuteOpenPropertiesCommand(object parameter)
        {
            ResourceDescription rd = cnClient.GetStaticDataForElement((long)parameter);

            PropertiesControl propertiesControl = new PropertiesControl();

            List <DigitalMeasurement> digitalMeasurements = new List <DigitalMeasurement>();
            List <AnalogMeasurement>  analogMeasurements  = new List <AnalogMeasurement>();

            PropertiesModelView propertiesModelView = new PropertiesModelView();

            if (rd != null)
            {
                StaticProperties staticProperties = new StaticProperties();
                staticProperties.ReadFromResourceDescription(rd);

                GeneralStaticPropertiesControl generalStaticPropertiesControl = new GeneralStaticPropertiesControl()
                {
                    DataContext = staticProperties
                };

                propertiesControl.StaticProperties.Content = generalStaticPropertiesControl;

                if (rd.ContainsProperty(ModelCode.PSR_MEASUREMENTS))
                {
                    List <long> measurementGids = rd.GetProperty(ModelCode.PSR_MEASUREMENTS).AsLongs();

                    foreach (long meas in measurementGids)
                    {
                        rd = cnClient.GetStaticDataForElement(meas);

                        short type = ModelCodeHelper.ExtractTypeFromGlobalId(meas);

                        PropertiesModelView.Measurements.Clear();

                        if (type == (short)DMSType.DISCRETE)
                        {
                            DigitalMeasurement digitalMeasurement = new DigitalMeasurement();
                            digitalMeasurement.ReadFromResourceDescription(rd);

                            csClient.GetDiscreteMeasurement(rd.GetProperty(ModelCode.IDOBJ_MRID).AsString(), out OMSSCADACommon.States state);

                            digitalMeasurement.State = state;

                            digitalMeasurements.Add(digitalMeasurement);

                            PropertiesModelView.Measurements.Add(digitalMeasurement.MRID, digitalMeasurement);
                        }
                        else if (type == (short)DMSType.ANALOG)
                        {
                            AnalogMeasurement analogMeasurement = new AnalogMeasurement();
                            analogMeasurement.ReadFromResourceDescription(rd);

                            csClient.GetAnalogMeasurement(rd.GetProperty(ModelCode.IDOBJ_MRID).AsString(), out float value);

                            analogMeasurement.Value = value;

                            analogMeasurements.Add(analogMeasurement);

                            PropertiesModelView.Measurements.Add(analogMeasurement.MRID, analogMeasurement);
                        }
                    }
                }
            }

            if (digitalMeasurements.Count == 0 && analogMeasurements.Count == 0)
            {
                propertiesModelView.MeasurementVisibility = Visibility.Collapsed;
            }
            else
            {
                propertiesModelView.MeasurementVisibility = Visibility.Visible;

                propertiesControl.Measurements.Content = new MeasurementsControl()
                {
                    DataContext = propertiesModelView
                };

                if (digitalMeasurements.Count > 0)
                {
                    foreach (DigitalMeasurement measurement in digitalMeasurements)
                    {
                        DiscreteMeasurementControl discreteMeasurementControl = new DiscreteMeasurementControl()
                        {
                            DataContext = measurement
                        };

                        propertiesModelView.DigitalControls.Add(discreteMeasurementControl);
                    }

                    propertiesModelView.DigitalMeasurementVisibility = Visibility.Visible;
                }
                else
                {
                    propertiesModelView.DigitalMeasurementVisibility = Visibility.Collapsed;
                }

                if (analogMeasurements.Count > 0)
                {
                    foreach (AnalogMeasurement measurement in analogMeasurements)
                    {
                        AnalogMeasurementControl analogMeasurementControl = new AnalogMeasurementControl()
                        {
                            DataContext = measurement
                        };

                        propertiesModelView.AnalogControls.Add(analogMeasurementControl);
                    }


                    propertiesModelView.AnalogMeasurementVisibility = Visibility.Visible;
                }
                else
                {
                    propertiesModelView.AnalogMeasurementVisibility = Visibility.Collapsed;
                }
            }

            ShellFillerShell sfs = new ShellFillerShell() /*DataContext = this*/ }
        private async Task <ITopologyElement> GetPopulatedElement(ResourceDescription rs)
        {
            string verboseMessage = $"{baseLogString} entering GetPopulatedElement method.";

            Logger.LogVerbose(verboseMessage);

            ITopologyElement topologyElement = new TopologyElement(rs.Id);

            try
            {
                DMSType type = GetDMSTypeOfTopologyElement(rs.Id);
                topologyElement.Mrid        = rs.GetProperty(ModelCode.IDOBJ_MRID).AsString();
                topologyElement.Name        = rs.GetProperty(ModelCode.IDOBJ_NAME).AsString();
                topologyElement.Description = rs.GetProperty(ModelCode.IDOBJ_DESCRIPTION).AsString();
                topologyElement.DmsType     = type.ToString();

                if (rs.ContainsProperty(ModelCode.CONDUCTINGEQUIPMENT_ISREMOTE))
                {
                    topologyElement.IsRemote = rs.GetProperty(ModelCode.CONDUCTINGEQUIPMENT_ISREMOTE).AsBool();
                }
                else
                {
                    topologyElement.IsRemote = false;
                }

                if (rs.ContainsProperty(ModelCode.BREAKER_NORECLOSING))
                {
                    topologyElement.NoReclosing = rs.GetProperty(ModelCode.BREAKER_NORECLOSING).AsBool();
                    if (!topologyElement.NoReclosing)
                    {
                        topologyElement = new Recloser(topologyElement);
                    }
                }
                else
                {
                    topologyElement.NoReclosing = true;
                }

                if (rs.ContainsProperty(ModelCode.CONDUCTINGEQUIPMENT_BASEVOLTAGE))
                {
                    long baseVoltageGid = rs.GetProperty(ModelCode.CONDUCTINGEQUIPMENT_BASEVOLTAGE).AsLong();

                    var voltageResult = await BaseVoltages.TryGetValueAsync(baseVoltageGid);

                    if (voltageResult.HasValue)
                    {
                        topologyElement.NominalVoltage = voltageResult.Value;
                    }
                    else if (baseVoltageGid == 0)
                    {
                        Logger.LogError($"{baseLogString} GetPopulatedElement => BaseVoltage with GID {baseVoltageGid:X16} does not exist in baseVoltages collection.");
                    }
                }
                else
                {
                    topologyElement.NominalVoltage = 0;
                }

                if (rs.ContainsProperty(ModelCode.BREAKER_NORECLOSING) && !rs.GetProperty(ModelCode.BREAKER_NORECLOSING).AsBool())
                {
                    var reclosersResult = await Reclosers.TryGetValueAsync(ReliableDictionaryNames.Reclosers);

                    if (reclosersResult.HasValue)
                    {
                        var reclosers = reclosersResult.Value;
                        reclosers.Add(topologyElement.Id);

                        await Reclosers.SetAsync(ReliableDictionaryNames.Reclosers, reclosers);
                    }
                    else
                    {
                        Logger.LogWarning($"{baseLogString} Reliable collection '{ReliableDictionaryNames.Reclosers}' was not defined yet. Handling...");
                        await Reclosers.SetAsync(ReliableDictionaryNames.Reclosers, new HashSet <long>() { topologyElement.Id });
                    }
                }

                if (rs.ContainsProperty(ModelCode.ENERGYCONSUMER_TYPE))
                {
                    topologyElement = new EnergyConsumer(topologyElement)
                    {
                        Type = (EnergyConsumerType)rs.GetProperty(ModelCode.ENERGYCONSUMER_TYPE).AsEnum()
                    };
                }

                if (type == DMSType.SYNCHRONOUSMACHINE)
                {
                    topologyElement = new SynchronousMachine(topologyElement);

                    if (rs.ContainsProperty(ModelCode.SYNCHRONOUSMACHINE_CAPACITY))
                    {
                        ((SynchronousMachine)topologyElement).Capacity = rs.GetProperty(ModelCode.SYNCHRONOUSMACHINE_CAPACITY).AsFloat();
                    }

                    if (rs.ContainsProperty(ModelCode.SYNCHRONOUSMACHINE_CURRENTREGIME))
                    {
                        ((SynchronousMachine)topologyElement).CurrentRegime = rs.GetProperty(ModelCode.SYNCHRONOUSMACHINE_CURRENTREGIME).AsFloat();
                    }
                }
            }
            catch (Exception e)
            {
                Logger.LogError($"{baseLogString} GetPopulatedElement => Could not get all properties." +
                                $"{Environment.NewLine}Excepiton message: {e.Message}" +
                                $"{Environment.NewLine} Stack trace: {e.StackTrace}");
            }
            return(topologyElement);
        }
        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);
        }