public ScadaTransactionActor(IReliableStateManager stateManager, ModelResourcesDesc modelResourceDesc, EnumDescs enumDescs) { this.baseLogString = $"{this.GetType()} [{this.GetHashCode()}] =>{Environment.NewLine}"; this.isCurrentGidToPointItemMapInitialized = false; this.isIncomingGidToPointItemMapInitialized = false; this.isCurrentAddressToGidMapInitialized = false; this.isIncomingAddressToGidMapInitialized = false; this.isInfoCacheInitialized = false; this.isModelChangesInitialized = false; this.isCommandDescriptionCacheInitialized = false; this.stateManager = stateManager; this.stateManager.StateManagerChanged += this.OnStateManagerChangedHandler; this.modelResourceDesc = modelResourceDesc; this.enumDescs = enumDescs; this.pointItemHelper = new ScadaModelPointItemHelper(); this.reliableDictionaryHelper = new ReliableDictionaryHelper(); }
private List <ModelCode> NadjiTipove(ModelCode kodProp) { ModelResourcesDesc modResDes = new ModelResourcesDesc(); //List<DMSType> tip = new List<DMSType>(); string[] props = (kodProp.ToString()).Split('_'); props[1] = props[1].TrimEnd('S'); DMSType propertyCode = ModelResourcesDesc.GetTypeFromModelCode(kodProp); ModelCode mc; ModelCodeHelper.GetModelCodeFromString(propertyCode.ToString(), out mc); foreach (ModelCode modelCode in Enum.GetValues(typeof(ModelCode))) { if (String.Compare(props[1], modelCode.ToString()) == 0) { DMSType type = ModelCodeHelper.GetTypeFromModelCode(modelCode); if (type == 0) { tipovi = new List <ModelCode>(); List <DMSType> r = modResDes.GetLeaves(modelCode); foreach (DMSType ff in r) { tipovi.Add(modResDes.GetModelCodeFromType(ff)); } } else { tipovi = new List <ModelCode>(); tipovi.Add(modelCode); } } } return(new List <ModelCode>()); }
public OutageManagementService() { proxyFactory = new ProxyFactory(); //TODO: Initialize what is needed //TODO: restauration of data... modelResourcesDesc = new ModelResourcesDesc(); using (UnitOfWork db = new UnitOfWork()) { //db.DeleteAllData(); InitializeEnergyConsumers(db); } outageModel = new OutageModel(); HistoryDBManager historyDBManager = new HistoryDBManager(); outageModel.ConsumersBlackedOut += historyDBManager.OnConsumersBlackedOut; outageModel.ConsumersEnergized += historyDBManager.OnConsumersEnergized; outageModel.SwitchOpened += historyDBManager.OnSwitchOpened; OutageService.SwitchClosed += historyDBManager.OnSwitchClosed; reportOutageService = new ReportOutageService(outageModel); isolateOutageService = new IsolateOutageService(outageModel); resolveOutageService = new ResolveOutageService(outageModel); validateResolveConditionsService = new ValidateResolveConditionsService(outageModel); sendRepairCrewService = new SendRepairCrewService(outageModel); sendLocationIsolationCrewService = new SendLocationIsolationCrewService(outageModel); OutageService.reportOutageService = reportOutageService; OutageService.isolateOutageService = isolateOutageService; OutageService.resolveOutageService = resolveOutageService; OutageService.validateResolveConditionsService = validateResolveConditionsService; OutageService.sendLocationIsolationCrewService = sendLocationIsolationCrewService; OutageService.sendRepairCrewService = sendRepairCrewService; OutageService.outageModel = outageModel; OutageTransactionActor.OutageModel = outageModel; OutageModelUpdateNotification.OutageModel = outageModel; callTracker = new CallTracker("CallTrackerSubscriber", outageModel); SubscribeOnEmailService(); InitializeHosts(); }
public CallTracker(IReliableStateManager stateManager, string subscriberName) { this.baseLogString = $"{this.GetType()} [{this.GetHashCode()}] =>{Environment.NewLine}"; string verboseMessage = $"{baseLogString} entering Ctor."; Logger.LogVerbose(verboseMessage); this.stateManager = stateManager; this.stateManager.StateManagerChanged += OnStateManagerChangedHandler; this.subscriberName = subscriberName; modelResourcesDesc = new ModelResourcesDesc(); trackingAlgorithm = new TrackingAlgorithm(); ImportFromConfig(); //timer initialization timer = new Timer(); timer.Interval = timerInterval; timer.Elapsed += TimerElapsedMethod; timer.AutoReset = false; }
public GenerateOutage(MainWindow parentWindow) { InitializeComponent(); DataContext = this; this.parentWindow = parentWindow; this.modelResourcesDesc = new ModelResourcesDesc(); GlobalIdentifiers = new ObservableCollection <GlobalIDBindingModel>(); OutageElement = new ObservableCollection <GlobalIDBindingModel>(); OptimumIsolationPoints = new ObservableCollection <GlobalIDBindingModel>(); DefaultIsolationPoints = new ObservableCollection <GlobalIDBindingModel>(); this.outageElementGids = new HashSet <long>(); this.optimumIsolationPointsGids = new HashSet <long>(); this.defaultIsolationPointsGids = new HashSet <long>(); Dispatcher.BeginInvoke((Action)(() => { InitializeGlobalIdentifiers(); })); }
public ModelManager(IReliableStateManager stateManager) { this.baseLogString = $"{this.GetType()} [{this.GetHashCode()}] =>{Environment.NewLine}"; string verboseMessage = $"{baseLogString} entering Ctor."; Logger.LogVerbose(verboseMessage); networkModelGda = new NetworkModelGDA(); modelResourcesDesc = new ModelResourcesDesc(); this.isEnergySourcesInitialized = false; this.isReclosersInitialized = false; this.isMeasurementsInitialized = false; this.isTopologyElementsInitialized = false; this.isBaseVoltagesInitialized = false; this.isElementConnectionsInitialized = false; this.isMeasurementToConnectedTerminalMapInitialized = false; this.isTerminalToConnectedElementsMapInitialized = false; this.stateManager = stateManager; this.stateManager.StateManagerChanged += this.OnStateManagerChangedHandler; }
public GetValues() { InitializeComponent(); DataContext = this; modelResourcesDesc = new ModelResourcesDesc(); propertiesDesc = new Dictionary <ModelCode, string>(); SelectedGID = null; GlobalIdentifiers = new ObservableCollection <GlobalIdentifierViewModel>(); try { tgda = new TestGda(); } catch (Exception ex) { MessageBox.Show(ex.Message, "GetValues", MessageBoxButton.OK, MessageBoxImage.Error); return; } Task.Run(Initialize); }
public void IntegrityUpdate() { string message = string.Empty; internalGen = new List <ResourceDescription>(5); modelResourcesDesc = new ModelResourcesDesc(); modelResourcesDesc2 = new ModelResourcesDesc(); retList = new List <ResourceDescription>(5); retList2 = new List <ResourceDescription>(5); properties = new List <ModelCode>(10); properties2 = new List <ModelCode>(10); ModelCode modelCodeGenerator = ModelCode.GENERATOR; ModelCode modelCodeEnergyConsumer = ModelCode.ENERGY_CONSUMER; ModelCode modelCodeAnalog = ModelCode.ANALOG; iteratorId = 0; iteratorId2 = 0; resourcesLeft = 0; resourcesLeft2 = 0; numberOfResources = 2; try { properties = modelResourcesDesc.GetAllPropertyIds(modelCodeGenerator); properties2 = modelResourcesDesc.GetAllPropertyIds(modelCodeAnalog); iteratorId = NetworkModelGDAProxy.Instance.GetExtentValues(modelCodeGenerator, properties); iteratorId2 = NetworkModelGDAProxy.Instance.GetExtentValues(modelCodeAnalog, properties2); resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorId); resourcesLeft2 = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorId2); //var retExtentValues = testGda.GetExtentValues(ModelCode.ANALOG, properties.ToList()); while (resourcesLeft > 0) { List <ResourceDescription> rds = NetworkModelGDAProxy.Instance.IteratorNext(numberOfResources, iteratorId); retList.AddRange(rds); resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorId); } //while (resourcesLeft2 > 0) //{ // List<ResourceDescription> rds2 = NetworkModelGDAProxy.Instance.IteratorNext(numberOfResources, iteratorId2); // retList2.AddRange(rds2); // foreach (var item in rds2) // { // if (retList.Where(x => x.Id == item.Id).FirstOrDefault() != null) // retList.Where(x => x.Id == item.Id).FirstOrDefault().Properties[6] = item.Properties[6]; // } // resourcesLeft2 = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorId2); //} NetworkModelGDAProxy.Instance.IteratorClose(iteratorId); internalGen.AddRange(retList); var descrete = DbManager.Instance.GetDiscreteCounters().ToList(); //foreach (ResourceDescription rd in internalGen) //{ // if (Gens.Any(x=> x.Id == rd.Id)) // { // continue; // } // bool active = descrete.Where(x => x.Gid == rd.Id).FirstOrDefault().CurrentValue; // float inputValue = DbManager.Instance.GetHistoryMeasurements().Where(x => x.Gid == rd.Id).OrderByDescending(x => x.MeasurementTime).First().MeasurementValue; // Gens.Add(new ModelForCheckboxes() { Id = rd.Id, IsActive = active, InputValue = inputValue, Name = rd.Properties[6].ToString(), Element = "Generator", Gid=rd.Id}); //} //OnPropertyChanged(nameof(Gens)); properties = modelResourcesDesc.GetAllPropertyIds(modelCodeEnergyConsumer); iteratorId = NetworkModelGDAProxy.Instance.GetExtentValues(modelCodeEnergyConsumer, 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); internalGen.AddRange(retList); foreach (ResourceDescription rd in internalGen) { if (EnergyConsumer.Any(x => x.Id == rd.Id)) { continue; } bool active = descrete.Where(x => x.Gid == rd.Id).FirstOrDefault().CurrentValue; EnergyConsumer.Add(new ModelForCheckboxes() { Id = rd.Id, IsActive = active }); } OnPropertyChanged(nameof(EnergyConsumer)); } catch (Exception e) { message = string.Format("Getting extent values method failed for {0}.\n\t{1}", modelCodeGenerator, e.Message); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } }
bool Get(INetworkModelGDAContract nms) { Dictionary <DMSType, List <ModelCode> > typeToPropertiesMap = ModelResourcesDesc.GetTypeToPropertiesMap(); if (insertedGids == null || updatedGids == null || deletedGids == null) { List <IdentifiedObject> inserted = new List <IdentifiedObject>(); DMSType[] types = ModelResourcesDesc.TypeIdsInInsertOrder; foreach (DMSType type in types) { int iterator = nms.GetExtentValues(type, typeToPropertiesMap[type], false); if (iterator < 0) { return(false); } List <ResourceDescription> result; do { result = nms.IteratorNext(iteratorCount, iterator, false); if (result == null) { return(false); } foreach (ResourceDescription rd in result) { if (rd == null) { continue; } inserted.Add(IdentifiedObject.Create(rd, true)); } }while(result.Count >= iteratorCount); nms.IteratorClose(iterator); Inserted = inserted; Updated = new List <IdentifiedObject>(0); Deleted = new List <long>(0); } } else { List <IdentifiedObject> inserted = new List <IdentifiedObject>(insertedGids.Count); List <IdentifiedObject> updated = new List <IdentifiedObject>(updatedGids.Count); List <ResourceDescription> result; int iterator = nms.GetMultipleValues(insertedGids, typeToPropertiesMap, true); do { result = nms.IteratorNext(iteratorCount, iterator, true); if (result == null) { return(false); } foreach (ResourceDescription rd in result) { if (rd == null) { continue; } inserted.Add(IdentifiedObject.Create(rd, true)); } }while(result.Count >= iteratorCount); nms.IteratorClose(iterator); iterator = nms.GetMultipleValues(updatedGids, typeToPropertiesMap, true); do { result = nms.IteratorNext(iteratorCount, iterator, true); if (result == null) { return(false); } foreach (ResourceDescription rd in result) { if (rd == null) { continue; } updated.Add(IdentifiedObject.Create(rd, true)); } }while(result.Count >= iteratorCount); nms.IteratorClose(iterator); Inserted = inserted; Updated = updated; Deleted = deletedGids; } return(true); }
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); } }
public GDAHelper() { resourcesDesc = new ModelResourcesDesc(); }
private bool PopulateNmsDataFromServer(ModelResourcesDesc resourcesDesc) { bool success = false; string message = "Getting nms data from server started."; Logger.LogInfo(message); using (NetworkModelGDAProxy nmsProxy = proxyFactory.CreateProxy <NetworkModelGDAProxy, INetworkModelGDAContract>(EndpointNames.NetworkModelGDAEndpoint)) { if (nmsProxy == null) { string errMessage = "NetworkModelGdaClient is null."; Logger.LogWarn(errMessage); throw new NullReferenceException(errMessage); } HashSet <ModelCode> requiredEntityTypes = new HashSet <ModelCode>(); foreach (DMSType dmsType in Enum.GetValues(typeof(DMSType))) { if (dmsType == DMSType.MASK_TYPE) { continue; } ModelCode mc = resourcesDesc.GetModelCodeFromType(dmsType); if (!requiredEntityTypes.Contains(mc)) { requiredEntityTypes.Add(mc); } } List <ModelCode> mrIdProp = new List <ModelCode>() { ModelCode.IDOBJ_MRID }; foreach (ModelCode modelCodeType in requiredEntityTypes) { int iteratorId = 0; int resourcesLeft = 0; int numberOfResources = 10000; //TODO: connfigurabilno try { iteratorId = nmsProxy.GetExtentValues(modelCodeType, mrIdProp); resourcesLeft = nmsProxy.IteratorResourcesLeft(iteratorId); while (resourcesLeft > 0) { List <ResourceDescription> gdaResult = nmsProxy.IteratorNext(numberOfResources, iteratorId); foreach (ResourceDescription rd in gdaResult) { if (rd.Properties[0].Id != ModelCode.IDOBJ_MRID) { continue; } string mrId = rd.Properties[0].PropertyValue.StringValue; if (!MridToPositiveGidFromServer.ContainsKey(mrId)) { MridToPositiveGidFromServer.Add(mrId, rd.Id); } else { throw new NotImplementedException("Method PopulateNmsDataFromServer() -> MridToPositiveGid.ContainsKey(mrId) == true"); } } resourcesLeft = nmsProxy.IteratorResourcesLeft(iteratorId); } nmsProxy.IteratorClose(iteratorId); message = "Getting nms data from server successfully finished."; Logger.LogInfo(message); success = true; } catch (Exception e) { message = string.Format("Getting extent values method failed for {0}.\n\t{1}", modelCodeType, e.Message); Logger.LogError(message); success = false; } } } return(success); }
/// <summary> /// Initializes a new instance of the Model class. /// </summary> public NetworkModel() { smartContainer = SmartContainer.Instance; smartContainer.Initialize(); resourcesDescs = new ModelResourcesDesc(); }
public ClientNMSService() { modelResourcesDesc = new ModelResourcesDesc(); gdaQueryProxy = new NetworkModelGDAProxy("NetworkModelGDAEndpoint"); }
public OpenDSSScriptBuilder(Dictionary <long, ResourceDescription> resources, TopologyResult topology) { Resources = resources; Topology = topology; modelResourcesDesc = new ModelResourcesDesc(); }
public ConsumerAccess() { modelResourcesDesc = new ModelResourcesDesc(); this.baseLogString = $"{this.GetType()} [{this.GetHashCode()}] =>{Environment.NewLine}"; Logger.LogDebug($"{baseLogString} Ctor => Logger initialized"); }
/// <summary> /// Test fixture set-up method. /// </summary> public virtual void Init() { generator = new PropertyGenerator(); modelResourcesDescs = new ModelResourcesDesc(); }
public CIMAdapterClass() { resourcesDesc = new ModelResourcesDesc(); proxyFactory = new ProxyFactory(); }
public CIMAdapterClass() { resourcesDesc = new ModelResourcesDesc(); }
private void RelationalPropertiesDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (SelectedProperty == null) { return; } RelatedEntityDmsTypes.Clear(); SelectedDmsType = null; PropertiesInRelated.Children.Clear(); RelatedValues.Document.Blocks.Clear(); List <DMSType> dmsTypes = new List <DMSType>(); if (RelationalPropertiesHelper.Relations.ContainsKey(SelectedProperty.Property)) { ModelCode relatedEntity = RelationalPropertiesHelper.Relations[SelectedProperty.Property]; dmsTypes.AddRange(ModelResourcesDesc.GetLeavesForCoreEntities(relatedEntity)); if (dmsTypes.Count == 0) { dmsTypes.Add(ModelCodeHelper.GetTypeFromModelCode(relatedEntity)); } } foreach (DMSType type in dmsTypes) { RelatedEntityDmsTypes.Add(new DmsTypeViewModel() { DmsType = type }); } HashSet <ModelCode> referencedTypeProperties = new HashSet <ModelCode>(); if (RelatedEntityDmsTypes.Count > 0) { foreach (DmsTypeViewModel referencedDmsType in RelatedEntityDmsTypes) { foreach (ModelCode propInReferencedType in modelResourcesDesc.GetAllPropertyIds(referencedDmsType.DmsType)) { if (!referencedTypeProperties.Contains(propInReferencedType)) { referencedTypeProperties.Add(propInReferencedType); } } } } Label label = new Label() { FontWeight = FontWeights.UltraBold, Content = "Properties (for classes in selected relation)", }; PropertiesInRelated.Children.Add(label); propertiesDesc.Clear(); if (referencedTypeProperties.Count > 0) { foreach (ModelCode property in referencedTypeProperties) { if (propertiesDesc.ContainsKey(property)) { continue; } propertiesDesc.Add(property, property.ToString()); CheckBox checkBox = new CheckBox() { Content = property.ToString(), }; checkBox.Unchecked += CheckBox_Unchecked; PropertiesInRelated.Children.Add(checkBox); } CheckAllBtn.IsEnabled = true; } }
public NetworkModel(NetworkModel networkModel) { networkDataModel = new Dictionary <DMSType, Container>(networkModel.networkDataModel); resourcesDescs = networkModel.resourcesDescs; }
/// <summary> /// Initializes a new instance of the Model class. /// </summary> public NetworkModel() { networkDataModel = new Dictionary <DMSType, Container>(); resourcesDescs = new ModelResourcesDesc(); Initialize(); }
public void SortOperations() { string message = String.Format("Sorting delta operations for delta with ID: {0}.", GetCompositeId(id)); Logger.LogDebug(message); List <ResourceDescription> insertOpsOrdered = new List <ResourceDescription>(); List <ResourceDescription> deleteOpsOrdered = new List <ResourceDescription>(); int insertOpsOrderedNo = 0; int deleteOpsOrderedNo = 0; int indexOp = 0; // pass through all given types for (int indexType = 0; indexType < Delta.ResourceDescs.TypeIdsInInsertOrder.Count; indexType++) { DMSType type = ModelResourcesDesc.GetTypeFromModelCode(Delta.ResourceDescs.TypeIdsInInsertOrder[indexType]); // pass through all insert operations // move operations with current type to list of ordered insert operations indexOp = 0; for (indexOp = 0; indexOp < insertOps.Count; indexOp++) { if (insertOps[indexOp] != null && type == (DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(insertOps[indexOp].Id)) { // add at the end of list of ordered insert operations insertOpsOrdered.Add(insertOps[indexOp]); insertOps[indexOp] = null; insertOpsOrderedNo++; // remove from the old non sorted list - ATTENTION: this turns to be VERY SLOW operation in case delta is BIG ////insertOps.RemoveAt(indexOp); } } // pass through all delete operations // move operations with current type to list of ordered delete operations indexOp = 0; for (indexOp = 0; indexOp < deleteOps.Count; indexOp++) { if (deleteOps[indexOp] != null && type == (DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(deleteOps[indexOp].Id)) { // add at the end of list of ordered delete operations deleteOpsOrdered.Add(deleteOps[indexOp]); deleteOps[indexOp] = null; deleteOpsOrderedNo++; // remove from the old non sorted list - ATTENTION: this turns to be VERY SLOW operation in case delta is BIG ////deleteOps.RemoveAt(indexOp); } } } // check if there are insert operations not covered by given data model types if (insertOps.Count != insertOpsOrderedNo) { // find type that is not specified in given list of types short typeNotDefined = 0; for (indexOp = 0; indexOp < insertOps.Count; indexOp++) { if (insertOps[indexOp] != null) { typeNotDefined = (short)ModelCodeHelper.ExtractTypeFromGlobalId(insertOps[indexOp].Id); } } message = String.Format("Failed to sort delta operations because there are some insert operations (count = {0}) whose type (e.g {1}) is not specified in the given list of types.", insertOps.Count - insertOpsOrderedNo, typeNotDefined); Logger.LogError(message); string exceptionMessage = String.Format("Invalid delta. Some insert operations (count = {0}) whose type (e.g {1}) is not correct.", insertOps.Count - insertOpsOrderedNo, typeNotDefined); throw new ModelException(ErrorCode.InvalidDelta, exceptionMessage); } // remember ordered insert operations insertOps = insertOpsOrdered; // check if there are delete operations not covered by given data model types if (deleteOps.Count != deleteOpsOrderedNo) { // find type that is not specified in given list of types short typeNotDefined = 0; for (indexOp = 0; indexOp < deleteOps.Count; indexOp++) { if (deleteOps[indexOp] != null) { typeNotDefined = ModelCodeHelper.ExtractTypeFromGlobalId(deleteOps[indexOp].Id); } } message = String.Format("Failed to sort delta operations because there are some delete operations (count = {0}) which type (e.g. {1}) is not specified in given list of types.", deleteOps.Count, typeNotDefined); Logger.LogError(message); string exceptionMessage = String.Format("Invalid delta. Some delete operations (count = {0}) which type (e.g. {1}) is not correct.", deleteOps.Count, typeNotDefined); throw new ModelException(ErrorCode.InvalidDelta, exceptionMessage); } // remember ordered delete operations deleteOpsOrdered.Reverse(); deleteOps = deleteOpsOrdered; message = String.Format("Sorting delta operations for delta with ID: {0} completed successfully.", GetCompositeId(id)); Logger.LogDebug(message); }
public OutageLifecycleHelper(ModelResourcesDesc modelResourcesDesc) { this.baseLogString = $"{this.GetType()} [{this.GetHashCode()}] =>{Environment.NewLine}"; this.modelResourcesDesc = modelResourcesDesc; }
public async Task <TransformAndLoadReport> CreateNMSDelta(ConcreteModel cimConcreteModel, ModelResourcesDesc resourcesDesc) { Logger.LogInformation("Importing Outage Elements..."); report = new TransformAndLoadReport(); concreteModel = cimConcreteModel; delta.ClearDeltaOperations(); MridToPositiveGidFromServer.Clear(); MridsFromConcreteModel.Clear(); NegativeGidToMrid.Clear(); if ((concreteModel != null) && (concreteModel.ModelMap != null)) { try { await ConvertModelAndPopulateDelta(resourcesDesc); } catch (Exception ex) { string message = $"{DateTime.Now} - ERROR in data import - {ex.Message}"; //LogManager.Log(message); Logger.LogError(message, ex); report.Report.AppendLine(ex.Message); report.Success = false; } } Logger.LogInformation("Importing Outage Elements - END"); return(report); }
public async Task <ExecutionReport> InitializeTopology() { ModelResourcesDesc resourcesDesc = new ModelResourcesDesc(); ExecutionReport executionReport = new ExecutionReport(); await ClearDictionary <long, ResourceDescription>(ReliableCollectionNames.NetworkModelDictinoary); GDAHelper gdaHelper = new GDAHelper(); Dictionary <long, ResourceDescription> energySources = (await gdaHelper.GetExtentValues(ModelCode.ENERGYSOURCE)).ToDictionary(value => value.Id); Dictionary <long, ResourceDescription> connectivityNodes = (await gdaHelper.GetExtentValues(ModelCode.CONNECTIVITYNODE)).ToDictionary(value => value.Id); Dictionary <long, ResourceDescription> switches = (await gdaHelper.GetExtentValues(ModelCode.SWITCH)).ToDictionary(value => value.Id); Dictionary <long, ResourceDescription> terminals = (await gdaHelper.GetExtentValues(ModelCode.TERMINAL)).ToDictionary(value => value.Id); List <ModelCode> classicBranchElements = resourcesDesc.ClassicBranches; Dictionary <long, ResourceDescription> cimBranches = new Dictionary <long, ResourceDescription>(); foreach (ModelCode classicBranchElement in classicBranchElements) { List <ResourceDescription> branches = await gdaHelper.GetExtentValues(classicBranchElement); foreach (ResourceDescription branch in branches) { cimBranches.Add(branch.Id, branch); } } Dictionary <long, ResourceDescription> otherCimElements = new Dictionary <long, ResourceDescription>(); foreach (ModelCode otherElement in resourcesDesc.OtherElements) { List <ResourceDescription> elements = await gdaHelper.GetExtentValues(otherElement); foreach (ResourceDescription element in elements) { otherCimElements.Add(element.Id, element); } } List <Task> tasks = new List <Task>() { SaveNetworkModelElements(energySources), SaveNetworkModelElements(connectivityNodes), SaveNetworkModelElements(switches), SaveNetworkModelElements(terminals), SaveNetworkModelElements(cimBranches), SaveNetworkModelElements(otherCimElements), }; InternalModelBuilderCIM internalModelBuilder = new InternalModelBuilderCIM(new CModelFramework()); internalModelBuilder.ReadSources(energySources, terminals); internalModelBuilder.ReadConnectivityNodes(connectivityNodes, terminals); internalModelBuilder.ReadBranches(cimBranches, terminals); internalModelBuilder.ReadSwitches(switches, terminals); IEnumerable <TopologyResult> topologyResults = null; try { topologyResults = await TopologyRequest.AnalyzeTopology(internalModelBuilder.InternalModel); } catch (Exception e) { string message = $"Analyze topology failed with error {e.Message}"; Logger.LogError(message); executionReport.Message = message; executionReport.Status = ExecutionStatus.ERROR; return(executionReport); } if (topologyResults != null) { try { await SaveTopologyModel(topologyResults); string message = $"Save topology successfully completed"; Logger.LogInformation(message); executionReport.Message = message; executionReport.Status = ExecutionStatus.SUCCESS; } catch (Exception e) { string message = $"Save topology model failed with error: {e.Message}"; Logger.LogError(message, e); executionReport.Message = message; executionReport.Status = ExecutionStatus.ERROR; } } else { string message = $"Some error ocurred on topology analyzer service"; Logger.LogError(message); executionReport.Message = message; executionReport.Status = ExecutionStatus.ERROR; } await Task.WhenAll(tasks); //Save network model version long currentNetworkModelVersion = await gdaHelper.GetVersion(); var networkModelVersionDictionary = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, long> >(ReliableCollectionNames.NetworkModelVersionDictionary); await networkModelVersionDictionary.ClearAsync(); using (var tx = this.stateManager.CreateTransaction()) { await networkModelVersionDictionary.AddAsync(tx, ReliableCollectionNames.NetworkModelVersionDictionary, currentNetworkModelVersion); await tx.CommitAsync(); } return(executionReport); }
public OutageIsolationProvider(IReliableStateManager stateManager, OutageLifecycleHelper lifecycleHelper, ModelResourcesDesc modelResourcesDesc) { this.baseLogString = $"{this.GetType()} [{this.GetHashCode()}] =>{Environment.NewLine}"; this.lifecycleHelper = lifecycleHelper; this.modelResourcesDesc = modelResourcesDesc; this.outageMessageMapper = new OutageMessageMapper(); this.isMonitoredHeadBreakerMeasurementsInitialized = false; this.isStartedIsolationAlgorithmsInitialized = false; this.stateManager = stateManager; this.stateManager.StateManagerChanged += this.OnStateManagerChangedHandler; }
public static void Main(string[] args) { ModelResourcesDesc resDesc = new ModelResourcesDesc(); try { // Set NMSTestInterfaceClient console layout Console.SetWindowPosition(0, 0); Console.SetBufferSize(250, 1000); Console.SetWindowSize((int)(Console.LargestWindowWidth * 0.7), (int)(Console.LargestWindowHeight * 0.8)); Console.Title = "Network Model Service Test Client"; } catch (Exception ex) { string errPositionMessage = string.Format("Error: Could not set Network Model Service Test Client's window size and position. {0}", ex.Message); Console.WriteLine(errPositionMessage); CommonTrace.WriteTrace(CommonTrace.TraceError, errPositionMessage); } string message = string.Format("Network Model Service Test Client is up and running..."); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceInfo, message); message = string.Format("Result directory: {0}", Config.Instance.ResultDirecotry); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceInfo, message); try { TestGda tgda = new TestGda(); string str = string.Empty; do { PrintMenu(); str = Console.ReadLine(); if (str == "1") { try { tgda.GetValues(InputGlobalId()); } catch (Exception ex) { message = string.Format("GetValues failed. {0}", ex.Message); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } } else if (str == "2") { try { tgda.GetExtentValues(InputModelCode()); } catch (Exception ex) { message = string.Format("GetExtentValues failed. {0}", ex.Message); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } } else if (str == "3") { try { tgda.GetRelatedValues(InputGlobalId(), InputAssociation()); } catch (Exception ex) { message = string.Format("GetRelatedValues failed. {0}", ex.Message); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } } else if (str == "4") { try { tgda.TestApplyDeltaInsert(); } catch (Exception ex) { message = string.Format("Test ApplyUpdate: Insert - Update - Delte failed. {0}", ex.Message); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } } else if (str != "q") { PrintUnknownOption(); } Console.WriteLine(); }while (str != "q"); } catch (Exception ex) { Console.WriteLine(ex.Message); CommonTrace.WriteTrace(CommonTrace.TraceError, ex.Message); } message = "Network Model Service Test Client stopped."; Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); }
bool Get(INetworkModelGDAContract nms) { Dictionary <long, Analog> analogs = new Dictionary <long, Analog>(); Dictionary <long, Discrete> discretes = new Dictionary <long, Discrete>(); Dictionary <long, Recloser> reclosers = new Dictionary <long, Recloser>(); Dictionary <long, Terminal> terminals = new Dictionary <long, Terminal>(); Dictionary <long, EnergyConsumer> energyConsumers = new Dictionary <long, EnergyConsumer>(); Dictionary <DMSType, List <ModelCode> > typeToPropertiesMap = ModelResourcesDesc.GetTypeToPropertiesMap(); List <ResourceDescription> result; int iterator = nms.GetExtentValues(DMSType.Analog, typeToPropertiesMap[DMSType.Analog], false); do { result = nms.IteratorNext(iteratorCount, iterator, false); if (result == null) { return(false); } foreach (ResourceDescription rd in result) { analogs.Add(rd.Id, (Analog)IdentifiedObject.Create(rd, true)); } }while(result.Count >= iteratorCount); nms.IteratorClose(iterator); iterator = nms.GetExtentValues(DMSType.Discrete, typeToPropertiesMap[DMSType.Discrete], false); do { result = nms.IteratorNext(iteratorCount, iterator, false); if (result == null) { return(false); } foreach (ResourceDescription rd in result) { discretes.Add(rd.Id, (Discrete)IdentifiedObject.Create(rd, true)); } }while(result.Count >= iteratorCount); nms.IteratorClose(iterator); iterator = nms.GetExtentValues(DMSType.EnergyConsumer, typeToPropertiesMap[DMSType.EnergyConsumer], false); do { result = nms.IteratorNext(iteratorCount, iterator, false); if (result == null) { return(false); } foreach (ResourceDescription rd in result) { energyConsumers.Add(rd.Id, (EnergyConsumer)IdentifiedObject.Create(rd, true)); } }while(result.Count >= iteratorCount); nms.IteratorClose(iterator); iterator = nms.GetExtentValues(DMSType.Recloser, typeToPropertiesMap[DMSType.Recloser], false); do { result = nms.IteratorNext(iteratorCount, iterator, false); if (result == null) { return(false); } foreach (ResourceDescription rd in result) { reclosers.Add(rd.Id, (Recloser)IdentifiedObject.Create(rd, true)); } }while(result.Count >= iteratorCount); nms.IteratorClose(iterator); List <long> terminalGIDs = new List <long>(reclosers.Count * 2); foreach (Recloser r in reclosers.Values) { for (int i = 0; i < r.Terminals.Count; ++i) { terminalGIDs.Add(r.Terminals[i]); } } iterator = nms.GetMultipleValues(terminalGIDs, typeToPropertiesMap, false); do { result = nms.IteratorNext(iteratorCount, iterator, false); if (result == null) { return(false); } foreach (ResourceDescription rd in result) { if (terminals.ContainsKey(rd.Id)) { continue; } terminals.Add(rd.Id, (Terminal)IdentifiedObject.Create(rd, true)); } }while(result.Count >= iteratorCount); nms.IteratorClose(iterator); Analogs = analogs; Discretes = discretes; Reclosers = reclosers; Terminals = terminals; EnergyConsumers = energyConsumers; return(true); }