예제 #1
0
 public void SetMessagePublisherConfiguration(IServiceConfiguration messagePublisherConfiguration)
 {
     if (HostState == HostState.AwaitingConfiguration)
     {
         MessagePublisherConfiguration = messagePublisherConfiguration;
     }
 }
예제 #2
0
        private static string GetServiceValueString(this IServiceConfiguration configuration, string valueKey)
        {
            #region Contracts

            if (configuration == null)
            {
                throw new ArgumentException(nameof(configuration));
            }
            if (string.IsNullOrEmpty(valueKey) == true)
            {
                throw new ArgumentException(nameof(valueKey));
            }

            #endregion

            // ServiceValueString
            var serviceValueString = configuration.ServiceSection?.GetValue <string>(valueKey);
            if (string.IsNullOrEmpty(serviceValueString) == true)
            {
                return(null);
            }

            // Return
            return(serviceValueString);
        }
 public ServiceConfigurationServiceConfigurationKey(
     IServiceConfiguration serviceConfiguration,
     ServiceConfigurationKey serviceConfigurationKey)
 {
     ServiceConfiguration    = serviceConfiguration;
     ServiceConfigurationKey = serviceConfigurationKey;
 }
예제 #4
0
        public IServiceContext AsServiceApplication(IServiceConfiguration serviceConfiguration, ICodingStyle codingStyle)
        {
            var coreContext = new DefaultCoreContext(codingStyle, cache);
            var service     = InterceptIfConfigured(new ObjectService(coreContext, cache));

            return(new DefaultServiceContext(coreContext, serviceConfiguration, service));
        }
예제 #5
0
 public static Object GetInstance(
     this IServiceConfiguration configuration,
     ServiceProvider provider,
     Type[] generics,
     Action <Object, ServiceProvider, IServiceConfiguration> setup,
     Int32 setupOrder)
 => provider.GetServiceManager(configuration, generics).GetInstance(setup, setupOrder);
예제 #6
0
        /// <summary>
        /// Creates an OrganizationServiceProxy using the specified settings.  This should always be wrapped in a using statement so the dispose method is called.
        /// </summary>
        /// <param name="crmOrganizationUrl">The CRM organization URL.</param>
        /// <param name="crmSdkServerUrl">The CRM Sdk server URL.</param>
        /// <param name="crmOrganization">The CRM organization.</param>
        /// <param name="impersonationUserId">The impersonation user id.</param>
        /// <param name="enableProxyTypes">if set to <c>true</c> [enable proxy types].</param>
        /// <param name="ifdUserName">IFD's User Name </param>
        /// <param name="ifdPassword">IFD User's Password</param>
        /// <param name="isIfdDeployment">Indicates whether this is an IFD Deployment.</param>
        /// <returns></returns>
        public static OrganizationServiceProxy CreateOrgProxy(string crmOrganizationUrl, string crmSdkServerUrl, string crmOrganization, Guid impersonationUserId = new Guid(), bool enableProxyTypes = true, bool isIfdDeployment = false, string ifdUserName = "", string ifdPassword = "")
        {
            crmOrganization = GetCrmOrganizationName(crmSdkServerUrl, crmOrganization);
            Uri orgUri = GetOrganizationServiceUri(crmOrganizationUrl, crmOrganization, isIfdDeployment);
            IServiceConfiguration <IOrganizationService> orgConfigInfo = ServiceConfigurationFactory.CreateConfiguration <IOrganizationService>(orgUri);

            var creds = new ClientCredentials();

            if (isIfdDeployment)
            {
                creds.UserName.UserName = ifdUserName;
                creds.UserName.Password = ifdPassword;
            }

            OrganizationServiceProxy orgService = new OrganizationServiceProxy(orgConfigInfo, creds);

            if (enableProxyTypes)
            {
                ;
                orgService.EnableProxyTypes(GetEarlyBoundProxyAssembly());
            }

            if (impersonationUserId != Guid.Empty)
            {
                orgService.CallerId = impersonationUserId;
            }

            return(orgService);
        }
 public HttpDiagnosticsService(IServiceConfiguration configuration)
 {
     this.configuration = configuration;
     collector = new TimeSeriesCollector();
     carbonWriter = CarbonWriterFactory.Instance();
     graphDataHandler = new GraphDataHandler(collector);
 }
예제 #8
0
 public void SetComponentConfiguration(IServiceConfiguration componentConfiguration)
 {
     if (HostState == HostState.AwaitingConfiguration)
     {
         ComponentConfiguration = componentConfiguration;
     }
 }
예제 #9
0
        public static void BuildInstance(
            this IServiceConfiguration configuration,
            ServiceProvider provider,
            Type[] generics,
            Action <Object, ServiceProvider, IServiceConfiguration> setup,
            Int32 setupOrder,
            out Object instance)
        {
            instance = configuration.TypeFactory.BuildInstance(provider.Root, generics);
            Boolean ranSetup = false;

            foreach (SetupAction action in configuration.SetupActions)
            {
                if (!ranSetup && action.Order >= setupOrder)
                {
                    setup(instance, provider, configuration);
                    ranSetup = true;
                }

                action.Invoke(instance, provider, configuration);
            }

            if (!ranSetup)
            {
                setup(instance, provider, configuration);
            }
        }
예제 #10
0
        public IOrganizationService GetOrganisationService(OrganizationDetail org, string domain, string userName, string password)
        {
            if (org != null)
            {
                Uri orgServiceUri = null;
                orgServiceUri = new Uri(org.Endpoints[EndpointType.OrganizationService]);
                //if (!string.IsNullOrEmpty(OrganisationServiceHostName))
                //{
                //    UriBuilder builder = new UriBuilder(orgServiceUri);
                //    builder.Host = OrganisationServiceHostName;
                //    orgServiceUri = builder.Uri;
                //}

                IServiceConfiguration <IOrganizationService> orgConfigInfo = ServiceConfigurationFactory.CreateConfiguration <IOrganizationService>(orgServiceUri);

                var creds      = _credentialsProvider.GetCredentials(orgConfigInfo.AuthenticationType, domain, userName, password);
                var orgService = new OrganizationServiceProxy(orgConfigInfo, creds);
                orgService.Timeout = new TimeSpan(0, 5, 0);

                var req      = new WhoAmIRequest();
                var response = (WhoAmIResponse)orgService.Execute(req);

                Debug.WriteLine(string.Format(" Connected to {0} as Crm user id: {1}", orgConfigInfo.CurrentServiceEndpoint.Address.Uri.ToString(), response.UserId));
                return(orgService);
            }
            return(null);
        }
예제 #11
0
        /// <summary>
        /// Get value based on key
        /// </summary>
        /// <typeparam name="T">type</typeparam>
        /// <param name="self">Service configuration</param>
        /// <param name="key">key</param>
        /// <param name="throwNotFound">true, throw if key is not found</param>
        /// <returns>value, null if not found</returns>
        public static T Get <T>(this IServiceConfiguration self, string key, bool throwNotFound = false) where T : class
        {
            Verify.IsNotNull(nameof(self), self);
            Verify.IsNotEmpty(nameof(key), key);

            return(self.Properties.Get <T>(key, throwNotFound: throwNotFound));
        }
예제 #12
0
 public bool IsInitQueue(string serviceName)
 {
     try
     {
         IBusQueue queue = GetQueue(serviceName);
         if (queue == null)
         {
             IServiceConfiguration config = _config.Services.FirstOrDefault(x => x.ServiceName == serviceName);
             if (config != null)
             {
                 queue = new BusQueue(_connection, config, _logger);
                 _queueList.Add(queue);
             }
             if (queue == null)
             {
                 return(false);
             }
         }
         return(queue.TryInit());
     }
     catch (Exception e)
     {
         _logger?.LogError(e, $"{_config.LocalIP} : {_config.ApplicationName}.{typeof(BusManager).FullName} : {e.Message}");
         return(false);
     }
 }
        public override void Setup()
        {
            ServiceConfiguration = new ServiceConfiguration {
                new EmployerAccountSiteManifest()
            };

            MockManifestRepository = new Mock <IManifestRepository>();
            MockPermissionsChecker = new Mock <ICheckPermissions>();
            MockPermissionsGranter = new Mock <IGrantPermissions>();

            Unit = new Portal.Web.Controllers.ResourceController(
                MockManifestRepository.Object,
                MockPermissionsChecker.Object,
                MockPermissionsGranter.Object,
                ServiceConfiguration);

            MockContextBase = new Mock <HttpContextBase>();

            MockContextBase.Setup(x => x.Request).Returns(new Mock <HttpRequestBase>().Object);
            MockContextBase.Setup(x => x.Response).Returns(new Mock <HttpResponseBase>().Object);
            MockContextBase.Setup(x => x.User).Returns(new Mock <IPrincipal>().Object);

            UnitControllerContext = new ControllerContext(MockContextBase.Object, new RouteData(), Unit);

            Unit.ControllerContext = UnitControllerContext;
        }
예제 #14
0
        internal IServiceManager GetServiceManager(
            IServiceConfiguration configuration,
            Type[] generics)
        {
            var key     = configuration.TypeFactory.MutateKey(configuration.Key, generics);
            var compKey = new ServiceConfigurationServiceConfigurationKey(configuration, key);

            IServiceManager manager;

            if (!_activeServices.TryGetValue(compKey, out manager))
            {
                manager = configuration.BuildServiceManager(this, generics);

                _activeServices.Add(compKey, manager);

                // Cache the primary service key if neccessary
                if (!_primaryActiveService.ContainsKey(key))
                {
                    _primaryActiveService.Add(key, manager);
                }

                // Attempt to cache all configuration cache keys. These must succeed. If an overlap is detected an exception will be thrown.
                foreach (ServiceConfigurationKey cacheKey in configuration.TypeFactory.MutateKeys(configuration.DefaultCacheKeys, generics))
                {
                    _primaryActiveService.Add(cacheKey, manager);
                }
            }

            return(manager);
        }
예제 #15
0
        public void SetUp()
        {
            _host = new Host <TradeServiceStartup>();
            _app  = _host.Build();
            _app.Start();

            _configuration = AppCore.Instance.Get <IServiceConfiguration>();

            var jsonSettings   = new AppJsonSerializer();
            var jsonSerializer = JsonSerializer.Create(jsonSettings);

            AppCore.Instance.ObjectProvider.Configure(conf => conf.For <JsonSerializerSettings>().Use(jsonSettings));
            AppCore.Instance.ObjectProvider.Configure(conf => conf.For <JsonSerializer>().Use(jsonSerializer));

            _traderToken = ApiServiceBuilder <IUserService> .Build("http://localhost:8080")
                           .Create()
                           .Login(new Credentials()
            {
                Username = "******",
                Password = "******"
            }).Result;

            _tradeClient = ApiServiceBuilder <ITradeService> .Build("http://localhost:8080")
                           .AddAuthorizationHeader(() => _traderToken.Digest)
                           .Create();

            _priceClient = AppCore.Instance.GetService <IPriceService>();

            Task.Delay(1000);

            var publisher = AppCore.Instance.Get <IPublisher>();

            publisher.Stop().Wait();
        }
예제 #16
0
 public HttpDiagnosticsService(IServiceConfiguration configuration)
 {
     this.configuration = configuration;
     collector          = new TimeSeriesCollector();
     carbonWriter       = CarbonWriterFactory.Instance();
     graphDataHandler   = new GraphDataHandler(collector);
 }
예제 #17
0
        /// <summary>
        /// Converts to HATEOAS response.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="path">The path.</param>
        /// <param name="isPostPut">if set to <c>true</c> [is post put].</param>
        /// <returns></returns>
        private object ConvertToHateoas(object source, IServiceConfiguration configuration, MessagePath path, bool isPostPut = false)
        {
            IList <HateoasLink> links      = path.Links;
            JsonSerializer      serializer = IoC.Get <JsonSerializer>();

            if ((path.HasKeyParameter) || (path.IsByParent) || isPostPut)
            {
                JObject jobject = JObject.FromObject(source, serializer);
                JArray  jarray  = JArray.FromObject(links, serializer);
                if (configuration.IsCamelCase)
                {
                    jobject.Add("links", jarray);
                }
                else
                {
                    jobject.Add("Links", jarray);
                }
                return(jobject);
            }
            else
            {
                HateoasReponse response = new HateoasReponse();
                response.Items = source;
                response.Links = links;
                return(JObject.FromObject(response, serializer));
            }
        }
예제 #18
0
        public Message Put(Message message)
        {
            MessageInformation information = new MessageInformation(message);

            try
            {
                string      sessionToken = this.GetSessionToken(information);
                MessagePath path         = new MessagePath(information);
                if (path.HasKeyParameter)
                {
                    throw new ArgumentException("POST operation cannot have a key parameter in the path.");
                }
                ISecurityManager       securityManager = IoC.Get <ISecurityManager>();
                dynamic                bo            = securityManager.DynamicGetBO(path.DtoType, sessionToken);
                dynamic                dto           = information.GetBody(path.DtoType);
                object                 response      = bo.Update(dto);
                IServiceConfiguration  configuration = IoC.Get <IServiceConfiguration>();
                JsonSerializerSettings settings      = IoC.Get <JsonSerializerSettings>();
                if (configuration.IsHateoas)
                {
                    response = this.ConvertToHateoas(response, configuration, path);
                }
                return(response.ToJsonMessage(settings, configuration.Indented));
            }
            catch (Exception ex)
            {
                return(ex.Message.ToJsonMessage());
            }
        }
예제 #19
0
 public BusQueue(IBusConnection connection, IServiceConfiguration config, ILogger logger = null)
 {
     _connection = connection;
     _config     = config;
     _logger     = logger;
     TryInit();
 }
예제 #20
0
 public StockChangeHandler(IServiceConfiguration configuration, IAzureTopicSubscriber topicSubscriber, IStockQuantityCommand command, IStockQuantityQuery stockQuantityQuery)
 {
     _configuration      = configuration;
     _topicSubscriber    = topicSubscriber;
     _command            = command;
     _stockQuantityQuery = stockQuantityQuery;
 }
예제 #21
0
 public NewsHeadlineFetcher(IHttpClientFactory httpClient, IServiceConfiguration configuration)
 {
     // https://www.telerik.com/blogs/.net-core-background-services
     _httpClient         = httpClient.CreateClient();
     _newsServiceUrl     = configuration.NewsServiceApiEndpointUri;
     _newsServiceUserUrl = configuration.NewsServiceUserUri;
 }
예제 #22
0
        protected virtual IServiceConfiguration <IDiscoveryService> GetServiceConfiguration(CrmConnection connection)
        {
            var mode = connection.ServiceConfigurationInstanceMode;

            if (mode == ServiceConfigurationInstanceMode.Static)
            {
                return(_config ?? (_config = CreateServiceConfiguration(connection)));
            }

            if (mode == ServiceConfigurationInstanceMode.PerName)
            {
                var key = connection.GetConnectionId();

                if (!_configLookup.ContainsKey(key))
                {
                    _configLookup[key] = CreateServiceConfiguration(connection);
                }

                return(_configLookup[key]);
            }

            if (mode == ServiceConfigurationInstanceMode.PerRequest && HttpSingleton <IServiceConfiguration <IDiscoveryService> > .Enabled)
            {
                var key = connection.GetConnectionId();

                return(HttpSingleton <IServiceConfiguration <IDiscoveryService> > .GetInstance(key, () => CreateServiceConfiguration(connection)));
            }

            var config = CreateServiceConfiguration(connection);

            return(config);
        }
        public AddPlayerToGameRequestDialog(IEnumerable <ICommunicator> communicators, Guid userId,
                                            AddPlayerToGameRequest dialogData,
                                            ILogger logger, IMediator mediator, IThreadContextSessionProvider threadContextSessionProvider,
                                            IGameRepository gameRepository, IServiceConfiguration serviceConfiguration) : base(logger, communicators,
                                                                                                                               userId, dialogData)
        {
            _mediator = mediator;
            _threadContextSessionProvider = threadContextSessionProvider;
            _gameRepository       = gameRepository;
            _serviceConfiguration = serviceConfiguration;
            _hasDesicion          = false;

            using (threadContextSessionProvider.CreateSessionScope())
            {
                var games = gameRepository.ListBySpecification(new UndeletedEntities <Game>()).ToList();
                games = games.Where(x =>
                                    x.AcceptedPlayers.Count + x.RequestedPlayers.Count <serviceConfiguration.PlayersPerTeam * 2 &&
                                                                                        x.IsActive &&
                                                                                        x.DateTime>
                                    DateTime.Now
                                    .Add(
                                        serviceConfiguration
                                        .GameDeadline,
                                        serviceConfiguration
                                        .StartDayTime,
                                        serviceConfiguration
                                        .EndDayTime))
                        .OrderBy(x => x.DateTime)
                        .Take(20).ToList();
                if (!games.Any())
                {
                    Add($"Нет игр для добавления игроков");
                }
                else
                {
                    Add($"Введи номер игры, в которую хочешь добавить игроков:");

                    var gamesMessage = string.Join("\n",
                                                   games.Select((x, index) =>
                                                                $"{index + 1}. Дата: {x.DateTime.ToString(DateTimeHelper.DateFormat)}"));
                    Add(gamesMessage);

                    Add((message, data) =>
                    {
                        if (!int.TryParse(message, out var number) || (number < 1 && number > games.Count()))
                        {
                            throw new InvalidInputException($"Введи номер игры от 1 до {games.Count()}");
                        }

                        data.GameId = games[number - 1].Id;
                        var game    = games[number - 1];

                        AddPlayerProcessingMessages(game.Id);

                        return(data);
                    });
                }
            }
        }
        public void Install(IServiceConfiguration configuration)
        {
            Guard.AgainstNull(configuration, nameof(configuration));

            GuardAdministrator();

            if (!string.IsNullOrEmpty(configuration.ServicePath))
            {
                new ServiceInvoker(configuration).Execute(ServiceCommand.Install);

                return;
            }

            CallContext.LogicalSetData(ServiceConfigurationKey, configuration);

            var instancedServiceName = configuration.GetInstancedServiceName();
            var log = ServiceHostEventLog.GetEventLog(instancedServiceName);

            ConsoleExtensions.WriteLine(ConsoleColor.Green, $"Installing service '{instancedServiceName}'.");

            var entryAssembly = Assembly.GetEntryAssembly();

            if (entryAssembly == null)
            {
                throw new InvalidOperationException("An entry assembly is required in order to install a service.");
            }

            var entryAssemblyLocation = entryAssembly.Location;

            if (string.IsNullOrEmpty(entryAssemblyLocation))
            {
                throw new InvalidOperationException("The entry assembly has no location.");
            }

            if (!Path.GetExtension(entryAssemblyLocation).Equals(".exe", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new InvalidOperationException(
                          "The entry assembly must be an 'exe' in order to install as a service.");
            }

            var assemblyInstaller = new AssemblyInstaller(typeof(ServiceHost).Assembly, null);

            using (var installer = assemblyInstaller)
            {
                IDictionary state = new Hashtable();

                installer.UseNewContext = true;

                try
                {
                    installer.Install(state);
                    installer.Commit(state);

                    var serviceKey = GetServiceKey(instancedServiceName);

                    serviceKey.SetValue("Description", configuration.Description);
                    serviceKey.SetValue("ImagePath",
                                        $"{entryAssemblyLocation} /serviceName=\"{configuration.ServiceName}\"{(string.IsNullOrEmpty(configuration.Instance) ? string.Empty : $" /instance=\"{configuration.Instance}\"")}");
                }
예제 #25
0
 internal ScopedServiceManager(
     IServiceConfiguration configuration,
     ServiceProvider provider,
     Type[] generics) : base(configuration, provider, generics)
 {
     _getInstance          = this.BuildInstance;
     _getInstanceWithSetup = this.BuildInstance;
 }
예제 #26
0
 public static IApplicationBuilder UseSwagger(this IApplicationBuilder app, IServiceConfiguration serviceConfiguration)
 {
     app.UseSwagger();
     return(app.UseSwaggerUI(options =>
     {
         options.SwaggerEndpoint($"/swagger/v{serviceConfiguration.Version}/swagger.json", $"API [{serviceConfiguration.Name}] v.{serviceConfiguration.Version}");
     }));
 }
예제 #27
0
 public DefaultServiceStarter(IServiceHost serviceHost, IServiceConfiguration serviceConfiguration, TClient client)
 {
     Client      = client;
     ServiceHost = serviceHost;
     Environment = new Dictionary <string, object> {
         { Service.EnvironmentKeys.StartParameters, serviceConfiguration.StartParameters }
     };
 }
        public ConsoleService(IServiceHostStart service, IServiceConfiguration configuration)
        {
            Guard.AgainstNull(service, nameof(service));
            Guard.AgainstNull(configuration, nameof(configuration));

            _configuration = configuration;
            _service       = service;
        }
예제 #29
0
        public override IRestResponse <TResult> GetResponse <TResult>(IServiceConfiguration serviceConfiguration, IRestClient client, IRestRequest restRequest)
        {
            var response = base.GetResponse <TResult>(serviceConfiguration, client, restRequest);

            Log.Debug("Sitecore.RestSharp: Response data:\n" + JsonConvert.SerializeObject(response, Formatting.Indented), this);

            return(response);
        }
예제 #30
0
        public Message Get(Message message)
        {
            MessageInformation information = new MessageInformation(message);

            try
            {
                string           sessionToken    = this.GetSessionToken(information);
                MessagePath      path            = new MessagePath(information);
                ISecurityManager securityManager = IoC.Get <ISecurityManager>();
                object           response;
                if (path.IsByParent)
                {
                    MessagePath parentPath = new MessagePath(information, true);
                    if (!parentPath.HasKeyParameter)
                    {
                        throw new ArgumentException("A link to a parent must have parameter key");
                    }
                    dynamic      bo     = securityManager.DynamicGetBO(parentPath.DtoType, sessionToken);
                    object       parent = bo.GetOne(string.Empty, parentPath.QueryInfo);
                    IObjectProxy proxy  = ObjectProxyFactory.Get(parent);
                    object       value  = proxy.GetValue(parent, path.ParentKeyParameter);
                    QueryInfo    query  = new QueryInfo();
                    query.Equal(path.KeyParameterName, value.ToString());
                    bo       = securityManager.DynamicGetBO(path.DtoType, sessionToken);
                    response = bo.GetOne(string.Empty, query);
                }
                else
                {
                    dynamic bo = securityManager.DynamicGetBO(path.DtoType, sessionToken);
                    if (path.HasKeyParameter)
                    {
                        response = bo.GetOne(string.Empty, path.QueryInfo);
                    }
                    else
                    {
                        response = bo.GetAll(path.QueryInfo);
                    }
                }
                IServiceConfiguration  configuration = IoC.Get <IServiceConfiguration>();
                JsonSerializerSettings settings      = IoC.Get <JsonSerializerSettings>();
                if (configuration.IsHateoas)
                {
                    response = this.ConvertToHateoas(response, configuration, path);
                }
                return(response.ToJsonMessage(settings, configuration.Indented));
            }
            catch (Exception ex)
            {
                if (ex is TargetInvocationException)
                {
                    return(ex.InnerException.Message.ToJsonMessage());
                }
                else
                {
                    return(ex.Message.ToJsonMessage());
                }
            }
        }
예제 #31
0
 internal TransientServiceManager(
     IServiceConfiguration configuration,
     ServiceProvider provider,
     Type[] generics)
 {
     this.configuration = configuration;
     this.provider      = provider;
     this.generics      = generics;
 }
 /// <summary>
 /// Helper method to get a calendar factory, consider splitting this out into yet another factory class.
 /// </summary>
 /// <param name="calendarConfiguration"></param>
 /// <param name="serviceConfiguration"></param>
 /// <returns></returns>
 private ICalendarFactory GetCalendarFactory(ICalendarConfiguration calendarConfiguration, IServiceConfiguration serviceConfiguration)
 {
     switch (calendarConfiguration.CalendarType)
     {
         case CalendarType.Google:
             return GetGoogleCalendarFactory(calendarConfiguration, serviceConfiguration);
         case CalendarType.Exchange:
             return GetExchangeCalendarFactory(calendarConfiguration);
         default:
             throw new InvalidDataException("Unknown calendar type");
     }
 }
      public void Start(IServiceConfiguration configuration)
      {
        BioData.BioSkyNetRepository _database = _locator.GetProcessor<BioData.BioSkyNetRepository>();
        _server = new Server
        {
          Services = { BiometricDatabaseSevice.BindService(new BiometricDatabaseSeviceImpl(_database)) },
          Ports = { new ServerPort(configuration.IpAddress, configuration.Port, ServerCredentials.Insecure) }
        };
        _server.Start();

        Console.WriteLine("BiometricDatabaseSevice server listening on port " + configuration.Port);
        Console.WriteLine("Press any key to stop the server...");
    }
예제 #34
0
 /// <summary>
 /// Configures the API from a root node.
 /// </summary>
 /// <param name="node">The node.</param>
 /// <param name="configuration">The configuration.</param>
 private static void ConfigureApi(XmlNode node, IServiceConfiguration configuration)
 {
     NodeAttributes attributes = new NodeAttributes(node);
     Type dtoType = GetDtoType(attributes.AsString("dtoType"), attributes.AsString("dtoName"), attributes.AsString("path"), attributes.AsString("entityName"), attributes.AsString("entityType"));
     if (dtoType != null)
     {
         string parameterName = attributes.AsString("parameterName");
         if (string.IsNullOrEmpty(parameterName))
         {
             parameterName = GetParameterName(attributes.AsString("path"), dtoType);
         }
         ApiNode childnode = configuration.AddNode(attributes.AsString("path"), dtoType, parameterName, attributes.AsString("byparent"));
         foreach (XmlNode subnode in node.SelectNodes("api"))
         {
             ConfigureApi(subnode, childnode);
         }
     }
 }
 public HttpHostConfiguration AddServiceConfiguration(IServiceConfiguration configureService)
 {
     this.serviceConfiguration.Add(configureService);
     return this;
 }
예제 #36
0
 /// <summary>
 /// Converts to HATEOAS response.
 /// </summary>
 /// <param name="source">The source.</param>
 /// <param name="configuration">The configuration.</param>
 /// <param name="path">The path.</param>
 /// <param name="isPostPut">if set to <c>true</c> [is post put].</param>
 /// <returns></returns>
 private object ConvertToHateoas(object source, IServiceConfiguration configuration, MessagePath path, bool isPostPut = false)
 {
     IList<HateoasLink> links = path.Links;
     JsonSerializer serializer = IoC.Get<JsonSerializer>();
     if ((path.HasKeyParameter) || (path.IsByParent) || isPostPut)
     {
         JObject jobject = JObject.FromObject(source, serializer);
         JArray jarray = JArray.FromObject(links, serializer);
         if (configuration.IsCamelCase)
         {
             jobject.Add("links", jarray);
         }
         else
         {
             jobject.Add("Links", jarray);
         }
         return jobject;
     }
     else
     {
         HateoasReponse response = new HateoasReponse();
         response.Items = source;
         response.Links = links;
         return JObject.FromObject(response, serializer);
     }
 }
예제 #37
0
 public SMDRReaderService(IServiceConfiguration config)
 {
     _config = config;
     _server = new ReactiveListener(_config.Port);
     SetupSubscriptions(_server);
 }
예제 #38
0
 ClientCredentials CreateDeviceCredentials(IServiceConfiguration<IOrganizationService> orgServiceConfig)
 {
     if (orgServiceConfig.AuthenticationType != AuthenticationProviderType.LiveId)
     {
         return null;
     }
     if (!string.IsNullOrEmpty(Parameters.DeviceID) && !string.IsNullOrEmpty(Parameters.DevicePassword))
     {
         return new ClientCredentials
             {
                 UserName =
                     {
                         UserName = Parameters.DeviceID,
                         Password = Parameters.DevicePassword
                     }
             };
     }
     return DeviceIdManager.LoadOrRegisterDevice(CrmSvcUtil.ApplicationId, orgServiceConfig.CurrentIssuer.IssuerAddress.Uri);
 }
예제 #39
0
 private static IServiceConfiguration GetConfiguration()
 {
     IServiceConfiguration configuration = null;
     try
     {
         configuration = (ServiceConfiguration) ConfigurationManager.GetSection("etservice/diagnostics");
     }
     catch (Exception e)
     {
         logger.Warn("Could not load configuration section etservice/diagnostics. Using defaults", e);
     }
     return configuration ?? new StaticServiceConfiguration();
 }
        /// <summary>
        /// Helper method to create a GoogleCalendarFactory
        /// </summary>
        /// <param name="calendarConfiguration"></param>
        /// <param name="serviceConfiguration"></param>
        /// <returns></returns>
        private ICalendarFactory GetGoogleCalendarFactory(ICalendarConfiguration calendarConfiguration, IServiceConfiguration serviceConfiguration)
        {
            var googleCalendarConfiguration = calendarConfiguration as GoogleCalendarConfiguration;
            if (googleCalendarConfiguration == null)
            {
                throw new InvalidDataException("Unable to cast calendar config to Google calendar format.");
            }

            var googleServiceConfiguration = serviceConfiguration as GoogleServiceConfiguration;
            if (googleServiceConfiguration == null)
            {
                throw new InvalidDataException("Unable to cast service config to Google service format.");
            }

            return new GoogleCalendarFactory(googleCalendarConfiguration, googleServiceConfiguration);
        }