public List <long> GetRelatedValues(long sourceGlobalId, Association association) { string message = "Getting related values method started."; Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); List <long> resultIds = new List <long>(); XmlTextWriter xmlWriter = null; int numberOfResources = 2; try { List <ModelCode> properties = new List <ModelCode>(); properties.Add(ModelCode.IDOBJ_DESCRIPTION); properties.Add(ModelCode.IDOBJ_MRID); properties.Add(ModelCode.IDOBJ_NAME); int iteratorId = query.GetRelatedValues(sourceGlobalId, properties, association); int resourcesLeft = query.IteratorResourcesLeft(iteratorId); xmlWriter = new XmlTextWriter(Config.Instance.ResultDirecotry + "\\GetRelatedValues_Results.xml", Encoding.Unicode); xmlWriter.Formatting = Formatting.Indented; while (resourcesLeft > 0) { List <ResourceDescription> rds = query.IteratorNext(numberOfResources, iteratorId); for (int i = 0; i < rds.Count; i++) { resultIds.Add(rds[i].Id); rds[i].ExportToXml(xmlWriter); xmlWriter.Flush(); } resourcesLeft = query.IteratorResourcesLeft(iteratorId); } query.IteratorClose(iteratorId); message = "Getting related values method successfully finished."; Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } catch (Exception e) { message = string.Format("Getting related values method failed for sourceGlobalId = {0} and association (propertyId = {1}, type = {2}). Reason: {3}", sourceGlobalId, association.PropertyId, association.Type, e.Message); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } finally { if (xmlWriter != null) { xmlWriter.Close(); } } return(resultIds); }
/// <summary> /// Inserts entity into the network model. /// </summary> /// <param name="rd">Description of the resource that should be inserted</param> private void InsertEntity(ResourceDescription rd) { if (rd == null) { CommonTrace.WriteTrace(CommonTrace.TraceVerbose, "Insert entity is not done because update operation is empty."); return; } long globalId = rd.Id; CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Inserting entity with GID ({0:x16}).", globalId); // check if mapping for specified global id already exists if (this.EntityExists(globalId)) { string message = String.Format("Failed to insert entity because entity with specified GID ({0:x16}) already exists in network model.", globalId); CommonTrace.WriteTrace(CommonTrace.TraceError, message); throw new Exception(message); } try { // find type DMSType type = (DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(globalId); Container container = null; // get container or create container if (ContainerExists(type)) { container = GetContainer(type); } else { container = new Container(); networkDataModel.Add(type, container); } // create entity and add it to container IdentifiedObject io = container.CreateEntity(globalId); // apply properties on created entity if (rd.Properties != null) { foreach (Property property in rd.Properties) { // globalId must not be set as property if (property.Id == ModelCode.IDOBJ_GID) { continue; } if (property.Type == PropertyType.Reference) { // if property is a reference to another entity long targetGlobalId = property.AsReference(); if (targetGlobalId != 0) { if (!EntityExists(targetGlobalId)) { string message = string.Format("Failed to get target entity with GID: 0x{0:X16}. {1}", targetGlobalId); throw new Exception(message); } // get referenced entity for update IdentifiedObject targetEntity = GetEntity(targetGlobalId); targetEntity.AddReference(property.Id, io.GlobalId); io.SetProperty(property); } } else { io.SetProperty(property); } } } CommonTrace.WriteTrace(CommonTrace.TraceVerbose, "Inserting entity with GID ({0:x16}) successfully finished.", globalId); } catch (Exception ex) { string message = String.Format("Failed to insert entity (GID = 0x{0:x16}) into model. {1}", rd.Id, ex.Message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); throw new Exception(message); } }
private void Commit(object sender, EventArgs e) { bool commitResultScadaCR; bool commitResultScadaCMD; bool commitResultSCADA = true; bool commitResultCE = true; bool commitResultNMS = false; try { if (toRespond == 4) { commitResultScadaCR = false; commitResultScadaCMD = false; commitResultCE = false; commitResultScadaCR = TransactionScadaPRProxy.Instance.Commit(); commitResultScadaCMD = TransactionScadaCDProxy.Instance.Commit(); commitResultSCADA = commitResultScadaCMD && commitResultScadaCR; commitResultCE = TransactionCEProxy.Instance.Commit(); if (!commitResultScadaCR) { updateResult.Message += String.Format("\nCommit phase failed for SCADA Processing Service"); } else { updateResult.Message += String.Format("\nChanges successfully applied on SCADA Processing Service"); } if (!commitResultScadaCMD) { updateResult.Message += String.Format("\nCommit phase failed for SCADA Commanding Service"); } else { updateResult.Message += String.Format("\nChanges successfully applied on SCADA Commanding Service"); } if (!commitResultCE) { updateResult.Message += String.Format("\nCommit phase failed for Calculation Engine Service"); } else { updateResult.Message += String.Format("\nChanges successfully applied on Calculation Engine Service"); } } else if (toRespond == 2) { commitResultCE = false; commitResultCE = TransactionCEProxy.Instance.Commit(); if (!commitResultCE) { updateResult.Message += String.Format("\nCommit phase failed for Calculation Engine Service"); } else { updateResult.Message += String.Format("\nChanges successfully applied on Calculation Engine Service"); } } else if (toRespond == 3) { commitResultScadaCR = false; commitResultScadaCMD = false; commitResultScadaCR = TransactionScadaPRProxy.Instance.Commit(); commitResultScadaCMD = TransactionScadaCDProxy.Instance.Commit(); if (!commitResultScadaCR) { updateResult.Message += String.Format("\nCommit phase failed for SCADA Processing Service"); } else { updateResult.Message += String.Format("\nChanges successfully applied on SCADA Processing Service"); } if (!commitResultScadaCMD) { updateResult.Message += String.Format("\nCommit phase failed for SCADA Commanding Service"); } else { updateResult.Message += String.Format("\nChanges successfully applied on SCADA Commanding Service"); } } } catch (Exception ex) { CommonTrace.WriteTrace(CommonTrace.TraceError, "Transaction Manager Service failed in Commit phase.\nResult message: {0}\nException message: {1}", updateResult.Message, ex.Message); CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Starting Rollback phase ... "); try { TransactionNMSProxy.Instance.Rollback(); CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Rollback for NMS successfully finished."); } catch (Exception exc) { CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Rollback for NMS - Message: {0}", exc.Message); } try { TransactionScadaPRProxy.Instance.Rollback(); CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Rollback for SCADA Processing successfully finished."); } catch (Exception exc) { CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Rollback for SCADA Processing - Message: {0}", exc.Message); } try { TransactionScadaCDProxy.Instance.Rollback(); CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Rollback for SCADA Commanding successfully finished."); } catch (Exception exc) { CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Rollback for SCADA Commanding - Message: {0}", exc.Message); } try { TransactionCEProxy.Instance.Rollback(); CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Rollback for CE successfully finished."); } catch (Exception exc) { CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Rollback for CE - Message: {0}", exc.Message); } } if (commitResultCE && commitResultSCADA) { CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Commit phase for all services succeeded. Starting commit for NMS!"); commitResultNMS = TransactionNMSProxy.Instance.Commit(); } if (commitResultNMS && commitResultSCADA && commitResultCE) { CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Commit phase finished successfully for all services!"); } else { CommonTrace.WriteTrace(CommonTrace.TraceWarning, "Commit phase failed!"); updateResult.Message += string.Format("\nCommit pahse failed"); updateResult.GlobalIdPairs.Clear(); } updateResult.Message += String.Format("\n\nApply finished"); toRespond = 1; noRespone = 0; }
public List <long> GetExtentValues(ModelCode modelCode) { string message = "Getting extent values method started."; Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); XmlTextWriter xmlWriter = null; int iteratorId = 0; List <long> ids = new List <long>(); try { int numberOfResources = 2; int resourcesLeft = 0; List <ModelCode> properties = modelResourcesDesc.GetAllPropertyIds(modelCode); iteratorId = GdaQueryProxy.GetExtentValues(modelCode, properties); resourcesLeft = GdaQueryProxy.IteratorResourcesLeft(iteratorId); xmlWriter = new XmlTextWriter(Config.Instance.ResultDirecotry + "\\GetExtentValues_Results.xml", Encoding.Unicode); xmlWriter.Formatting = Formatting.Indented; while (resourcesLeft > 0) { List <ResourceDescription> rds = GdaQueryProxy.IteratorNext(numberOfResources, iteratorId); for (int i = 0; i < rds.Count; i++) { ids.Add(rds[i].Id); rds[i].ExportToXml(xmlWriter); xmlWriter.Flush(); } resourcesLeft = GdaQueryProxy.IteratorResourcesLeft(iteratorId); } GdaQueryProxy.IteratorClose(iteratorId); message = "Getting extent values method successfully finished."; Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } catch (Exception e) { message = string.Format("Getting extent values method failed for {0}.\n\t{1}", modelCode, e.Message); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } finally { if (xmlWriter != null) { xmlWriter.Close(); } } return(ids); }
private void DeleteEntity(ResourceDescription rd) { if (rd == null) { CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Delete entity is not done because update operation is empty."); return; } try { long globalId = rd.Id; CommonTrace.WriteTrace(CommonTrace.TraceVerbose, "Deleting entity with GID ({0:x16}).", globalId); // check if entity exists if (!this.EntityExists(globalId)) { string message = string.Format("Failed to delete entity because entity with specified GID ({0:x16}) does not exist in network model.", globalId); CommonTrace.WriteTrace(CommonTrace.TraceError, message); throw new Exception(message); } // get entity to be deleted IdentifiedObject io = GetEntity(globalId); // check if entity could be deleted (if it is not referenced by any other entity) if (io.IsReferenced) { Dictionary <ModelCode, List <long> > references = new Dictionary <ModelCode, List <long> >(); io.GetReferences(references, TypeOfReference.Target); StringBuilder sb = new StringBuilder(); foreach (KeyValuePair <ModelCode, List <long> > kvp in references) { foreach (long referenceGlobalId in kvp.Value) { sb.AppendFormat("0x{0:x16}, ", referenceGlobalId); } } string message = string.Format("Failed to delete entity (GID = 0x{0:x16}) because it is referenced by entities with GIDs: {1}.", globalId, sb.ToString()); CommonTrace.WriteTrace(CommonTrace.TraceError, message); throw new Exception(message); } // find property ids List <ModelCode> propertyIds = resourcesDescs.GetAllSettablePropertyIdsForEntityId(io.GID); // remove references Property property = null; foreach (ModelCode propertyId in propertyIds) { PropertyType propertyType = Property.GetPropertyType(propertyId); if (propertyType == PropertyType.Reference) { property = io.GetProperty(propertyId); if (propertyType == PropertyType.Reference) { // get target entity and remove reference to another entity long targetGlobalId = property.AsReference(); if (targetGlobalId != 0) { // get target entity IdentifiedObject targetEntity = GetEntity(targetGlobalId); // remove reference to another entity targetEntity.RemoveReference(propertyId, globalId); } } } } // remove entity form netowrk model DMSType type = (DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(globalId); Container container = GetContainer(type); container.RemoveEntity(globalId); // -------------------------------------------------- affectedEntities.Add(globalId, DeltaOpType.Delete); // -------------------------------------------------- CommonTrace.WriteTrace(CommonTrace.TraceVerbose, "Deleting entity with GID ({0:x16}) successfully finished.", globalId); } catch (Exception ex) { string message = string.Format("Failed to delete entity (GID = 0x{0:x16}) from model. {1}", rd.Id, ex.Message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); throw new Exception(message); } }
public UpdateResult Prepare(ref Delta delta) { try { transactionCallback = OperationContext.Current.GetCallbackChannel <ITransactionCallback>(); updateResult = new UpdateResult(); listOfAnalogCopy = new List <AnalogLocation>(); listOfDiscretesCopy = new List <DiscreteLocation>(); // napravi kopiju od originala foreach (AnalogLocation alocation in listOfAnalog) { listOfAnalogCopy.Add(alocation.Clone() as AnalogLocation); } foreach (DiscreteLocation dlocation in listOfDiscretes) { listOfDiscretesCopy.Add(dlocation.Clone() as DiscreteLocation); } Analog analog = null; Discrete discrete = null; foreach (ResourceDescription analogRd in delta.InsertOperations) { if ((DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(analogRd.Id) == (DMSType.ANALOG)) { foreach (Property prop in analogRd.Properties) { analog = ResourcesDescriptionConverter.ConvertTo <Analog>(analogRd); listOfAnalogCopy.Add(new AnalogLocation() { Analog = analog, StartAddress = Int32.Parse(analog.ScadaAddress.Split('_')[1]), Length = 2, LengthInBytes = 4 }); } } else if ((DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(analogRd.Id) == (DMSType.DISCRETE)) { foreach (Property prop in analogRd.Properties) { discrete = ResourcesDescriptionConverter.ConvertTo <Discrete>(analogRd); listOfDiscretes.Add(new DiscreteLocation() { Discrete = discrete, StartAddress = Int32.Parse(discrete.ScadaAddress.Split('_')[1]), Length = 1, LengthInBytes = 2 }); } } } foreach (ResourceDescription analogRd in delta.UpdateOperations) { if ((DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(analogRd.Id) == (DMSType.ANALOG)) { foreach (Property prop in analogRd.Properties) { analog = ResourcesDescriptionConverter.ConvertTo <Analog>(analogRd); foreach (AnalogLocation al in listOfAnalogCopy) { if (al.Analog.Mrid.Equals(analog.Mrid)) { if (analog.MaxValue != al.Analog.MaxValue && analog.MaxValue != 0) { al.Analog.MaxValue = analog.MaxValue; } else if (analog.MeasurmentType != al.Analog.MeasurmentType && analog.MeasurmentType.ToString() != "") { al.Analog.MeasurmentType = analog.MeasurmentType; } else if (analog.MinValue != al.Analog.MinValue && analog.MinValue != 0) { al.Analog.MinValue = analog.MinValue; } else if (analog.Name != al.Analog.Name && analog.Name.ToString() != "") { al.Analog.Name = analog.Name; } else if (analog.AliasName != al.Analog.AliasName && analog.AliasName.ToString() != "") { al.Analog.AliasName = analog.AliasName; } else if (analog.NormalValue != al.Analog.NormalValue && analog.NormalValue != 0) { al.Analog.NormalValue = analog.NormalValue; } else if (analog.PowerSystemResource != al.Analog.PowerSystemResource && analog.PowerSystemResource.ToString() != "") { al.Analog.PowerSystemResource = analog.PowerSystemResource; } else if (analog.Direction != al.Analog.Direction && analog.Direction.ToString() != "") { al.Analog.Direction = analog.Direction; } else if (analog.ScadaAddress != al.Analog.ScadaAddress && analog.ScadaAddress.ToString() != "") { al.Analog.ScadaAddress = analog.ScadaAddress; } } } } } else if ((DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(analogRd.Id) == (DMSType.DISCRETE)) { foreach (Property prop in analogRd.Properties) { discrete = ResourcesDescriptionConverter.ConvertTo <Discrete>(analogRd); foreach (DiscreteLocation al in listOfDiscretesCopy) { if (al.Discrete.Mrid.Equals(discrete.Mrid)) { if (discrete.MaxValue != al.Discrete.MaxValue && discrete.MaxValue != 0) { al.Discrete.MaxValue = discrete.MaxValue; } else if (discrete.MeasurmentType != al.Discrete.MeasurmentType && discrete.MeasurmentType.ToString() != "") { al.Discrete.MeasurmentType = discrete.MeasurmentType; } else if (discrete.MinValue != al.Discrete.MinValue && discrete.MinValue != 0) { al.Discrete.MinValue = discrete.MinValue; } else if (discrete.Name != al.Discrete.Name && discrete.Name.ToString() != "") { al.Discrete.Name = discrete.Name; } else if (discrete.AliasName != al.Discrete.AliasName && discrete.AliasName.ToString() != "") { al.Discrete.AliasName = discrete.AliasName; } else if (discrete.NormalValue != al.Discrete.NormalValue && discrete.NormalValue != 0) { al.Discrete.NormalValue = discrete.NormalValue; } else if (discrete.PowerSystemResource != al.Discrete.PowerSystemResource && discrete.PowerSystemResource.ToString() != "") { al.Discrete.PowerSystemResource = discrete.PowerSystemResource; } else if (discrete.Direction != al.Discrete.Direction && discrete.Direction.ToString() != "") { al.Discrete.Direction = discrete.Direction; } else if (discrete.ScadaAddress != al.Discrete.ScadaAddress && discrete.ScadaAddress.ToString() != "") { al.Discrete.ScadaAddress = discrete.ScadaAddress; } } } } } } updateResult.Message = "SCADA CMD Transaction Prepare finished."; updateResult.Result = ResultType.Succeeded; CommonTrace.WriteTrace(CommonTrace.TraceInfo, "SCADA CMD Transaction Prepare finished successfully."); transactionCallback.Response("OK"); } catch (Exception e) { updateResult.Message = "SCADA CMD Transaction Prepare finished."; updateResult.Result = ResultType.Failed; CommonTrace.WriteTrace(CommonTrace.TraceWarning, "SCADA CMD Transaction Prepare failed. Message: {0}", e.Message); transactionCallback.Response("ERROR"); } return(updateResult); }
public List <List <string> > GetValuesAndPath(long globalId) { List <string> path = new List <string>(); List <string> strProps = new List <string>(); string message = "Getting values method started."; Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); XmlTextWriter xmlWriter = null; ResourceDescription rd = null; try { short type = ModelCodeHelper.ExtractTypeFromGlobalId(globalId); List <ModelCode> properties = modelResourcesDesc.GetAllPropertyIds((DMSType)type); rd = GdaQueryProxy.GetValues(globalId, properties); foreach (Property prop in rd.Properties) { switch (prop.Type) { case PropertyType.Bool: strProps.Add(prop.Id.ToString() + "~" + prop.AsBool().ToString()); break; case PropertyType.Int32: strProps.Add(prop.Id.ToString() + "~" + prop.AsInt().ToString()); break; case PropertyType.Int64: if (prop.Id.ToString().Contains("DATE")) { strProps.Add(prop.Id.ToString() + "~" + new DateTime(prop.AsLong()).ToString()); } else { strProps.Add(prop.Id.ToString() + "~" + prop.AsLong().ToString()); } break; case PropertyType.Float: strProps.Add(prop.Id.ToString() + "~" + prop.AsFloat().ToString()); break; case PropertyType.String: strProps.Add(prop.Id.ToString() + "~" + prop.AsString().ToString()); break; case PropertyType.Reference: strProps.Add(prop.Id.ToString() + "~" + prop.AsReference().ToString()); break; case PropertyType.Enum: strProps.Add(prop.Id.ToString() + "~" + prop.AsEnum().ToString()); break; case PropertyType.ReferenceVector: string val = prop.Id.ToString() + "~"; foreach (var item in prop.AsLongs()) { val += item.ToString() + "\n"; } strProps.Add(val); break; default: strProps.Add(prop.Id.ToString() + "~" + "Empty"); break; } } xmlWriter = new XmlTextWriter(Config.Instance.ResultDirecotry + "\\GetValues_Results.xml", Encoding.Unicode); path.Add(Config.Instance.ResultDirecotry + "\\GetValues_Results.xml"); xmlWriter.Formatting = Formatting.Indented; rd.ExportToXml(xmlWriter); xmlWriter.Flush(); message = "Getting values method successfully finished."; Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } catch (Exception e) { message = string.Format("Getting values method for entered id = {0} failed.\n\t{1}", globalId, e.Message); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } finally { if (xmlWriter != null) { xmlWriter.Close(); } } List <List <string> > strRet = new List <List <string> >(); strRet.Add(path); strRet.Add(strProps); return(strRet); }
private void InsertEntity(ResourceDescription rd, out ResourceDescription newRd) { newRd = rd; if (rd == null) { CommonTrace.WriteTrace(CommonTrace.TraceVerbose, "Insert entity is not done because update operation is empty."); throw new Exception(); } long globalId = rd.Id; CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Inserting entity with GID ({0:x16}).", globalId); // check if mapping for specified global id already exists if (this.EntityExists(globalId)) { string message = string.Format("Failed to insert entity because entity with specified GID ({0:x16}) already exists in network model.", globalId); CommonTrace.WriteTrace(CommonTrace.TraceError, message); throw new Exception(message); } try { // find type DMSType type = (DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(globalId); //check mrid already exist // if exist made mapping old-new mrids if (CheckMridExist(type, rd)) { var typedCollection = networkDataModelCopy[type]; var objMrid = rd.Properties.Single(x => x.Id == ModelCode.IDOBJ_MRID); var result = typedCollection.Entities.Values.SingleOrDefault(x => x.MRID == objMrid.PropertyValue.StringValue); GidHelper[globalId] = result.GID; return; } Container container = null; // get container or create container if (ContainerExists(type)) { container = GetContainer(type); } else { container = new Container(); networkDataModelCopy.Add(type, container); } // create entity and add it to container IdentifiedObject io = container.CreateEntity(globalId); // -------------------------------------------------- affectedEntities.Add(globalId, DeltaOpType.Insert); // -------------------------------------------------- // apply properties on created entity if (rd.Properties != null) { foreach (Property property in rd.Properties) { // globalId must not be set as property if (property.Id == ModelCode.IDOBJ_GID) { continue; } if (property.Type == PropertyType.Reference) { // if property is a reference to another entity long targetGlobalId = property.AsReference(); if (GidHelper.ContainsKey(targetGlobalId)) { //Update old-new mrids targetGlobalId = GidHelper[targetGlobalId]; newRd.Properties.Single(x => x.Id == property.Id).SetValue(targetGlobalId); } if (targetGlobalId != 0) { if (!EntityExists(targetGlobalId)) { string message = string.Format("Failed to get target entity with GID: 0x{0:X16}. {1}", targetGlobalId); throw new Exception(message); } // get referenced entity for update IdentifiedObject targetEntity = GetEntity(targetGlobalId); targetEntity.AddReference(property.Id, io.GID); } io.SetProperty(property); } else { io.SetProperty(property); } } } CommonTrace.WriteTrace(CommonTrace.TraceVerbose, "Inserting entity with GID ({0:x16}) successfully finished.", globalId); } catch (Exception ex) { string message = string.Format("Failed to insert entity (GID = 0x{0:x16}) into model. {1}", rd.Id, ex.Message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); throw new Exception(message); } }
public List <long> GetExtentValues(ModelCode modelCodeType, List <ModelCode> properties, StringBuilder sb) { var message = "Getting extent values method started."; CommonTrace.WriteTrace(CommonTrace.TraceError, message); int iteratorId = 0; int resourcesLeft = 0; int numberOfResources = 300; var ids = new List <long>(); var tempSb = new StringBuilder(); try { iteratorId = GdaQueryProxy.GetExtentValues(modelCodeType, properties); resourcesLeft = GdaQueryProxy.IteratorResourcesLeft(iteratorId); while (resourcesLeft > 0) { List <ResourceDescription> rds = GdaQueryProxy.IteratorNext(numberOfResources, iteratorId); foreach (var rd in rds) { if (rd == null) { continue; } tempSb.Append($"\nEntity with gid: 0x{rd.Id:X16}" + Environment.NewLine); foreach (var property in rd.Properties) { switch (property.Type) { case PropertyType.Int64: StringAppender.AppendLong(tempSb, property); break; case PropertyType.Float: StringAppender.AppendFloat(tempSb, property); break; case PropertyType.String: StringAppender.AppendString(tempSb, property); break; case PropertyType.Reference: StringAppender.AppendReference(tempSb, property); break; case PropertyType.ReferenceVector: StringAppender.AppendReferenceVector(tempSb, property); break; case PropertyType.Enum: StringAppender.AppendEnum(tempSb, property); break; case PropertyType.DateTime: StringAppender.AppendDateTime(tempSb, property); break; default: tempSb.Append($"\t{property.Id}: {property.PropertyValue.LongValue}{Environment.NewLine}"); break; } } ids.Add(rd.Id); } resourcesLeft = GdaQueryProxy.IteratorResourcesLeft(iteratorId); } GdaQueryProxy.IteratorClose(iteratorId); message = "Getting extent values method successfully finished."; CommonTrace.WriteTrace(CommonTrace.TraceError, message); } catch (Exception e) { message = string.Format("Getting extent values method failed for {0}.\n\t{1}", modelCodeType, e.Message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } if (sb != null) { sb.Append(tempSb.ToString()); } return(ids); }
public List <List <string> > GetRelatedValuesAndPath(long sourceGlobalId, Association association) { string message = "Getting related values method started."; List <string> path = new List <string>(); List <string> strProps = new List <string>(); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); List <long> resultIds = new List <long>(); XmlTextWriter xmlWriter = null; int numberOfResources = 2; try { List <ModelCode> properties = new List <ModelCode>(); properties.Add(ModelCode.IDOBJ_ALIASNAME); properties.Add(ModelCode.IDOBJ_MRID); properties.Add(ModelCode.IDOBJ_NAME); int iteratorId = GdaQueryProxy.GetRelatedValues(sourceGlobalId, properties, association); int resourcesLeft = GdaQueryProxy.IteratorResourcesLeft(iteratorId); xmlWriter = new XmlTextWriter(Config.Instance.ResultDirecotry + "\\GetRelatedValues_Results.xml", Encoding.Unicode); path.Add(Config.Instance.ResultDirecotry + "\\GetRelatedValues_Results.xml"); xmlWriter.Formatting = Formatting.Indented; while (resourcesLeft > 0) { List <ResourceDescription> rds = GdaQueryProxy.IteratorNext(numberOfResources, iteratorId); for (int i = 0; i < rds.Count; i++) { resultIds.Add(rds[i].Id); properties.Clear(); properties = modelResourcesDesc.GetAllPropertyIds((DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(rds[i].Id)); ResourceDescription rd = GdaQueryProxy.GetValues(rds[i].Id, properties); rd.ExportToXml(xmlWriter); foreach (Property prop in rd.Properties) { switch (prop.Type) { case PropertyType.Bool: strProps.Add(prop.Id.ToString() + "~" + prop.AsBool().ToString()); break; case PropertyType.Int32: strProps.Add(prop.Id.ToString() + "~" + prop.AsInt().ToString()); break; case PropertyType.Int64: if (prop.Id.ToString().Contains("DATE")) { strProps.Add(prop.Id.ToString() + "~" + new DateTime(prop.AsLong()).ToString()); } else { strProps.Add(prop.Id.ToString() + "~" + prop.AsLong().ToString()); } break; case PropertyType.Float: strProps.Add(prop.Id.ToString() + "~" + prop.AsFloat().ToString()); break; case PropertyType.String: strProps.Add(prop.Id.ToString() + "~" + prop.AsString().ToString()); break; case PropertyType.Reference: strProps.Add(prop.Id.ToString() + "~" + prop.AsReference().ToString()); break; case PropertyType.Enum: strProps.Add(prop.Id.ToString() + "~" + prop.AsEnum().ToString()); break; case PropertyType.ReferenceVector: string val = prop.Id.ToString() + "~"; foreach (var item in prop.AsLongs()) { val += item.ToString() + "\n"; } strProps.Add(val); break; default: strProps.Add(prop.Id.ToString() + "~" + "Empty"); break; } } xmlWriter.Flush(); } resourcesLeft = GdaQueryProxy.IteratorResourcesLeft(iteratorId); } GdaQueryProxy.IteratorClose(iteratorId); message = "Getting related values method successfully finished."; Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } catch (Exception e) { message = string.Format("Getting related values method failed for sourceGlobalId = {0} and association (propertyId = {1}, type = {2}). Reason: {3}", sourceGlobalId, association.PropertyId, association.Type, e.Message); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } finally { if (xmlWriter != null) { xmlWriter.Close(); } } List <List <string> > strRet = new List <List <string> >(); strRet.Add(path); strRet.Add(strProps); return(strRet); }
public List <long> GetRelatedValues(long sourceGlobalId, List <ModelCode> properties, Association association, StringBuilder sb) { var message = "Getting related values method started."; CommonTrace.WriteTrace(CommonTrace.TraceError, message); int iteratorId = 0; int resourcesLeft = 0; int numberOfResources = 500; var resultIds = new List <long>(); var tempSb = new StringBuilder(); try { iteratorId = GdaQueryProxy.GetRelatedValues(sourceGlobalId, properties, association); resourcesLeft = GdaQueryProxy.IteratorResourcesLeft(iteratorId); while (resourcesLeft > 0) { List <ResourceDescription> rds = GdaQueryProxy.IteratorNext(numberOfResources, iteratorId); foreach (var rd in rds) { if (rd == null) { continue; } tempSb.Append($"\nEntity with gid: 0x{rd.Id:X16}" + Environment.NewLine); foreach (Property property in rd.Properties) { switch (property.Type) { case PropertyType.Int64: StringAppender.AppendLong(tempSb, property); break; case PropertyType.Float: StringAppender.AppendFloat(tempSb, property); break; case PropertyType.String: StringAppender.AppendString(tempSb, property); break; case PropertyType.Reference: StringAppender.AppendReference(tempSb, property); break; case PropertyType.ReferenceVector: StringAppender.AppendReferenceVector(tempSb, property); break; case PropertyType.Enum: StringAppender.AppendEnum(tempSb, property); break; case PropertyType.DateTime: StringAppender.AppendDateTime(tempSb, property); break; default: tempSb.Append($"\t{property.Id}: {property.PropertyValue.LongValue}{Environment.NewLine}"); break; } } resultIds.Add(rd.Id); } resourcesLeft = GdaQueryProxy.IteratorResourcesLeft(iteratorId); } GdaQueryProxy.IteratorClose(iteratorId); message = "Getting related values method successfully finished."; CommonTrace.WriteTrace(CommonTrace.TraceError, message); } catch (Exception e) { message = $"Getting related values method failed for sourceGlobalId = {sourceGlobalId} and association (propertyId = {association.PropertyId}, type = {association.Type}). Reason: {e.Message}"; CommonTrace.WriteTrace(CommonTrace.TraceError, message); } if (sb != null) { sb.Append(tempSb.ToString()); } return(resultIds); }
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); }
public UpdateResult ModelUpdate(Delta delta) { deltaToApply = delta; noRespone = 0; toRespond = 1; Delta ceDelta = new Delta(); Delta scadaDelta = new Delta(); updateResult = new UpdateResult(); List <long> idToRemove = new List <long>(10); Delta analogsDelta = delta.SeparateDeltaForEMSType(DMSType.ANALOG); Delta energyConsumerDelta = delta.SeparateDeltaForEMSType(DMSType.ENERGY_CONSUMER); Delta generatorDelta = delta.SeparateDeltaForEMSType(DMSType.GENERATOR); Delta discreteDelta = delta.SeparateDeltaForEMSType(DMSType.DISCRETE); Delta substationDelta = delta.SeparateDeltaForEMSType(DMSType.SUBSTATION); Delta geograficalRegionDelta = delta.SeparateDeltaForEMSType(DMSType.GEOGRAFICAL_REGION); ceDelta = generatorDelta + energyConsumerDelta; scadaDelta = analogsDelta + discreteDelta; if (scadaDelta.InsertOperations.Count != 0 || scadaDelta.UpdateOperations.Count != 0) { toRespond += 2; } if (ceDelta.InsertOperations.Count != 0 || ceDelta.UpdateOperations.Count != 0) { toRespond++; } try { // first transaction - send delta to NMS try { updateResult = TransactionNMSProxy.Instance.Prepare(ref delta); } catch (Exception e) { CommonTrace.WriteTrace(CommonTrace.TraceError, "Transacion: NMS Prepare phase failed; Message: {0}", e.Message); updateResult.Message = "Transaction: Failed to apply delta on Network Model Service"; updateResult.Result = ResultType.Failed; return(updateResult); } // create new delta object from delta with gids analogsDelta = delta.SeparateDeltaForEMSType(DMSType.ANALOG); energyConsumerDelta = delta.SeparateDeltaForEMSType(DMSType.ENERGY_CONSUMER); generatorDelta = delta.SeparateDeltaForEMSType(DMSType.GENERATOR); discreteDelta = delta.SeparateDeltaForEMSType(DMSType.DISCRETE); ceDelta = energyConsumerDelta + generatorDelta; scadaDelta = analogsDelta + discreteDelta; ceDeltaToApply = ceDelta; if (toRespond == 2) { if (ceDelta.InsertOperations.Count != 0 || ceDelta.UpdateOperations.Count != 0) { try { TransactionCEProxy.Instance.Prepare(ref ceDelta); } catch (Exception e) { CommonTrace.WriteTrace(CommonTrace.TraceError, "Transacion: CE Prepare phase failed; Message: {0}", e.Message); updateResult.Message = "Transaction: Failed to apply delta on Calculation Engine Service"; updateResult.Result = ResultType.Failed; return(updateResult); } } else { try { TransactionScadaPRProxy.Instance.Prepare(ref scadaDelta); TransactionScadaCDProxy.Instance.Prepare(ref scadaDelta); } catch (Exception e) { CommonTrace.WriteTrace(CommonTrace.TraceError, "Transacion: SCADA Prepare phase failed; Message: {0}", e.Message); updateResult.Message = "Transaction: Failed to apply delta on SCADA PR and CMD Services"; updateResult.Result = ResultType.Failed; return(updateResult); } } } else if (toRespond == 3) { // second transaction - send ceDelta to CE, analogDelta to SCADA try { TransactionScadaPRProxy.Instance.Prepare(ref scadaDelta); TransactionScadaCDProxy.Instance.Prepare(ref scadaDelta); } catch (Exception e) { CommonTrace.WriteTrace(CommonTrace.TraceError, "Transacion: Prepare phase failed for SCADA Services; Message: {0}", e.Message); updateResult.Message = "Transaction: Failed to apply delta on SCADA Services"; updateResult.Result = ResultType.Failed; return(updateResult); } } else if (toRespond == 4) { try { TransactionCEProxy.Instance.Prepare(ref ceDelta); TransactionScadaPRProxy.Instance.Prepare(ref scadaDelta); TransactionScadaCDProxy.Instance.Prepare(ref scadaDelta); } catch (Exception e) { CommonTrace.WriteTrace(CommonTrace.TraceError, "Transacion: Prepare phase failed for CE or SCADA Services; Message: {0}", e.Message); updateResult.Message = "Transaction: Failed to apply delta on Calculation Engine or SCADA Services"; updateResult.Result = ResultType.Failed; return(updateResult); } } } catch (Exception e) { // ako se neki exception desio prilikom transakcije - radi rollback CommonTrace.WriteTrace(CommonTrace.TraceError, "Transaction failed; Message: {0}", e.Message); CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Start Rollback!"); TransactionNMSProxy.Instance.Rollback(); TransactionScadaPRProxy.Instance.Rollback(); TransactionScadaCDProxy.Instance.Rollback(); TransactionCEProxy.Instance.Rollback(); CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Rollback finished!"); } Thread.Sleep(5000); return(updateResult); }
public List <ResourceDescription> GetRelatedValues(long sourceGlobalId, Association association) { string message = "Getting related values method started."; Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); List <ResourceDescription> resultRds = new List <ResourceDescription>(); int numberOfResources = 5; List <long> ids = new List <long>(); try { List <ModelCode> properties = new List <ModelCode>(); //int iteratorId = GdaQueryProxy.GetRelatedValues(sourceGlobalId, properties, association); //int resourcesLeft = GdaQueryProxy.IteratorResourcesLeft(iteratorId); int iteratorId = NetworkModelGDAProxy.Instance.GetRelatedValues(sourceGlobalId, properties, association); int resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorId); //import ids while (resourcesLeft > 0) { //List<ResourceDescription> rds = GdaQueryProxy.IteratorNext(numberOfResources, iteratorId); List <ResourceDescription> rds = NetworkModelGDAProxy.Instance.IteratorNext(numberOfResources, iteratorId); foreach (var rd in rds) { ids.Add(rd.Id); } //resourcesLeft = GdaQueryProxy.IteratorResourcesLeft(iteratorId); resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorId); } //find all properties for each id and call foreach (var id in ids) { properties = modelResourcesDesc.GetAllPropertyIdsForEntityId(id); //resultRds.Add(GdaQueryProxy.GetValues(id, properties)); resultRds.Add(NetworkModelGDAProxy.Instance.GetValues(id, properties)); } //GdaQueryProxy.IteratorClose(iteratorId); NetworkModelGDAProxy.Instance.IteratorClose(iteratorId); message = "Getting related values method successfully finished."; Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } catch (Exception e) { message = string.Format("Getting related values method failed for sourceGlobalId = {0} and association (propertyId = {1}, type = {2}). Reason: {3}", sourceGlobalId, association.PropertyId, association.Type, e.Message); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } return(resultRds); }
public List <List <string> > GetExtentValuesAndPath(ModelCode modelCode) { string message = "Getting extent values method started."; List <string> path = new List <string>(); List <string> strProps = new List <string>(); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); XmlTextWriter xmlWriter = null; int iteratorId = 0; List <long> ids = new List <long>(); try { int numberOfResources = 2; int resourcesLeft = 0; List <ModelCode> properties = modelResourcesDesc.GetAllPropertyIds(modelCode); iteratorId = GdaQueryProxy.GetExtentValues(modelCode, properties); resourcesLeft = GdaQueryProxy.IteratorResourcesLeft(iteratorId); xmlWriter = new XmlTextWriter(Config.Instance.ResultDirecotry + "\\GetExtentValues_Results.xml", Encoding.Unicode); path.Add(Config.Instance.ResultDirecotry + "\\GetExtentValues_Results.xml"); xmlWriter.Formatting = Formatting.Indented; while (resourcesLeft > 0) { List <ResourceDescription> rds = GdaQueryProxy.IteratorNext(numberOfResources, iteratorId); for (int i = 0; i < rds.Count; i++) { ids.Add(rds[i].Id); rds[i].ExportToXml(xmlWriter); foreach (Property prop in rds[i].Properties) { switch (prop.Type) { case PropertyType.Bool: strProps.Add(prop.Id.ToString() + "~" + prop.AsBool().ToString()); break; case PropertyType.Int32: strProps.Add(prop.Id.ToString() + "~" + prop.AsInt().ToString()); break; case PropertyType.Int64: if (prop.Id.ToString().Contains("DATE")) { strProps.Add(prop.Id.ToString() + "~" + new DateTime(prop.AsLong()).ToString()); } else { strProps.Add(prop.Id.ToString() + "~" + prop.AsLong().ToString()); } break; case PropertyType.Float: strProps.Add(prop.Id.ToString() + "~" + prop.AsFloat().ToString()); break; case PropertyType.String: strProps.Add(prop.Id.ToString() + "~" + prop.AsString().ToString()); break; case PropertyType.Reference: strProps.Add(prop.Id.ToString() + "~" + prop.AsReference().ToString()); break; case PropertyType.Enum: strProps.Add(prop.Id.ToString() + "~" + prop.AsEnum().ToString()); break; case PropertyType.ReferenceVector: string val = prop.Id.ToString() + "~"; foreach (var item in prop.AsLongs()) { val += item.ToString() + "\n"; } strProps.Add(val); break; default: strProps.Add(prop.Id.ToString() + "~" + "Empty"); break; } } xmlWriter.Flush(); } resourcesLeft = GdaQueryProxy.IteratorResourcesLeft(iteratorId); } GdaQueryProxy.IteratorClose(iteratorId); message = "Getting extent values method successfully finished."; Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } catch (Exception e) { message = string.Format("Getting extent values method failed for {0}.\n\t{1}", modelCode, e.Message); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); } finally { if (xmlWriter != null) { xmlWriter.Close(); } } List <List <string> > strRet = new List <List <string> >(); strRet.Add(path); strRet.Add(strProps); return(strRet); }
public UpdateResult ApplyDelta(Delta delta) { bool applyingStarted = false; bool transactionSucceded = false; UpdateResult updateResult = new UpdateResult(); Delta newDelta = new Delta(); GetShallowCopyModel(); affectedEntities = new AffectedEntities(); try { CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Applying delta to network model."); Dictionary <short, int> typesCounters = GetCounters(); Dictionary <long, long> globalIdPairs = new Dictionary <long, long>(); var result = GetAllCounters(typesCounters); Delta.Counter = result; delta.FixNegativeToPositiveIds(ref typesCounters, ref globalIdPairs); updateResult.GlobalIdPairs = globalIdPairs; delta.SortOperations(); applyingStarted = true; foreach (ResourceDescription rd in delta.InsertOperations) { // We need newRd because old-new mapping InsertEntity(rd, out ResourceDescription newRd); newDelta.AddDeltaOperation(DeltaOpType.Insert, newRd, true); } #region Update&Delete foreach (ResourceDescription rd in delta.UpdateOperations) { UpdateEntity(rd); } foreach (ResourceDescription rd in delta.DeleteOperations) { DeleteEntity(rd); } #endregion transactionSucceded = TryApplyTransaction(); if (transactionSucceded) { MergeModelsFinal(); } } catch (Exception ex) { string message = string.Format("Applying delta to network model failed. {0}.", ex.Message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); applyingStarted = false; updateResult.Result = ResultType.Failed; updateResult.Message = message; } finally { if (applyingStarted && transactionSucceded) { if (newDelta.InsertOperations.Count > 0) { SaveDelta(delta); } } else { RestoreModel(); } if (updateResult.Result == ResultType.Succeeded) { string mesage = "Applying delta to network model successfully finished."; CommonTrace.WriteTrace(CommonTrace.TraceInfo, mesage); updateResult.Message = mesage; } } return(updateResult); }
private void InsertEntity(ResourceDescription rd) { if (rd == null) { string message = String.Format("MODBUS SIMULATOR - Insert entity is not done because update operation is empty."); CommonTrace.WriteTrace(CommonTrace.TraceVerbose, message); throw new Exception(message); } long globalId = rd.Id; string mrid = rd.Properties[0].PropertyValue.StringValue; CommonTrace.WriteTrace(CommonTrace.TraceInfo, "MODBUS SIMULATOR - Insertion of entity with GID ({0:x16}).", globalId); if (EntityExists(globalId, mrid)) { string message = String.Format("Failed to insert analog value because entity already exists in modbus simulator model."); CommonTrace.WriteTrace(CommonTrace.TraceError, message); throw new Exception(message); } try { //Gets object type depending on its Global ID DMSType type = (DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(globalId); //New DMSType Object IdentifiedObject io = CreateEntity(globalId); //If object has no properties the method is finished if (rd.Properties == null) { return; } foreach (Property property in rd.Properties) { //No point in setting the GlobalID since it is already set if (property.Id == ModelCode.IDOBJ_GID) { continue; } //Check if property is a Reference, set it if it is not if (property.Type != PropertyType.Reference) { io.SetProperty(property); continue; } //If it is, get an ID of the object which is a reference long targetGlobalId = property.AsReference(); // // wa DMSType tip = (DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(globalId); if (tip == DMSType.SUBSTATION || tip == DMSType.SYNCMACHINE) { continue; } if (targetGlobalId != 0) { //if it exists IdentifiedObject targetEntity = GetEntity(targetGlobalId); if (targetEntity == null) { CommonTrace.WriteTrace(CommonTrace.TraceInfo, "MODBUS SIMULATOR - Target entity is Substation.", globalId); continue; } targetEntity.AddReference(property.Id, io.GlobalId); } io.SetProperty(property); } CommonTrace.WriteTrace(CommonTrace.TraceVerbose, "MODBUS SIMULATOR - Insertion of entity with GID ({0:x16}) successfully finished.", globalId); } catch (Exception ex) { string message = String.Format("MODBUS SIMULATOR - Failed to insert entity (GID = 0x{0:x16}) into model. {1}", rd.Id, ex.Message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); throw new Exception(message); } }
private void UpdateEntity(ResourceDescription rd) { if (rd == null || rd.Properties == null && rd.Properties.Count == 0) { CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Update entity is not done because update operation is empty."); return; } try { long globalId = rd.Id; CommonTrace.WriteTrace(CommonTrace.TraceVerbose, "Updating entity with GID ({0:x16}).", globalId); if (!this.EntityExists(globalId)) { string message = string.Format("Failed to update entity because entity with specified GID ({0:x16}) does not exist in network model.", globalId); CommonTrace.WriteTrace(CommonTrace.TraceError, message); throw new Exception(message); } IdentifiedObject io = GetEntity(globalId); // -------------------------------------------------- affectedEntities.Add(globalId, DeltaOpType.Update); // -------------------------------------------------- // updating properties of entity foreach (Property property in rd.Properties) { if (property.Type == PropertyType.Reference) { long oldTargetGlobalId = io.GetProperty(property.Id).AsReference(); if (oldTargetGlobalId != 0) { IdentifiedObject oldTargetEntity = GetEntity(oldTargetGlobalId); oldTargetEntity.RemoveReference(property.Id, globalId); } // updating reference of entity long targetGlobalId = property.AsReference(); if (targetGlobalId != 0) { if (!EntityExists(targetGlobalId)) { string message = string.Format("Failed to get target entity with GID: 0x{0:X16}.", targetGlobalId); throw new Exception(message); } IdentifiedObject targetEntity = GetEntity(targetGlobalId); targetEntity.AddReference(property.Id, globalId); } // update value of the property in specified entity io.SetProperty(property); } else { // update value of the property in specified entity io.SetProperty(property); } } CommonTrace.WriteTrace(CommonTrace.TraceVerbose, "Updating entity with GID ({0:x16}) successfully finished.", globalId); } catch (Exception ex) { string message = string.Format("Failed to update entity (GID = 0x{0:x16}) in model. {1} ", rd.Id, ex.Message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); throw new Exception(message); } }
/// <summary> /// Returns entity (identified object) on the specified index. Throws an exception if entity does not exist. /// </summary> /// <param name="index">Index of the entity that should be returned</param> /// <returns>Instance of the entity in case it is found on specified position, otherwise throws exception</returns> public IdentifiedObject GetEntity(long globalId) { //short type = ModelCodeHelper.ExtractTypeFromGlobalId(globalId); DMSType type = (DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(globalId); switch (type) { case DMSType.AOR_GROUP: break; case DMSType.REGION: break; case DMSType.SUBREGION: break; case DMSType.SUBSTATION: break; case DMSType.SYNCMACHINE: foreach (SynchronousMachine item in dersCopy.Values) { if (item.GlobalId != globalId) { continue; } else { return(item); } } break; case DMSType.ANALOGVALUE: foreach (AnalogValue item in analogPointsCopy) { if (item.GlobalId != globalId) { continue; } else { return(item); } } break; case DMSType.DISCRETEVALUE: foreach (DiscreteValue item in discretPointsCopy) { if (item.GlobalId != globalId) { continue; } else { return(item); } } break; default: string message = String.Format("Failed to retrieve entity (GID = 0x{1:x16}) because entity doesn't exist.", globalId); CommonTrace.WriteTrace(CommonTrace.TraceError, message); throw new Exception(message); } return(null); }
public void AddAlarm(AlarmHelper alarm) { bool normalAlarm = false; if (Alarms.Count == 0 && alarm.Type.Equals(AlarmType.NORMAL)) { return; } PublishingStatus publishingStatus = PublishingStatus.INSERT; bool updated = false; try { alarm.AckState = AckState.Unacknowledged; if (string.IsNullOrEmpty(alarm.CurrentState)) { alarm.CurrentState = string.Format("{0} | {1}", State.Active, alarm.AckState); } // cleared status check foreach (AlarmHelper item in Alarms) { if (item.Gid.Equals(alarm.Gid) && item.CurrentState.Contains(State.Active.ToString())) { item.Severity = alarm.Severity; item.Value = alarm.Value; item.Message = alarm.Message; item.TimeStamp = alarm.TimeStamp; publishingStatus = PublishingStatus.UPDATE; updated = true; break; } else if (item.Gid.Equals(alarm.Gid) && item.CurrentState.Contains(State.Cleared.ToString())) { if (alarm.Type.Equals(AlarmType.NORMAL) && !item.Type.Equals(AlarmType.NORMAL.ToString())) { bool normalCreated = false; if (this.isNormalCreated.TryGetValue(alarm.Gid, out normalCreated)) { if (!normalCreated) { normalAlarm = true; } } break; } } } // ako je insert dodaj u listu - inace je updateovan if (publishingStatus.Equals(PublishingStatus.INSERT) && !updated && !alarm.Type.Equals(AlarmType.NORMAL)) { if (alarm.Type != AlarmType.DOM) { RemoveFromAlarms(alarm.Gid); this.Alarms.Add(alarm); if (InsertAlarmIntoDb(alarm)) { Console.WriteLine("Alarm with GID:{0} recorded into alarms database.", alarm.Gid); } this.isNormalCreated[alarm.Gid] = false; } else { this.Alarms.Add(alarm); if (InsertAlarmIntoDb(alarm)) { Console.WriteLine("Alarm with GID:{0} recorded into alarms database.", alarm.Gid); } this.isNormalCreated[alarm.Gid] = false; } } if (alarm.Type.Equals(AlarmType.NORMAL) && normalAlarm) { RemoveFromAlarms(alarm.Gid); this.Alarms.Add(alarm); this.Publisher.PublishAlarmsEvents(alarm, publishingStatus); this.isNormalCreated[alarm.Gid] = true; } else if (!alarm.Type.Equals(AlarmType.NORMAL)) { this.Publisher.PublishAlarmsEvents(alarm, publishingStatus); } //Console.WriteLine("AlarmsEvents: AddAlarm method"); string message = string.Format("Alarm on Analog Gid: {0} - Value: {1}", alarm.Gid, alarm.Value); CommonTrace.WriteTrace(CommonTrace.TraceInfo, message); } catch (Exception ex) { string message = string.Format("Greska ", ex.Message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); //throw new Exception(message); } }
public List <long> TestGetExtentValuesAllTypes() { string message = "Getting extent values for all DMS types started."; Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceInfo, message); List <ModelCode> properties = new List <ModelCode>(); List <long> ids = new List <long>(); int iteratorId = 0; int numberOfResources = 1000; DMSType currType = 0; try { foreach (DMSType type in Enum.GetValues(typeof(DMSType))) { if (type != DMSType.MASK_TYPE) { currType = type; properties = modelResourcesDesc.GetAllPropertyIds(type); iteratorId = GdaQueryProxy.GetExtentValues(modelResourcesDesc.GetModelCodeFromType(type), properties); int count = GdaQueryProxy.IteratorResourcesLeft(iteratorId); while (count > 0) { List <ResourceDescription> rds = GdaQueryProxy.IteratorNext(numberOfResources, iteratorId); for (int i = 0; i < rds.Count; i++) { ids.Add(rds[i].Id); } count = GdaQueryProxy.IteratorResourcesLeft(iteratorId); } bool ok = GdaQueryProxy.IteratorClose(iteratorId); message = string.Format("Number of {0} in model {1}.", type, ids.Count); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceInfo, message); } message = "Getting extent values for all DMS types successfully ended."; Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceInfo, message); } } catch (Exception e) { message = string.Format("Getting extent values for all DMS types failed for type {0}.\n\t{1}", currType, e.Message); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceInfo, message); throw; } return(ids); }
/// <summary> /// Method implements integrity update logic for scada cr component /// </summary> /// <returns></returns> public bool InitiateIntegrityUpdate() { List <ModelCode> properties = new List <ModelCode>(10); List <ModelCode> propertiesDiscrete = new List <ModelCode>(10); ModelCode modelCode = ModelCode.ANALOG; ModelCode modelCodeDiscrete = ModelCode.DISCRETE; int iteratorId = 0; int resourcesLeft = 0; int numberOfResources = 2; List <ResourceDescription> retList = new List <ResourceDescription>(5); List <ResourceDescription> retListDiscrete = new List <ResourceDescription>(5); try { properties = modelResourcesDesc.GetAllPropertyIds(modelCode); propertiesDiscrete = modelResourcesDesc.GetAllPropertyIds(modelCodeDiscrete); iteratorId = NetworkModelGDAProxy.Instance.GetExtentValues(modelCode, properties); resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorId); while (resourcesLeft > 0) { List <ResourceDescription> rds = NetworkModelGDAProxy.Instance.IteratorNext(numberOfResources, iteratorId); retList.AddRange(rds); resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorId); } NetworkModelGDAProxy.Instance.IteratorClose(iteratorId); var iteratorIdDiscrete = NetworkModelGDAProxy.Instance.GetExtentValues(modelCodeDiscrete, propertiesDiscrete); resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorIdDiscrete); while (resourcesLeft > 0) { List <ResourceDescription> rds = NetworkModelGDAProxy.Instance.IteratorNext(numberOfResources, iteratorIdDiscrete); retListDiscrete.AddRange(rds); resourcesLeft = NetworkModelGDAProxy.Instance.IteratorResourcesLeft(iteratorIdDiscrete); } NetworkModelGDAProxy.Instance.IteratorClose(iteratorIdDiscrete); } catch (Exception e) { message = string.Format("Getting extent values method failed for {0}.\n\t{1}", modelCode, e.Message); Console.WriteLine(message); Console.WriteLine("Trying again..."); CommonTrace.WriteTrace(CommonTrace.TraceError, "Trying again..."); NetworkModelGDAProxy.Instance = null; Thread.Sleep(1000); InitiateIntegrityUpdate(); return(false); } listOfAnalog.Clear(); try { foreach (ResourceDescription rd in retList) { Analog analog = ResourcesDescriptionConverter.ConvertTo <Analog>(rd); if ((DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(analog.PowerSystemResource) == DMSType.ENERGY_CONSUMER) { listOfAnalog.Add(new AnalogLocation() { Analog = analog, StartAddress = Int32.Parse(analog.ScadaAddress.Split('_')[1]), Length = 2, LengthInBytes = 4 }); } else { listOfAnalog.Add(new AnalogLocation() { Analog = analog, StartAddress = Int32.Parse(analog.ScadaAddress.Split('_')[1]), Length = 2, LengthInBytes = 4 }); } } foreach (ResourceDescription rd in retListDiscrete) { Discrete discrete = ResourcesDescriptionConverter.ConvertTo <Discrete>(rd); if ((DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(discrete.PowerSystemResource) == DMSType.ENERGY_CONSUMER) { listOfDiscretes.Add(new DiscreteLocation() { Discrete = discrete, StartAddress = Int32.Parse(discrete.ScadaAddress.Split('_')[1]), Length = 1, LengthInBytes = 2 }); } else { listOfDiscretes.Add(new DiscreteLocation() { Discrete = discrete, StartAddress = Int32.Parse(discrete.ScadaAddress.Split('_')[1]), Length = 1, LengthInBytes = 2 }); } } } catch (Exception e) { message = string.Format("Conversion to Analog object failed.\n\t{0}", e.Message); Console.WriteLine(message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); return(false); } message = string.Format("Integrity update: Number of {0} values: {1}", modelCode.ToString(), listOfAnalog.Count.ToString()); CommonTrace.WriteTrace(CommonTrace.TraceInfo, message); Console.WriteLine("Integrity update: Number of {0} values: {1}", modelCode.ToString(), listOfAnalog.Count.ToString()); return(true); }
public UpdateResult ApplyDelta(Delta delta) { insert = new HashSet <long>(); update = new HashSet <long>(); delete = new HashSet <long>(); bool applyingStarted = false; UpdateResult updateResult = new UpdateResult(); try { CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Applying delta to network model."); Dictionary <short, int> typesCounters = GetCounters(); Dictionary <long, long> globalIdPairs = new Dictionary <long, long>(); delta.FixNegativeToPositiveIds(ref typesCounters, ref globalIdPairs); updateResult.GlobalIdPairs = globalIdPairs; delta.SortOperations(); applyingStarted = true; foreach (ResourceDescription rd in delta.InsertOperations) { InsertEntity(rd); insert.Add(rd.Id); } foreach (ResourceDescription rd in delta.UpdateOperations) { UpdateEntity(rd); update.Add(rd.Id); } foreach (ResourceDescription rd in delta.DeleteOperations) { DeleteEntity(rd); delete.Add(rd.Id); } } catch (Exception ex) { string message = string.Format("Applying delta to network model failed. {0}.", ex.Message); CommonTrace.WriteTrace(CommonTrace.TraceError, message); updateResult.Result = ResultType.Failed; updateResult.Message = message; } finally { if (applyingStarted) { SaveDelta(delta); } if (updateResult.Result == ResultType.Succeeded) { string mesage = "Applying delta to network model successfully finished."; CommonTrace.WriteTrace(CommonTrace.TraceInfo, mesage); updateResult.Message = mesage; } } return(updateResult); }