// // Private constructor for Singleton. // private LiveStsFederationMetadata() { MetadataBase metadataBase = LoadMetadata(); SecurityTokenServiceDescriptor stsDescriptor = ReadStsDescriptor(metadataBase); _signingCertificates = ReadStsSigningCertificates(stsDescriptor); }
public void GetPoints(out MetadataBase watt, out MetadataBase powerFactor, out MetadataBase voltAmpre, out MetadataBase voltAmpreReactive) { watt = Watt; powerFactor = PowerFactor; voltAmpre = VoltAmpre; voltAmpreReactive = VoltAmpreReactive; }
public static Expression <Func <T, bool> > BuildFiltersExp(MetadataBase metadata, FilterBase initialFilter, List <LogicalFilter> logicalFilters) { if (metadata == null) { throw new ArgumentNullException(nameof(metadata)); } if (initialFilter == null) { throw new ArgumentNullException(nameof(initialFilter)); } ParameterExpression paramExp = Expression.Parameter(typeof(T), "parameter"); Expression exp = initialFilter.GetExpression(paramExp, metadata); if (logicalFilters != null) { foreach (LogicalFilter logicalFilter in logicalFilters) { exp = logicalFilter.GetExpression(exp, paramExp, metadata); } } var predicate = Expression.Lambda <Func <T, bool> >(exp, paramExp); return(predicate); }
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { SignalWrapper item = (SignalWrapper)comboBox1.SelectedItem; m_activeSignal = item.Signal.TryGetSignal("Voltage Angle"); m_frameworkCtrl.Framework.SetAngleReference(m_activeSignal); }
private SignalDataBase TryGetSignal(MetadataBase signal, IDictionary<Guid, SignalDataBase> results) { SignalDataBase data; if (results.TryGetValue(signal.UniqueId, out data)) return data; return null; }
public override Expression GetExpression(ParameterExpression paramExp, MetadataBase metadata) { Expression left = Expression.Property(paramExp, PropertyName); Expression right = GetConstantExp(metadata); switch (Operator) { case ComparisonOperator.Equal: return(Expression.Equal(left, right)); case ComparisonOperator.NotEqual: return(Expression.NotEqual(left, right)); case ComparisonOperator.GreaterThan: return(Expression.GreaterThan(left, right)); case ComparisonOperator.GreaterThanOrEqual: return(Expression.GreaterThanOrEqual(left, right)); case ComparisonOperator.LessThan: return(Expression.LessThan(left, right)); case ComparisonOperator.LessThanOrEqual: return(Expression.LessThanOrEqual(left, right)); } throw new Exception($"Operator {Operator} not supported"); }
public void ValidateItemByCode(MetadataBase currentItem, List <MetadataBase> validatingEntity) { if (currentItem.Id > 0 && (validatingEntity.Where(x => x.Id == currentItem.Id).FirstOrDefault().Code != currentItem.Code)) { throw new ServiceException(new ErrorMessage[] { new ErrorMessage() { Code = string.Empty, Message = $"Code unauthorized to change" } }); } var result = validatingEntity.Where(x => x.Code != null); if (result.Any() && ((currentItem.Id == 0 && validatingEntity.Any(x => x.Code.ToLower() == currentItem.Code.ToLower() && x.Deleted == false)) || (currentItem.Id > 0 && validatingEntity.Any(x => x.Id != currentItem.Id && (x.Code.ToLower() == currentItem.Code.ToLower() && x.Deleted == false))))) { throw new ServiceException(new ErrorMessage[] { new ErrorMessage() { Code = string.Empty, Message = $"Exsiting code found " } }); } }
public static string ToXmlString(this MetadataBase metadata, X509Certificate2 signingCertificate) { var serializer = ExtendedMetadataSerializer.WriterInstance; var xmlDoc = new XmlDocument(); using (var xmlWriter = xmlDoc.CreateNavigator().AppendChild()) { serializer.WriteMetadata(xmlWriter, metadata); } var entityDescriptorId = (metadata as ExtendedEntityDescriptor)?.EntityDescriptorId; if (!string.IsNullOrEmpty(entityDescriptorId)) { xmlDoc.DocumentElement.SetAttribute("ID", entityDescriptorId); } if (signingCertificate != null) { xmlDoc.Sign(signingCertificate, true); } return(xmlDoc.OuterXml); }
public T ExecuteFunction <T>(string function, OracleUdtInfo udtInfo, params IParam[] parameters) { MetadataBase returnMetadata = null; OracleParameter retOra = null; try { using (var connection = _DbFactory.CreateConnection()) { var builder = _BuilderFactory.CreateBuilder(connection); Execute(builder, connection, function, parameters, (info) => FunctionBeforeQuery <T>(builder, info, udtInfo, out returnMetadata, out retOra), (info) => { if (returnMetadata is MetadataOracleObject <T> metadata) { return(ReturnValueAdditionalInformation(info, udtInfo, metadata, out retOra)); } else if (returnMetadata is MetadataOracleBoolean metadataBoolean) { return(ReturnValueAdditionalInformationBoolean <T>(info, metadataBoolean, out retOra)); } else { return(null); } }); return(GetReturnParameterOtuputValue <T>(retOra, returnMetadata)); } } finally { _DbFactory.Dispose(); } }
private void AssignIfFound(long id, ref MetadataBase category, Dictionary <ulong, MetadataBase> points) { if (id >= 0 && points.ContainsKey((ulong)id)) { category = points[(ulong)id]; } }
internal virtual void SaveMetadata(string name, MetadataBase metadata) { using (var entry = Cache.CreateEntry($"metadata-{name}")) { entry.SetValue(metadata); } }
public void ValidateItemByDescription(MetadataBase currentItem, List <MetadataBase> validatingEntity) { var result = validatingEntity.Where(x => x.Description != null); if (result.Any() && (currentItem.Id == 0 && validatingEntity.Any(x => x.Description.ToLower() == currentItem.Description.ToLower() && x.Deleted == false))) { throw new ServiceException(new ErrorMessage[] { new ErrorMessage() { Code = string.Empty, Message = $"Exsiting description found " } }); } else if (result.Any() && (currentItem.Id > 0 && validatingEntity.Any(x => x.Id != currentItem.Id && (x.Description.ToLower() == currentItem.Description.ToLower() && x.Deleted == false)))) { throw new ServiceException(new ErrorMessage[] { new ErrorMessage() { Code = string.Empty, Message = $"Exsiting description found " } }); } }
internal void ShowMetadata(MetadataBase meta) { if (dockControlMeta?.Visible == true) { dockControlMeta.UpdateMeta(meta); } }
/// <summary> /// Parses the federation metadata document and gets issuer Name and Signing Certificates /// </summary> /// <param name="metadataAddress">URL of the Federation Metadata document</param> /// <param name="issuer">Issuer Name</param> /// <param name="signingTokens">Signing Certificates in the form of X509SecurityToken</param> static void GetTenantInformation(string metadataAddress, out string issuer, out List <X509SecurityToken> signingTokens) { signingTokens = new List <X509SecurityToken>(); // The issuer and signingTokens are cached for 24 hours. They are updated if any of the conditions in the if condition is true. if (DateTime.UtcNow.Subtract(_stsMetadataRetrievalTime).TotalHours > 24 || string.IsNullOrEmpty(_issuer) || _signingTokens == null) { MetadataSerializer serializer = new MetadataSerializer() { // turning off certificate validation for demo. Don't use this in production code. CertificateValidationMode = X509CertificateValidationMode.None }; MetadataBase metadata = serializer.ReadMetadata(XmlReader.Create(metadataAddress)); EntityDescriptor entityDescriptor = (EntityDescriptor)metadata; // get the issuer name if (!string.IsNullOrWhiteSpace(entityDescriptor.EntityId.Id)) { _issuer = entityDescriptor.EntityId.Id; } // get the signing certs _signingTokens = ReadSigningCertsFromMetadata(entityDescriptor); _stsMetadataRetrievalTime = DateTime.UtcNow; } issuer = _issuer; signingTokens = _signingTokens; }
public void GetAllDesiredSignals(HashSet <MetadataBase> activeSignals, HashSet <SignalGroup> currentlyActiveGroups) { MetadataBase signalReference = null; m_frequencySignals.Clear(); m_voltageAngleSignals.Clear(); foreach (SignalGroup group in currentlyActiveGroups) { SinglePhasorTerminal calc = group as SinglePhasorTerminal; if (calc != null) { if (signalReference is null) { signalReference = calc.VoltageAngle; m_framework.SetAngleReference(signalReference); } m_frequencySignals.Add(calc.VoltageAngleReference.SignalId); activeSignals.Add(calc.VoltageAngleReference); //m_frequencySignals.Add(calc.Frequency.SignalId); //activeSignals.Add(calc.Frequency); m_voltageAngleSignals.Add(calc.VoltageMagnitudePu.SignalId); activeSignals.Add(calc.VoltageMagnitudePu); //m_voltageAngleSignals.Add(calc.VoltageAngle.SignalId); //activeSignals.Add(calc.VoltageAngle); } } }
private SignalDataBase TryGetSignal(MetadataBase signal, IDictionary <Guid, SignalDataBase> results) { if (results.TryGetValue(signal.UniqueId, out SignalDataBase data)) { return(data); } return(null); }
public SinglePhasorPowerSignals(MetadataBase voltageMagnitudePointId, MetadataBase voltageAnglePointId, MetadataBase currentMagnitudePointId, MetadataBase currentAnglePointId) : base(voltageMagnitudePointId, voltageAnglePointId, currentMagnitudePointId, currentAnglePointId) { Watt = new MetadataDouble(Guid.NewGuid(), null, "", "", this); PowerFactor = new MetadataDouble(Guid.NewGuid(), null, "", "", this); VoltAmpre = new MetadataDouble(Guid.NewGuid(), null, "", "", this); VoltAmpreReactive = new MetadataDouble(Guid.NewGuid(), null, "", "", this); }
private static void CopyChanges(this ConnectionDetail connectionDetail, MetadataBase existingItem, MetadataBase newItem, List <Guid> deletedIds) { foreach (var prop in existingItem.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (!Attribute.IsDefined(prop, typeof(DataMemberAttribute))) { continue; } var newValue = prop.GetValue(newItem); var existingValue = prop.GetValue(existingItem) as MetadataBase; var type = prop.PropertyType; if (type.IsArray) { type = type.GetElementType(); } if (!typeof(MetadataBase).IsAssignableFrom(type) && !typeof(Label).IsAssignableFrom(type)) { if (newItem.HasChanged != false) { prop.SetValue(existingItem, newValue); } } else if (typeof(Label).IsAssignableFrom(type)) { if (newItem.HasChanged != false) { connectionDetail.CopyChanges((Label)prop.GetValue(existingItem), (Label)newValue, deletedIds); } } else if (newValue != null) { if (prop.PropertyType.IsArray) { connectionDetail.CopyChanges(existingItem, prop, (MetadataBase[])newValue, deletedIds); } else { if (existingValue.MetadataId == ((MetadataBase)newValue).MetadataId) { connectionDetail.CopyChanges(existingValue, (MetadataBase)newValue, deletedIds); } else { prop.SetValue(existingItem, newValue); } } } else if (existingValue != null && deletedIds.Contains(existingValue.MetadataId.Value)) { prop.SetValue(existingItem, null); } } }
public MetadataReferenceSetOwnershipRegistration(MetadataBase owner, MetadataReferenceSetBase set) { owner.EnsureNotNull(nameof(owner)); set.EnsureNotNull(nameof(set)); // _helpFlags = 0; _owner = owner; _set = set; set.SetOwnershipRegistration(registration: this); }
private TComponent FillComponentBase <TComponent>(TComponent component, MetadataBase attribute) where TComponent : ComponentBase { component.Caption = attribute.Translations?.FirstOrDefault().Name; component.Binding = new ComponentBinding { PropertyPath = new List <string> { attribute.Name } }; return(component); }
/// <summary> /// Retrieves a populated <see cref="WsFederationConfiguration"/> given an address and an <see cref="IDocumentRetriever"/>. /// </summary> /// <param name="address">address of the metadata document.</param> /// <param name="retriever">the <see cref="IDocumentRetriever"/> to use to read the metadata document</param> /// <param name="cancel"><see cref="CancellationToken"/>.</param> /// <returns>A populated <see cref="WsFederationConfiguration"/> instance.</returns> public static async Task <WsFederationConfiguration> GetAsync(string address, IDocumentRetriever retriever, CancellationToken cancel) { if (string.IsNullOrWhiteSpace(address)) { LogHelper.Throw(string.Format(CultureInfo.InvariantCulture, LogMessages.IDX10000, GetType() + ": address"), typeof(ArgumentNullException), EventLevel.Verbose); } if (retriever == null) { LogHelper.Throw(string.Format(CultureInfo.InvariantCulture, LogMessages.IDX10000, GetType() + ": retriever"), typeof(ArgumentNullException), EventLevel.Verbose); } WsFederationConfiguration configuration = new WsFederationConfiguration(); string document = await retriever.GetDocumentAsync(address, cancel); using (XmlReader metaDataReader = XmlReader.Create(new StringReader(document), SafeSettings)) { var serializer = new MetadataSerializer { CertificateValidationMode = X509CertificateValidationMode.None }; MetadataBase metadataBase = serializer.ReadMetadata(metaDataReader); var entityDescriptor = (EntityDescriptor)metadataBase; if (!string.IsNullOrWhiteSpace(entityDescriptor.EntityId.Id)) { configuration.Issuer = entityDescriptor.EntityId.Id; } SecurityTokenServiceDescriptor stsd = entityDescriptor.RoleDescriptors.OfType <SecurityTokenServiceDescriptor>().First(); if (stsd != null) { configuration.TokenEndpoint = stsd.PassiveRequestorEndpoints.First().Uri.AbsoluteUri; foreach (KeyDescriptor keyDescriptor in stsd.Keys) { if (keyDescriptor.KeyInfo != null && (keyDescriptor.Use == KeyType.Signing || keyDescriptor.Use == KeyType.Unspecified)) { IdentityModelEventSource.Logger.WriteVerbose(LogMessages.IDX10807); foreach (SecurityKeyIdentifierClause clause in keyDescriptor.KeyInfo) { X509RawDataKeyIdentifierClause x509Clause = clause as X509RawDataKeyIdentifierClause; if (x509Clause != null) { var key = new X509SecurityKey(new X509Certificate2(x509Clause.GetX509RawData())); configuration.SigningKeys.Add(key); } } } } } } return(configuration); }
protected override void Dispose(bool explicitDispose) { if (explicitDispose && IsRegistrationCompleted) { _set?.Dispose(); } _set = null; _owner = null; // base.Dispose(explicitDispose); }
internal void GetMetadata_ExistsInCache(MetadataBase metadata, string name, Mock <IMemoryCache> memoryCache) { object validParameter = metadata; memoryCache.Setup(m => m.TryGetValue($"metadata-{name}", out validParameter)).Returns(true); var cache = new ServForOracleCache(memoryCache.Object); var actual = cache.GetMetadata(name); Assert.Equal(metadata, actual); }
/// <summary> /// Invoke after metadata is retrieved and parsed /// </summary> /// <param name="metadata"></param> /// <param name="dependencyResolver"></param> public static void OnReceived(MetadataBase metadata, IDependencyResolver dependencyResolver) { if (metadata == null) { throw new ArgumentNullException("metadata"); } if (dependencyResolver == null) { throw new ArgumentNullException("dependencyResolver"); } string entityId = "RegisteredIssuer"; var handlerType = typeof(IMetadataHandler <>).MakeGenericType(metadata.GetType()); var handler = dependencyResolver.Resolve(handlerType) as IMetadataHandler; if (handler == null) { throw new InvalidOperationException(String.Format("Handler must implement: {0}", typeof(IMetadataHandler).Name)); } var idps = handler.GetIdentityProviderSingleSignOnDescriptor(metadata); var certManager = dependencyResolver.Resolve <ICertificateManager>(); //Default WIF implementation change if another policy is in place. Used to validate the issuer when building the claims var identityRegister = IdentityConfigurationHelper._identityConfiguration.IssuerNameRegistry as ConfigurationBasedIssuerNameRegistry;//SecurityTokenHandlerConfiguration.DefaultIssuerNameRegistry as ConfigurationBasedIssuerNameRegistry; if (identityRegister == null) { return; } var register = idps.SelectMany(x => x.Roles, (d, r) => new { d.EntityId, r }).SelectMany(x => x.r.Keys.SelectMany(y => y.KeyInfo.Select(cl => { var binaryClause = cl as BinaryKeyIdentifierClause; if (binaryClause == null) { throw new InvalidOperationException(String.Format("Expected type: {0} but it was: {1}", typeof(BinaryKeyIdentifierClause), cl.GetType())); } var certContent = binaryClause.GetBuffer(); var cert = new X509Certificate2(certContent); return(cert); })), (d, c) => new { d.EntityId, c }).Aggregate(identityRegister, (t, next) => { if (!identityRegister.ConfiguredTrustedIssuers.Keys.Contains(next.c.Thumbprint)) { identityRegister.AddTrustedIssuer(certManager.GetCertificateThumbprint(next.c), next.EntityId); } return(t); }); }
internal void GetMetadata_DoesNoExistsInCache_ReturnsDefault(string name, Mock <IMemoryCache> memoryCache) { object validParameter = null; MetadataBase metadata = default; memoryCache.Setup(m => m.TryGetValue($"metadata-{name}", out validParameter)).Returns(false); var cache = new ServForOracleCache(memoryCache.Object); var actual = cache.GetMetadata(name); Assert.Equal(metadata, actual); }
public void Initialize(SubscriptionFramework framework) { //m_frameworkCtrl = framework; comboBox1.Items.Clear(); foreach (SignalGroup signal in framework.AllSignalGroups) { MetadataBase s = signal.TryGetSignal("Voltage Angle"); if (s != null) { comboBox1.Items.Add(new SignalWrapper(signal)); } } comboBox1.Sorted = true; }
private SecurityTokenServiceDescriptor ReadStsDescriptor(MetadataBase metadataBase) { EntitiesDescriptor entities = metadataBase as EntitiesDescriptor; if (entities != null) { foreach (EntityDescriptor en in entities.ChildEntities) { foreach (RoleDescriptor role in en.RoleDescriptors) { SecurityTokenServiceDescriptor stsDescriptor = role as SecurityTokenServiceDescriptor; if (stsDescriptor != null) { // // If there are multiple STS descriptors, the first one listed will be used. // This mirrors the behavior of the Federation Utility tool that creates automatic trust // using the STS Federation metadata. This is provided for illustrative purposes only. // In a production system, you may choose to trust one or more STS descriptors that are // published in the STS Federation metadata. // return(stsDescriptor); } } } } EntityDescriptor entity = metadataBase as EntityDescriptor; if (entity != null) { foreach (RoleDescriptor role in entity.RoleDescriptors) { SecurityTokenServiceDescriptor stsDescriptor = role as SecurityTokenServiceDescriptor; if (stsDescriptor != null) { // // If there are multiple STS descriptors, the first one listed will be used. // This mirrors the behavior of the Federation Utility tool that creates automatic trust // using the STS Federation metadata. This is provided for illustrative purposes only. // In a production system, you may choose to trust one or more STS descriptors that are // published in the STS Federation metadata. // return(stsDescriptor); } } } throw new InvalidOperationException("The metadata does not contain a valid SecurityTokenServiceDescriptor."); }
public MetadataBase GetMetadata(GetMetadataParams param, bool force = false) { if (_metadataCache != null && !force) { return(_metadataCache); } JArray prm = new JArray { }; if (param != null) { prm = new JArray { param.BlockHash } } ; JObject query = new JObject { { "method", "state_getMetadata" }, { "params", prm } }; JObject response = _jsonRpc.Request(query); if (TryDeserialize <MetadataV11, ParseMetadataV11>(response, out MetadataV11 md11)) { _metadataCache = md11; return(md11); } if (TryDeserialize <MetadataV8, ParseMetadataV8>(response, out MetadataV8 md8)) { _metadataCache = md8; return(md8); } if (TryDeserialize <MetadataV7, ParseMetadataV7>(response, out MetadataV7 md7)) { _metadataCache = md7; return(md7); } if (TryDeserialize <MetadataV4, ParseMetadataV4>(response, out MetadataV4 md4)) { _metadataCache = md4; return(md4); } return(null); }
public void SetUp() { Mock<MetadataBase> mockMetadataBase1 = new Mock<MetadataBase>((uint)1,(uint)2); mockMetadataBase1.CallBase = true; Mock<MetadataBase> mockMetadataBase2 = new Mock<MetadataBase>((uint)1, (uint)2); mockMetadataBase2.CallBase = true; Mock<MetadataBase> mockMetadataBase3 = new Mock<MetadataBase>((uint)4, (uint)2); mockMetadataBase2.CallBase = true; _metadataBase1 = mockMetadataBase1.Object; _metadataBase2 = mockMetadataBase2.Object; _metadataBase3 = mockMetadataBase3.Object; }
public async Task ManagerTest() { //ARRANGE MetadataBase configuration = null; var federationPartyId = "imperial.ac.uk"; var federationPartyContextBuilder = new FederationPartyContextBuilderMock(); var configurationRetriever = new ConfigurationRetrieverMock(); var configurationManager = new ConfigurationManager <MetadataBase>(federationPartyContextBuilder, configurationRetriever); //ACT configuration = await configurationManager.GetConfigurationAsync(federationPartyId); //ASSET Assert.IsNotNull(configuration); }
public static string ToXmlString(this MetadataBase metadata, int cacheDuration) { var serializer = new CacheAwareMetadataSerializer(cacheDuration); using (var stream = new MemoryStream()) { serializer.WriteMetadata(stream, metadata); using (var reader = new StreamReader(stream)) { stream.Seek(0, SeekOrigin.Begin); return(reader.ReadToEnd()); } } }
public static string ToXmlString(this MetadataBase metadata) { var serializer = ExtendedMetadataSerializer.WriterInstance; using (var stream = new MemoryStream()) { serializer.WriteMetadata(stream, metadata); using (var reader = new StreamReader(stream)) { stream.Seek(0, SeekOrigin.Begin); return(reader.ReadToEnd()); } } }
public void ActivateSignal(MetadataBase signal) { m_activeSignals.Add(signal); RefreshActivePoints(); }
public void GetPoints(out MetadataBase newSignal) { newSignal = m_newSignal; }
public SignalAngleDifference(MetadataBase signal, MetadataBase signalReference) : base(signal, signalReference) { m_newSignal = new MetadataDouble(Guid.NewGuid(), null, "", "", this); }
public SignalAssignment() : base(new MetadataDouble(Guid.NewGuid(), null, "", "")) { m_newSignal = new MetadataDouble(Guid.NewGuid(), null, "", "", this); }
public void SetNewBaseSignal(MetadataBase signalId) { Dependencies[0] = signalId; }
public SignalScaling(double scalingFactor, MetadataBase signalId) : base(signalId) { m_scalingFactor = scalingFactor; m_newSignal = new MetadataDouble(Guid.NewGuid(), null, "", "", this); }
public void DeactivateSignal(MetadataBase signal) { m_activeSignals.Remove(signal); RefreshActivePoints(); }
public void SetAngleReference(MetadataBase signal) { m_angleReference.SetNewBaseSignal(signal); RefreshActivePoints(); }