Beispiel #1
0
        /// <summary>
        /// Create a Consumer instance identified by the parameters passed.
        /// </summary>
        /// <param name="applicationKey">Application key.</param>
        /// <param name="instanceId">Instance ID.</param>
        /// <param name="userToken">User token.</param>
        /// <param name="solutionId">Solution ID.</param>
        public Consumer(string applicationKey, string instanceId = null, string userToken = null, string solutionId = null)
        {
            Environment environment = new Environment(applicationKey, instanceId, userToken, solutionId);

            environmentTemplate = EnvironmentUtils.MergeWithSettings(environment, SettingsManager.ConsumerSettings);
            registrationService = new RegistrationService(SettingsManager.ConsumerSettings, SessionsManager.ConsumerSessionService);
        }
        public void SaveAndRetrieveByExample()
        {
            // Save a new Environment.
            Environment saved = DataFactory.CreateEnvironmentRequest();

            environmentRepository.Save(saved);

            // Create an example Environment instance for use in the retrieve call.
            ApplicationInfo applicationInfo = new ApplicationInfo {
                ApplicationKey = "UnitTesting"
            };
            Environment example = new Environment
            {
                ApplicationInfo = applicationInfo,
                InstanceId      = saved.InstanceId,
                SessionToken    = saved.SessionToken,
                SolutionId      = saved.SolutionId,
                UserToken       = saved.UserToken
            };

            // Retrieve Environments based on the example Environment instance.
            IEnumerable <Environment> environments = environmentRepository.Retrieve(example);

            // Assert that the retrieved Environments match properties of the example Environment instance.
            foreach (Environment retrieved in environments)
            {
                Assert.AreEqual(saved.ApplicationInfo.ApplicationKey, retrieved.ApplicationInfo.ApplicationKey);
                Assert.AreEqual(saved.InstanceId, retrieved.InstanceId);
                Assert.AreEqual(saved.SessionToken, retrieved.SessionToken);
                Assert.AreEqual(saved.Id, retrieved.Id);
                Assert.AreEqual(saved.SolutionId, retrieved.SolutionId);
                Assert.AreEqual(saved.UserToken, retrieved.UserToken);
            }
        }
        public void SaveAndRetrieveBySessionToken()
        {
            Environment     saved           = DataFactory.CreateEnvironmentRequest();
            Guid            environmentId   = (new EnvironmentRepository()).Save(saved);
            ApplicationInfo applicationInfo = new ApplicationInfo
            {
                ApplicationKey = "UnitTesting",
            };
            Environment example = new Environment
            {
                ApplicationInfo = applicationInfo,
                InstanceId      = "ThisInstance01",
                SessionToken    = "2e5dd3ca282fc8ddb3d08dcacc407e8a",
                SolutionId      = "auTestSolution",
                UserToken       = "UserToken01"
            };
            Environment retrieved = (new EnvironmentRepository()).RetrieveBySessionToken("2e5dd3ca282fc8ddb3d08dcacc407e8a");

            Assert.AreEqual(saved.ApplicationInfo.ApplicationKey, retrieved.ApplicationInfo.ApplicationKey);
            Assert.AreEqual(saved.InstanceId, retrieved.InstanceId);
            Assert.AreEqual(saved.SessionToken, retrieved.SessionToken);
            Assert.AreEqual(saved.Id, retrieved.Id);
            Assert.AreEqual(saved.SolutionId, retrieved.SolutionId);
            Assert.AreEqual(saved.UserToken, retrieved.UserToken);
        }
        /// <summary>
        /// Create a Consumer instance based upon the Environment passed.
        /// </summary>
        /// <param name="environment">Environment object.</param>
        /// <param name="settings">Consumer settings. If null, Consumer settings will be read from the SifFramework.config file.</param>
        public FunctionalServiceConsumer(Environment environment, IFrameworkSettings settings = null)
        {
            ConsumerSettings = settings ?? SettingsManager.ConsumerSettings;

            environmentTemplate = EnvironmentUtils.MergeWithSettings(environment, ConsumerSettings);
            registrationService = new RegistrationService(ConsumerSettings, SessionsManager.ConsumerSessionService);
        }
Beispiel #5
0
 /// <summary>
 /// Create a Consumer instance based upon the Environment passed.
 /// </summary>
 /// <param name="environment">Environment object.</param>
 /// <param name="settings">Consumer settings. If null, Consumer settings will be read from the SifFramework.config file.</param>
 /// <param name="sessionService">Consumer session service. If null, the Consumer session will be stored in the SifFramework.config file.</param>
 protected Consumer(
     Environment environment,
     IFrameworkSettings settings    = null,
     ISessionService sessionService = null)
 {
     ConsumerSettings    = settings ?? SettingsManager.ConsumerSettings;
     environmentTemplate = EnvironmentUtils.MergeWithSettings(environment, ConsumerSettings);
     RegistrationService =
         new RegistrationService(ConsumerSettings, sessionService ?? SessionsManager.ConsumerSessionService);
 }
        /// <summary>
        /// Create an Environment instance from properties defined in the framework settings.
        /// </summary>
        /// <param name="settings">Framework settings.</param>
        /// <returns>Environment instance.</returns>
        internal static Environment LoadFromSettings(IFrameworkSettings settings)
        {
            Environment merged = new Environment();

            if (merged.ApplicationInfo == null)
            {
                merged.ApplicationInfo = new ApplicationInfo();
            }

            if (string.IsNullOrWhiteSpace(settings.ApplicationKey))
            {
                throw new ConfigurationErrorsException("An applicationKey must be defined in the Provider Environment template.");
            }
            else
            {
                merged.ApplicationInfo.ApplicationKey = settings.ApplicationKey;
            }

            if (!string.IsNullOrWhiteSpace(settings.SolutionId))
            {
                merged.SolutionId = settings.SolutionId;
            }

            if (!string.IsNullOrWhiteSpace(settings.UserToken))
            {
                merged.UserToken = settings.UserToken;
            }

            if (!string.IsNullOrWhiteSpace(settings.InstanceId))
            {
                merged.InstanceId = settings.InstanceId;
            }

            if (!string.IsNullOrWhiteSpace(settings.AuthenticationMethod))
            {
                merged.AuthenticationMethod = settings.AuthenticationMethod;
            }

            if (!string.IsNullOrWhiteSpace(settings.ConsumerName))
            {
                merged.ConsumerName = settings.ConsumerName;
            }

            if (!string.IsNullOrWhiteSpace(settings.DataModelNamespace))
            {
                merged.ApplicationInfo.DataModelNamespace = settings.DataModelNamespace;
            }

            if (!string.IsNullOrWhiteSpace(settings.SupportedInfrastructureVersion))
            {
                merged.ApplicationInfo.SupportedInfrastructureVersion = settings.SupportedInfrastructureVersion;
            }

            return(merged);
        }
        public void SaveAndRetrieve()
        {
            Environment saved         = DataFactory.CreateEnvironmentRequest();
            Guid        environmentId = (new EnvironmentRepository()).Save(saved);
            Environment retrieved     = (new EnvironmentRepository()).Retrieve(environmentId);

            Assert.AreEqual(saved.Type, retrieved.Type);
            Assert.AreEqual(saved.AuthenticationMethod, retrieved.AuthenticationMethod);
            Assert.AreEqual(saved.ConsumerName, retrieved.ConsumerName);
            Assert.AreEqual(saved.ApplicationInfo.ApplicationKey, retrieved.ApplicationInfo.ApplicationKey);
            Assert.AreEqual(saved.ApplicationInfo.SupportedInfrastructureVersion, retrieved.ApplicationInfo.SupportedInfrastructureVersion);
            Assert.AreEqual(saved.ApplicationInfo.DataModelNamespace, retrieved.ApplicationInfo.DataModelNamespace);
        }
        /// <summary>
        /// Parse the Environment object for the service URL.
        /// </summary>
        /// <param name="environment">Environment object to parse.</param>
        /// <returns>Service URL.</returns>
        internal static string ParseServiceUrl(Environment environment)
        {
            string serviceUrl = null;

            if (environment != null &&
                environment.InfrastructureServices != null &&
                environment.InfrastructureServices[InfrastructureServiceNames.requestsConnector] != null &&
                environment.InfrastructureServices[InfrastructureServiceNames.requestsConnector].Value != null)
            {
                serviceUrl = environment.InfrastructureServices[InfrastructureServiceNames.requestsConnector].Value;
            }

            return(serviceUrl);
        }
        /// <summary>
        /// Combine the passed in environment object with the equivalent properties defined in the framework settings
        /// (if present). Properties that already exist in the passed in the environment take precedence over the
        /// properties defined in the framework settings.
        /// </summary>
        /// <param name="environment">Environment object to check.</param>
        /// <param name="settings">Framework settings.</param>
        /// <returns>Environment object with merged properties.</returns>
        internal static Environment MergeWithSettings(Environment environment, IFrameworkSettings settings)
        {
            Environment merged;

            if (environment == null)
            {
                merged = new Environment();
            }
            else
            {
                merged = environment;
            }

            if (merged.ApplicationInfo == null)
            {
                merged.ApplicationInfo = new ApplicationInfo();
            }

            if (string.IsNullOrWhiteSpace(merged.ApplicationInfo.ApplicationKey) && settings.ApplicationKey != null)
            {
                merged.ApplicationInfo.ApplicationKey = settings.ApplicationKey;
            }

            if (string.IsNullOrWhiteSpace(merged.ApplicationInfo.ApplicationKey))
            {
                throw new ArgumentException("An applicationKey must either be provided or defined in the Consumer Environment template.", "applicationKey");
            }

            if (string.IsNullOrWhiteSpace(merged.AuthenticationMethod) && settings.AuthenticationMethod != null)
            {
                merged.AuthenticationMethod = settings.AuthenticationMethod;
            }

            if (string.IsNullOrWhiteSpace(merged.ConsumerName) && settings.ConsumerName != null)
            {
                merged.ConsumerName = settings.ConsumerName;
            }

            if (string.IsNullOrWhiteSpace(merged.ApplicationInfo.DataModelNamespace) && settings.DataModelNamespace != null)
            {
                merged.ApplicationInfo.DataModelNamespace = settings.DataModelNamespace;
            }

            if (string.IsNullOrWhiteSpace(merged.ApplicationInfo.SupportedInfrastructureVersion) && settings.SupportedInfrastructureVersion != null)
            {
                merged.ApplicationInfo.SupportedInfrastructureVersion = settings.SupportedInfrastructureVersion;
            }

            return(merged);
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        private static EnvironmentRegister CreateEnvironmentRegister(Environment environmentRequest, Environment environmentResponse)
        {
            EnvironmentRegister environmentRegister = new EnvironmentRegister
            {
                ApplicationKey         = environmentRequest.ApplicationInfo.ApplicationKey,
                DefaultZone            = environmentResponse.DefaultZone,
                InfrastructureServices = environmentResponse.InfrastructureServices,
                InstanceId             = environmentRequest.InstanceId,
                ProvisionedZones       = environmentResponse.ProvisionedZones,
                SolutionId             = environmentRequest.SolutionId,
                UserToken = environmentRequest.UserToken
            };

            return(environmentRegister);
        }
        public void SaveAndRetrieve()
        {
            // Save a new Environment and then retrieve it using it's identifier.
            Environment saved         = DataFactory.CreateEnvironmentRequest();
            Guid        environmentId = environmentRepository.Save(saved);
            Environment retrieved     = environmentRepository.Retrieve(environmentId);

            // Assert that the retrieved Environment matches the saved Environment.
            Assert.AreEqual(saved.Type, retrieved.Type);
            Assert.AreEqual(saved.AuthenticationMethod, retrieved.AuthenticationMethod);
            Assert.AreEqual(saved.ConsumerName, retrieved.ConsumerName);
            Assert.AreEqual(saved.ApplicationInfo.ApplicationKey, retrieved.ApplicationInfo.ApplicationKey);
            Assert.AreEqual(saved.ApplicationInfo.SupportedInfrastructureVersion, retrieved.ApplicationInfo.SupportedInfrastructureVersion);
            Assert.AreEqual(saved.ApplicationInfo.DataModelNamespace, retrieved.ApplicationInfo.DataModelNamespace);
        }
        public void SaveAndRetrieveBySessionToken()
        {
            // Save a new Environment and then retrieve it based on it's session token.
            Environment saved = DataFactory.CreateEnvironmentRequest();

            environmentRepository.Save(saved);
            Environment retrieved = environmentRepository.RetrieveBySessionToken(saved.SessionToken);

            // Assert that the retrieved Environment matches the saved Environment.
            Assert.AreEqual(saved.ApplicationInfo.ApplicationKey, retrieved.ApplicationInfo.ApplicationKey);
            Assert.AreEqual(saved.InstanceId, retrieved.InstanceId);
            Assert.AreEqual(saved.SessionToken, retrieved.SessionToken);
            Assert.AreEqual(saved.Id, retrieved.Id);
            Assert.AreEqual(saved.SolutionId, retrieved.SolutionId);
            Assert.AreEqual(saved.UserToken, retrieved.UserToken);
        }
        private static ApplicationRegister CreateApplicationRegister(string path)
        {
            environmentType environmentTypeRequest;
            environmentType environmentTypeResponse;

            string request  = @path + "\\EnvironmentRequest.xml";
            string response = @path + "\\EnvironmentResponse.xml";

            if (!File.Exists(request) || !File.Exists(response))
            {
                return(null);
            }

            Console.WriteLine("");
            Console.WriteLine("Processsing input from: " + path);
            Console.WriteLine("Request:  " + request);
            Console.WriteLine("Response: " + response);
            Console.WriteLine("");

            using (FileStream xmlStream = File.OpenRead(request))
            {
                environmentTypeRequest = SerialiserFactory.GetXmlSerialiser <environmentType>().Deserialise(xmlStream);
            }

            using (FileStream xmlStream = File.OpenRead(response))
            {
                environmentTypeResponse = SerialiserFactory.GetXmlSerialiser <environmentType>().Deserialise(xmlStream);
            }

            Environment         environmentRequest  = MapperFactory.CreateInstance <environmentType, Environment>(environmentTypeRequest);
            Environment         environmentResponse = MapperFactory.CreateInstance <environmentType, Environment>(environmentTypeResponse);
            EnvironmentRegister environmentRegister = CreateEnvironmentRegister(environmentRequest, environmentResponse);
            ApplicationRegister applicationRegister = new ApplicationRegister
            {
                ApplicationKey       = environmentRequest.ApplicationInfo.ApplicationKey,
                SharedSecret         = "SecretDem0",
                EnvironmentRegisters = new Collection <EnvironmentRegister> {
                    { environmentRegister }
                }
            };

            return(applicationRegister);
        }
        /// <summary>
        /// Create an Environment instance from properties defined in the framework settings.
        /// </summary>
        /// <param name="settings">Framework settings.</param>
        /// <returns>Environment instance.</returns>
        internal static Environment LoadFromSettings(IFrameworkSettings settings)
        {
            Environment merged = new Environment();

            if (merged.ApplicationInfo == null)
            {
                merged.ApplicationInfo = new ApplicationInfo();
            }

            if (String.IsNullOrWhiteSpace(settings.ApplicationKey))
            {
                throw new ConfigurationErrorsException("An applicationKey must be defined in the Provider Environment template.");
            }
            else
            {
                merged.ApplicationInfo.ApplicationKey = settings.ApplicationKey;
            }

            if (!String.IsNullOrWhiteSpace(settings.AuthenticationMethod))
            {
                merged.AuthenticationMethod = settings.AuthenticationMethod;
            }

            if (!String.IsNullOrWhiteSpace(settings.ConsumerName))
            {
                merged.ConsumerName = settings.ConsumerName;
            }

            if (!String.IsNullOrWhiteSpace(settings.DataModelNamespace))
            {
                merged.ApplicationInfo.DataModelNamespace = settings.DataModelNamespace;
            }

            if (!String.IsNullOrWhiteSpace(settings.SupportedInfrastructureVersion))
            {
                merged.ApplicationInfo.SupportedInfrastructureVersion = settings.SupportedInfrastructureVersion;
            }

            return merged;
        }
Beispiel #15
0
        /// <summary>
        /// Internal method to check if a given right is supported by the ACL.
        /// </summary>
        /// <param name="serviceName">The name of the service to check</param>
        /// <param name="zone">The zone to check authorization in</param>
        /// <param name="context">The context to check authorization in</param>
        /// <param name="right">The right to check</param>
        /// <returns>The session token if authorized, otherwise a HttpResponseException is thrown</returns>
        protected virtual string CheckAuthorisation(string serviceName, string[] zone, string[] context, Right right)
        {
            string      sessionToken = CheckAuthorisation(zone, context);
            Environment environment  = authService.GetEnvironmentBySessionToken(sessionToken);

            if (environment == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Request failed as could not retrieve environment XML."));
            }
            try
            {
                RightsUtils.CheckRight(getRights(serviceName, EnvironmentUtils.GetTargetZone(environment, zone == null ? null : zone[0])), right);
                log.Debug("Functional Service " + serviceName + " has expected ACL (" + right.Type + ":" + right.Value + ")");
                return(sessionToken);
            }
            catch (RejectedException e)
            {
                string msg = "Functional Service " + serviceName + " does not have sufficient access rights to perform an " + right.Type + " operation: " + e.Message;
                log.Debug(msg);
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, msg, e));
            }
        }
        public static ProvisionedZone GetTargetZone(Environment environment, string zoneId = null)
        {
            // Return the requested zone
            if (StringUtils.NotEmpty(zoneId))
            {
                return(environment.ProvisionedZones[zoneId]);
            }

            // No zone, so try getting the default zone
            if (StringUtils.NotEmpty(environment.DefaultZone.SifId))
            {
                return(environment.ProvisionedZones[environment.DefaultZone.SifId]);
            }

            // No default zone defined
            // Fallback: If there is exactly one zone defined then return that
            if (environment.ProvisionedZones != null && environment.ProvisionedZones.Count == 1)
            {
                return(environment.ProvisionedZones.Values.FirstOrDefault());
            }

            return(null);
        }
        public void Retrieve()
        {
            // Save a new Environment and then retrieve it using it's identifier.
            Environment     saved         = DataFactory.CreateEnvironmentRequest();
            Guid            environmentId = environmentRepository.Save(saved);
            environmentType retrieved     = environmentService.Retrieve(environmentId);

            // Assert that the retrieved Environment matches the saved Environment.
            Assert.AreEqual(saved.ApplicationInfo.AdapterProduct.IconURI, retrieved.applicationInfo.adapterProduct.iconURI);
            Assert.AreEqual(saved.ApplicationInfo.AdapterProduct.ProductName, retrieved.applicationInfo.adapterProduct.productName);
            Assert.AreEqual(saved.ApplicationInfo.AdapterProduct.ProductVersion, retrieved.applicationInfo.adapterProduct.productVersion);
            Assert.AreEqual(saved.ApplicationInfo.AdapterProduct.VendorName, retrieved.applicationInfo.adapterProduct.vendorName);
            Assert.AreEqual(saved.ApplicationInfo.ApplicationKey, retrieved.applicationInfo.applicationKey);
            Assert.AreEqual(saved.ApplicationInfo.ApplicationProduct.IconURI, retrieved.applicationInfo.applicationProduct.iconURI);
            Assert.AreEqual(saved.ApplicationInfo.ApplicationProduct.ProductName, retrieved.applicationInfo.applicationProduct.productName);
            Assert.AreEqual(saved.ApplicationInfo.ApplicationProduct.ProductVersion, retrieved.applicationInfo.applicationProduct.productVersion);
            Assert.AreEqual(saved.ApplicationInfo.ApplicationProduct.VendorName, retrieved.applicationInfo.applicationProduct.vendorName);
            Assert.AreEqual(saved.ApplicationInfo.DataModelNamespace, retrieved.applicationInfo.dataModelNamespace);
            Assert.AreEqual(saved.ApplicationInfo.SupportedInfrastructureVersion, retrieved.applicationInfo.supportedInfrastructureVersion);
            Assert.AreEqual(saved.ApplicationInfo.Transport, retrieved.applicationInfo.transport);
            Assert.AreEqual(saved.AuthenticationMethod, retrieved.authenticationMethod);
            Assert.AreEqual(saved.ConsumerName, retrieved.consumerName);
            Assert.AreEqual(saved.DefaultZone.Description, retrieved.defaultZone.description);
        }
        /// <summary>
        /// Parse the Environment object for the service URL.
        /// </summary>
        /// <param name="environment">Environment object to parse.</param>
        /// <param name="serviceType">The type of service to get a connector for.</param>
        /// <param name="connector">The type of connector to get, only has an effect when the service type is UTILITY.</param>
        /// <returns>Service URL.</returns>
        internal static string ParseServiceUrl(Environment environment, ServiceType serviceType = ServiceType.OBJECT, InfrastructureServiceNames connector = InfrastructureServiceNames.requestsConnector)
        {
            if (environment == null || environment.InfrastructureServices == null)
            {
                return(null);
            }

            InfrastructureServiceNames name;

            switch (serviceType)
            {
            case ServiceType.UTILITY:
                name = connector;
                break;

            case ServiceType.FUNCTIONAL:
                name = InfrastructureServiceNames.servicesConnector;
                break;

            case ServiceType.OBJECT:
                name = InfrastructureServiceNames.requestsConnector;
                break;

            default:
                name = InfrastructureServiceNames.requestsConnector;
                break;
            }

            if (environment.InfrastructureServices[name] == null ||
                environment.InfrastructureServices[name].Value == null)
            {
                return(null);
            }

            return(environment.InfrastructureServices[name].Value);
        }
 /// <summary>
 /// Create a Consumer instance based upon the Environment passed.
 /// </summary>
 /// <param name="environment">Environment object.</param>
 public FunctionalServiceConsumer(Environment environment)
 {
     environmentTemplate = EnvironmentUtils.MergeWithSettings(environment, SettingsManager.ConsumerSettings);
     registrationService = new RegistrationService(SettingsManager.ConsumerSettings, SessionsManager.ConsumerSessionService);
 }
        /// <summary>
        /// <see cref="IRegistrationService.Register()">Register</see>
        /// </summary>
        public Environment Register()
        {
            Environment environment = EnvironmentUtils.LoadFromSettings(settings);

            return(Register(ref environment));
        }
        /// <summary>
        /// <see cref="IRegistrationService.Register(ref Environment)">Register</see>
        /// </summary>
        public Environment Register(ref Environment environment)
        {
            if (Registered)
            {
                return(CurrentEnvironment);
            }

            if (sessionService.HasSession(environment.ApplicationInfo.ApplicationKey, environment.SolutionId, environment.UserToken, environment.InstanceId))
            {
                if (log.IsDebugEnabled)
                {
                    log.Debug("Session token already exists for this object service (Consumer/Provider).");
                }

                string storedSessionToken = sessionService.RetrieveSessionToken(environment.ApplicationInfo.ApplicationKey, environment.SolutionId, environment.UserToken, environment.InstanceId);
                AuthorisationToken = authorisationTokenService.Generate(storedSessionToken, settings.SharedSecret);
                string storedEnvironmentUrl = sessionService.RetrieveEnvironmentUrl(environment.ApplicationInfo.ApplicationKey, environment.SolutionId, environment.UserToken, environment.InstanceId);
                string environmentXml       = HttpUtils.GetRequest(storedEnvironmentUrl, AuthorisationToken);

                if (log.IsDebugEnabled)
                {
                    log.Debug("Environment XML from GET request ...");
                }
                if (log.IsDebugEnabled)
                {
                    log.Debug(environmentXml);
                }

                environmentType environmentTypeToDeserialise = SerialiserFactory.GetXmlSerialiser <environmentType>().Deserialise(environmentXml);
                Environment     environmentResponse          = MapperFactory.CreateInstance <environmentType, Environment>(environmentTypeToDeserialise);

                sessionToken   = environmentResponse.SessionToken;
                environmentUrl = environmentResponse.InfrastructureServices[InfrastructureServiceNames.environment].Value;

                if (log.IsDebugEnabled)
                {
                    log.Debug("Environment URL is " + environmentUrl + ".");
                }

                if (!storedSessionToken.Equals(sessionToken) || !storedEnvironmentUrl.Equals(environmentUrl))
                {
                    AuthorisationToken = authorisationTokenService.Generate(sessionToken, settings.SharedSecret);
                    sessionService.RemoveSession(storedSessionToken);
                    sessionService.StoreSession(environmentResponse.ApplicationInfo.ApplicationKey, sessionToken, environmentUrl, environmentResponse.SolutionId, environmentResponse.UserToken, environmentResponse.InstanceId);
                }

                environment = environmentResponse;
            }
            else
            {
                if (log.IsDebugEnabled)
                {
                    log.Debug("Session token does not exist for this object service (Consumer/Provider).");
                }

                AuthorisationToken initialToken = authorisationTokenService.Generate(environment.ApplicationInfo.ApplicationKey, settings.SharedSecret);
                environmentType    environmentTypeToSerialise = MapperFactory.CreateInstance <Environment, environmentType>(environment);
                string             body           = SerialiserFactory.GetXmlSerialiser <environmentType>().Serialise(environmentTypeToSerialise);
                string             environmentXml = HttpUtils.PostRequest(settings.EnvironmentUrl, initialToken, body);

                if (log.IsDebugEnabled)
                {
                    log.Debug("Environment XML from POST request ...");
                }
                if (log.IsDebugEnabled)
                {
                    log.Debug(environmentXml);
                }

                try
                {
                    environmentType environmentTypeToDeserialise = SerialiserFactory.GetXmlSerialiser <environmentType>().Deserialise(environmentXml);
                    Environment     environmentResponse          = MapperFactory.CreateInstance <environmentType, Environment>(environmentTypeToDeserialise);

                    sessionToken   = environmentResponse.SessionToken;
                    environmentUrl = environmentResponse.InfrastructureServices[InfrastructureServiceNames.environment].Value;

                    if (log.IsDebugEnabled)
                    {
                        log.Debug("Environment URL is " + environmentUrl + ".");
                    }

                    AuthorisationToken = authorisationTokenService.Generate(sessionToken, settings.SharedSecret);
                    sessionService.StoreSession(environment.ApplicationInfo.ApplicationKey, sessionToken, environmentUrl, environmentResponse.SolutionId, environmentResponse.UserToken, environmentResponse.InstanceId);
                    environment = environmentResponse;
                }
                catch (Exception)
                {
                    if (environmentUrl != null)
                    {
                        HttpUtils.DeleteRequest(environmentUrl, AuthorisationToken);
                    }
                    else if (!string.IsNullOrWhiteSpace(TryParseEnvironmentUrl(environmentXml)))
                    {
                        HttpUtils.DeleteRequest(TryParseEnvironmentUrl(environmentXml), AuthorisationToken);
                    }

                    throw;
                }
            }

            CurrentEnvironment = environment;
            Registered         = true;
            return(CurrentEnvironment);
        }
        public void SaveAndRetrieveByExample()
        {
            Environment saved = DataFactory.CreateEnvironmentRequest();
            Guid environmentId = (new EnvironmentRepository()).Save(saved);
            ApplicationInfo applicationInfo = new ApplicationInfo
            {
                ApplicationKey = "UnitTesting",            };
            Environment example = new Environment
            {
                ApplicationInfo = applicationInfo,
                InstanceId = "ThisInstance01",
                SessionToken = "2e5dd3ca282fc8ddb3d08dcacc407e8a",
                SolutionId = "auTestSolution",
                UserToken = "UserToken01"
            };
            IEnumerable<Environment> environments = (new EnvironmentRepository()).Retrieve(example);

            foreach (Environment retrieved in environments)
            {
                Assert.AreEqual(saved.ApplicationInfo.ApplicationKey, retrieved.ApplicationInfo.ApplicationKey);
                Assert.AreEqual(saved.InstanceId, retrieved.InstanceId);
                Assert.AreEqual(saved.SessionToken, retrieved.SessionToken);
                Assert.AreEqual(saved.Id, retrieved.Id);
                Assert.AreEqual(saved.SolutionId, retrieved.SolutionId);
                Assert.AreEqual(saved.UserToken, retrieved.UserToken);
            }
        }
        /// <summary>
        /// <see cref="IRegistrationService.Register()">Register</see>
        /// </summary>
        public Environment Register()
        {
            Environment environment = EnvironmentUtils.LoadFromSettings(SettingsManager.ProviderSettings);

            return(Register(ref environment));
        }
Beispiel #24
0
        /// <summary>
        /// <see cref="Sif.Framework.Service.Registration.IRegistrationService.Register()">Register</see>
        /// </summary>
        public void Register()
        {
            Environment environment = EnvironmentUtils.LoadFromSettings(SettingsManager.ProviderSettings);

            Register(ref environment);
        }
        /// <summary>
        /// Parse the Environment object for the service URL.
        /// </summary>
        /// <param name="environment">Environment object to parse.</param>
        /// <returns>Service URL.</returns>
        internal static string ParseServiceUrl(Environment environment)
        {
            string serviceUrl = null;

            if (environment != null &&
                environment.InfrastructureServices != null &&
                environment.InfrastructureServices[InfrastructureServiceNames.requestsConnector] != null &&
                environment.InfrastructureServices[InfrastructureServiceNames.requestsConnector].Value != null)
            {
                serviceUrl = environment.InfrastructureServices[InfrastructureServiceNames.requestsConnector].Value;
            }

            return serviceUrl;
        }
        /// <summary>
        /// <see cref="Sif.Framework.Service.Registration.IRegistrationService.Register(Sif.Framework.Model.Infrastructure.Environment)">Register</see>
        /// </summary>
        public Environment Register(ref Environment environment)
        {
            if (Registered)
            {
                return CurrentEnvironment;
            }

            if (sessionService.HasSession(environment.ApplicationInfo.ApplicationKey, environment.SolutionId, environment.UserToken, environment.InstanceId))
            {
                if (log.IsDebugEnabled) log.Debug("Session token already exists for this object service (Consumer/Provider).");

                string storedSessionToken = sessionService.RetrieveSessionToken(environment.ApplicationInfo.ApplicationKey, environment.SolutionId, environment.UserToken, environment.InstanceId);
                AuthorisationToken = AuthenticationUtils.GenerateBasicAuthorisationToken(storedSessionToken, settings.SharedSecret);
                string storedEnvironmentUrl = sessionService.RetrieveEnvironmentUrl(environment.ApplicationInfo.ApplicationKey, environment.SolutionId, environment.UserToken, environment.InstanceId);
                string environmentXml = HttpUtils.GetRequest(storedEnvironmentUrl, AuthorisationToken);

                if (log.IsDebugEnabled) log.Debug("Environment XML from GET request ...");
                if (log.IsDebugEnabled) log.Debug(environmentXml);

                environmentType environmentTypeToDeserialise = SerialiserFactory.GetXmlSerialiser<environmentType>().Deserialise(environmentXml);
                Environment environmentResponse = MapperFactory.CreateInstance<environmentType, Environment>(environmentTypeToDeserialise);

                sessionToken = environmentResponse.SessionToken;
                environmentUrl = environmentResponse.InfrastructureServices[InfrastructureServiceNames.environment].Value;

                if (log.IsDebugEnabled) log.Debug("Environment URL is " + environmentUrl + ".");

                if (!storedSessionToken.Equals(sessionToken) || !storedEnvironmentUrl.Equals(environmentUrl))
                {
                    AuthorisationToken = AuthenticationUtils.GenerateBasicAuthorisationToken(sessionToken, settings.SharedSecret);
                    sessionService.RemoveSession(storedSessionToken);
                    sessionService.StoreSession(environmentResponse.ApplicationInfo.ApplicationKey, sessionToken, environmentUrl, environmentResponse.SolutionId, environmentResponse.UserToken, environmentResponse.InstanceId);
                }

                environment = environmentResponse;
            }
            else
            {
                if (log.IsDebugEnabled) log.Debug("Session token does not exist for this object service (Consumer/Provider).");

                string initialToken = AuthenticationUtils.GenerateBasicAuthorisationToken(environment.ApplicationInfo.ApplicationKey, settings.SharedSecret);
                environmentType environmentTypeToSerialise = MapperFactory.CreateInstance<Environment, environmentType>(environment);
                string body = SerialiserFactory.GetXmlSerialiser<environmentType>().Serialise(environmentTypeToSerialise);
                string environmentXml = HttpUtils.PostRequest(settings.EnvironmentUrl, initialToken, body);

                if (log.IsDebugEnabled) log.Debug("Environment XML from POST request ...");
                if (log.IsDebugEnabled) log.Debug(environmentXml);

                try
                {
                    environmentType environmentTypeToDeserialise = SerialiserFactory.GetXmlSerialiser<environmentType>().Deserialise(environmentXml);
                    Environment environmentResponse = MapperFactory.CreateInstance<environmentType, Environment>(environmentTypeToDeserialise);

                    sessionToken = environmentResponse.SessionToken;
                    environmentUrl = environmentResponse.InfrastructureServices[InfrastructureServiceNames.environment].Value;

                    if (log.IsDebugEnabled) log.Debug("Environment URL is " + environmentUrl + ".");

                    AuthorisationToken = AuthenticationUtils.GenerateBasicAuthorisationToken(sessionToken, settings.SharedSecret);
                    sessionService.StoreSession(environment.ApplicationInfo.ApplicationKey, sessionToken, environmentUrl, environmentResponse.SolutionId, environmentResponse.UserToken, environmentResponse.InstanceId);
                    environment = environmentResponse;
                }
                catch (Exception)
                {

                    if (environmentUrl != null)
                    {
                        HttpUtils.DeleteRequest(environmentUrl, AuthorisationToken);
                    }
                    else if (!String.IsNullOrWhiteSpace(TryParseEnvironmentUrl(environmentXml)))
                    {
                        HttpUtils.DeleteRequest(TryParseEnvironmentUrl(environmentXml), AuthorisationToken);
                    }

                    throw;
                }

            }

            CurrentEnvironment = environment;
            Registered = true;
            return CurrentEnvironment;
        }
        /// <summary>
        /// <see cref="IRegistrationService.Register(ref Environment)">Register</see>
        /// </summary>
        public Environment Register(ref Environment environment)
        {
            if (Registered)
            {
                return(CurrentEnvironment);
            }

            if (sessionService.HasSession(
                    environment.ApplicationInfo.ApplicationKey,
                    environment.SolutionId,
                    environment.UserToken,
                    environment.InstanceId))
            {
                if (log.IsDebugEnabled)
                {
                    log.Debug("Session token already exists for this object service (Consumer/Provider).");
                }

                string storedSessionToken = sessionService.RetrieveSessionToken(
                    environment.ApplicationInfo.ApplicationKey,
                    environment.SolutionId,
                    environment.UserToken,
                    environment.InstanceId);
                authorisationToken = authorisationTokenService.Generate(storedSessionToken, settings.SharedSecret);
                string storedEnvironmentUrl = sessionService.RetrieveEnvironmentUrl(
                    environment.ApplicationInfo.ApplicationKey,
                    environment.SolutionId,
                    environment.UserToken,
                    environment.InstanceId);
                string environmentBody = HttpUtils.GetRequest(
                    storedEnvironmentUrl,
                    authorisationToken,
                    settings.CompressPayload,
                    contentTypeOverride: settings.ContentType.ToDescription(),
                    acceptOverride: settings.Accept.ToDescription());

                if (log.IsDebugEnabled)
                {
                    log.Debug($"Environment response from GET request ...\n{environmentBody}");
                }

                environmentType environmentTypeToDeserialise =
                    SerialiserFactory.GetSerialiser <environmentType>(settings.Accept).Deserialise(environmentBody);
                Environment environmentResponse =
                    MapperFactory.CreateInstance <environmentType, Environment>(environmentTypeToDeserialise);

                sessionToken   = environmentResponse.SessionToken;
                environmentUrl =
                    environmentResponse.InfrastructureServices[InfrastructureServiceNames.environment].Value;

                if (log.IsDebugEnabled)
                {
                    log.Debug($"Environment URL is {environmentUrl}.");
                }

                if (!storedSessionToken.Equals(sessionToken) || !storedEnvironmentUrl.Equals(environmentUrl))
                {
                    authorisationToken = authorisationTokenService.Generate(sessionToken, settings.SharedSecret);
                    sessionService.RemoveSession(storedSessionToken);
                    sessionService.StoreSession(
                        environmentResponse.ApplicationInfo.ApplicationKey,
                        sessionToken,
                        environmentUrl,
                        environmentResponse.SolutionId,
                        environmentResponse.UserToken,
                        environmentResponse.InstanceId);
                }

                environment = environmentResponse;
            }
            else
            {
                if (log.IsDebugEnabled)
                {
                    log.Debug("Session token does not exist for this object service (Consumer/Provider).");
                }

                string environmentBody = null;

                try
                {
                    AuthorisationToken initialToken = authorisationTokenService.Generate(
                        environment.ApplicationInfo.ApplicationKey,
                        settings.SharedSecret);
                    environmentType environmentTypeToSerialise =
                        MapperFactory.CreateInstance <Environment, environmentType>(environment);
                    string body = SerialiserFactory.GetSerialiser <environmentType>(settings.ContentType)
                                  .Serialise(environmentTypeToSerialise);
                    environmentBody = HttpUtils.PostRequest(
                        settings.EnvironmentUrl,
                        initialToken,
                        body,
                        settings.CompressPayload,
                        contentTypeOverride: settings.ContentType.ToDescription(),
                        acceptOverride: settings.Accept.ToDescription());

                    if (log.IsDebugEnabled)
                    {
                        log.Debug($"Environment response from POST request ...\n{environmentBody}");
                    }

                    environmentType environmentTypeToDeserialise =
                        SerialiserFactory.GetSerialiser <environmentType>(settings.Accept).Deserialise(environmentBody);
                    Environment environmentResponse =
                        MapperFactory.CreateInstance <environmentType, Environment>(environmentTypeToDeserialise);

                    sessionToken   = environmentResponse.SessionToken;
                    environmentUrl =
                        environmentResponse.InfrastructureServices[InfrastructureServiceNames.environment].Value;

                    if (log.IsDebugEnabled)
                    {
                        log.Debug($"Environment URL is {environmentUrl}.");
                    }

                    authorisationToken = authorisationTokenService.Generate(sessionToken, settings.SharedSecret);
                    sessionService.StoreSession(
                        environment.ApplicationInfo.ApplicationKey,
                        sessionToken,
                        environmentUrl,
                        environmentResponse.SolutionId,
                        environmentResponse.UserToken,
                        environmentResponse.InstanceId);
                    environment = environmentResponse;
                }
                catch (Exception e)
                {
                    if (environmentUrl != null)
                    {
                        HttpUtils.DeleteRequest(environmentUrl, authorisationToken, settings.CompressPayload);
                    }
                    else if (!string.IsNullOrWhiteSpace(TryParseEnvironmentUrl(environmentBody)))
                    {
                        HttpUtils.DeleteRequest(
                            TryParseEnvironmentUrl(environmentBody),
                            authorisationToken,
                            settings.CompressPayload);
                    }

                    throw new RegistrationException("Registration failed.", e);
                }
            }

            CurrentEnvironment = environment;
            Registered         = true;
            return(CurrentEnvironment);
        }
        /// <summary>
        /// Combine the passed in environment object with the equivalent properties defined in the framework settings
        /// (if present). Properties that already exist in the passed in the environment take precedence over the
        /// properties defined in the framework settings.
        /// </summary>
        /// <param name="environment">Environment object to check.</param>
        /// <param name="settings">Framework settings.</param>
        /// <returns>Environment object with merged properties.</returns>
        internal static Environment MergeWithSettings(Environment environment, IFrameworkSettings settings)
        {
            Environment merged;

            if (environment == null)
            {
                merged = new Environment();
            }
            else
            {
                merged = environment;
            }

            if (merged.ApplicationInfo == null)
            {
                merged.ApplicationInfo = new ApplicationInfo();
            }

            if (String.IsNullOrWhiteSpace(merged.ApplicationInfo.ApplicationKey) && settings.ApplicationKey != null)
            {
                merged.ApplicationInfo.ApplicationKey = settings.ApplicationKey;
            }

            if (String.IsNullOrWhiteSpace(merged.ApplicationInfo.ApplicationKey))
            {
                throw new ArgumentException("An applicationKey must either be provided or defined in the Consumer Environment template.", "applicationKey");
            }

            if (String.IsNullOrWhiteSpace(merged.AuthenticationMethod) && settings.AuthenticationMethod != null)
            {
                merged.AuthenticationMethod = settings.AuthenticationMethod;
            }

            if (String.IsNullOrWhiteSpace(merged.ConsumerName) && settings.ConsumerName != null)
            {
                merged.ConsumerName = settings.ConsumerName;
            }

            if (String.IsNullOrWhiteSpace(merged.ApplicationInfo.DataModelNamespace) && settings.DataModelNamespace != null)
            {
                merged.ApplicationInfo.DataModelNamespace = settings.DataModelNamespace;
            }

            if (String.IsNullOrWhiteSpace(merged.ApplicationInfo.SupportedInfrastructureVersion) && settings.SupportedInfrastructureVersion != null)
            {
                merged.ApplicationInfo.SupportedInfrastructureVersion = settings.SupportedInfrastructureVersion;
            }

            return merged;
        }
        public virtual IHttpActionResult BroadcastEvents(string zoneId = null, string contextId = null)
        {
            IEventService <TMultiple> eventService = service as IEventService <TMultiple>;
            bool eventsSupported = (eventService != null);

            if (!eventsSupported)
            {
                return(BadRequest("Support for SIF Events has not been implemented."));
            }

            IHttpActionResult result;

            try
            {
                IRegistrationService registrationService = RegistrationManager.ProviderRegistrationService;

                if (registrationService is NoRegistrationService)
                {
                    result = BadRequest("SIF Events are only supported in a BROKERED environment.");
                }
                else
                {
                    IEventIterator <TMultiple> eventIterator = eventService.GetEventIterator(zoneId, contextId);

                    if (eventIterator == null)
                    {
                        result = BadRequest("SIF Events implementation is not valid.");
                    }
                    else
                    {
                        // Retrieve the current Authorisation Token.
                        registrationService.Register();
                        AuthorisationToken token = registrationService.AuthorisationToken;

                        // Retrieve the EventsConnector endpoint URL.
                        Environment environmentTemplate = EnvironmentUtils.LoadFromSettings(SettingsManager.ProviderSettings);
                        string      storedSessionToken  = SessionsManager.ProviderSessionService.RetrieveSessionToken(
                            environmentTemplate.ApplicationInfo.ApplicationKey,
                            environmentTemplate.SolutionId,
                            environmentTemplate.UserToken,
                            environmentTemplate.InstanceId);
                        Environment environment = authService.GetEnvironmentBySessionToken(storedSessionToken);
                        string      url         = EnvironmentUtils.ParseServiceUrl(environment, ServiceType.UTILITY, InfrastructureServiceNames.eventsConnector) + "/" + TypeName + "s";

                        while (eventIterator.HasNext())
                        {
                            SifEvent <TMultiple> sifEvent = eventIterator.GetNext();

                            NameValueCollection headerFields = new NameValueCollection()
                            {
                                { HttpUtils.RequestHeader.eventAction.ToDescription(), sifEvent.EventAction.ToDescription() },
                                { HttpUtils.RequestHeader.messageId.ToDescription(), sifEvent.Id.ToString() },
                                { HttpUtils.RequestHeader.messageType.ToDescription(), "EVENT" },
                                { HttpUtils.RequestHeader.serviceName.ToDescription(), $"{TypeName}s" }
                            };

                            switch (sifEvent.EventAction)
                            {
                            case EventAction.UPDATE_FULL:
                                headerFields.Add(HttpUtils.RequestHeader.Replacement.ToDescription(), "FULL");
                                break;

                            case EventAction.UPDATE_PARTIAL:
                                headerFields.Add(HttpUtils.RequestHeader.Replacement.ToDescription(), "PARTIAL");
                                break;
                            }

                            string body = SerialiseEvents(sifEvent.SifObjects);
                            string xml  = HttpUtils.PostRequest(url, token, body, headerFields: headerFields);
                        }
                    }

                    result = Ok();
                }
            }
            catch (Exception e)
            {
                result = InternalServerError(e);
            }

            return(result);
        }