Esempio n. 1
0
 public void Configure(EndPointConfiguration configuration)
 {
     _methodPackageMetadataCreator.SetConfiguration(configuration);
     _variableReplacementService.Configure(configuration);
     _routeLength = configuration.Route.Length;
     ProcessAssets(configuration);
 }
Esempio n. 2
0
        /// <summary>
        /// Método que realiza un GET al Servicio especificado sin parámetros
        /// </summary>
        /// <param name="client">HttpClient con la instancia</param>
        /// <param name="serviceName">Nombre del Servicio a utilizar</param>
        /// <returns></returns>
        public static async Task <TReturn> GetAsync <TReturn>(this HttpClient client, string serviceName)
        {
            //using (var trace = new TracerDb())
            //{
            //    trace.TraceInformation("Invocando Método GetAsync(), Servicio: [{0}]", serviceName);

            var success = false;

            //var endPointSection = EndPointConfigurationManager.GetPolicyConfiguration(serviceName);
            var endPointSection = new EndPointConfiguration {
                Address = ""
            };

            //var currentRetry = endPointSection.Retries;

            //do
            //{
            try
            {
                // Checkea el intento actual de la llamada, si es distinto al de la configuración aplica el Task.Delay de acuerdo a la configuración
                //if (currentRetry != endPointSection.Retries)
                //    await Task.Delay(endPointSection.Wait);

                // Setea los headers para la petición
                SetHttpClientSettings(client, endPointSection.Policies);

                //trace.TraceInformation("Se generará la Petición (GetAsync): [{0}]", endPointSection.Address);

                var response = await client.GetAsync(endPointSection.Address).ConfigureAwait(false);

                var jsonString = await response.Content.ReadAsStringAsync();

                success = response.IsSuccessStatusCode;

                //trace.TraceInformation("jsonString: [{0}], IsSuccessStatusCode: [{1}]", jsonString, response.IsSuccessStatusCode,
                //    new TraceMainData(endPointSection.Address, 0, serviceName));

                // Si el Response es Success, Deserializa el json string en un objeto Generic T
                if (response.IsSuccessStatusCode)
                {
                    return(await response.Content.ReadAsAsync <TReturn>());
                }

                //trace.TraceError("Ha ocurrido un error con el resultado de la llamada al Servicio: [{0}], ReasonPhrase:[{1}], StatusCode: [{2}], Reintento:[{3}]",
                //    endPointSection.Address, response.ReasonPhrase, response.StatusCode, currentRetry);

                //currentRetry--;
            }
            catch (Exception ex)
            {
                //currentRetry--;

                //trace.TraceError("Se ha generado una excepción: [{0}]. Detalle de excepción: [{1}]. Se setea el Reintento: [{2}]", ex.Message, ex.GetInnerExceptionsDetail(), currentRetry,
                //    new TraceMainData(endPointSection.Address, 0, serviceName));
            }
            //} while (!success && currentRetry > 0);

            throw new ServiceResponseException(Messages.ServiceInternalError, endPointSection.Address);
            //}
        }
Esempio n. 3
0
        public void StartWCF()
        {
            logger.Debug("Configuring WCF...");

            logger.Debug("Registering WCF as written in config file.");

            _sh = new ServiceHost(typeof(GManager), new Uri[] { });
            Alchemi.Core.Utility.WCFUtils.SetPublishingServiceHost(_sh);

            foreach (string key in Config.EndPoints.Keys)
            {
                EndPointConfiguration epc = Config.EndPoints[key];
                if (epc.RemotingMechanism != RemotingMechanism.TcpBinary)
                {
                    EndPoint ep = epc.GetEndPoint();
                    logger.Debug(String.Format("Registering WCF end point {0}...", ep.ToString()));
                    try
                    {
                        _sh.AddServiceEndpoint(typeof(IManager), Alchemi.Core.Utility.WCFUtils.GetWCFBinding(ep), ep.FullPublishingAddress);
                        logger.Debug("Success.");
                    }
                    catch (Exception ex)
                    {
                        logger.Debug(String.Format("Failed Registering WCF end point {0} with exception {1}", ep.ToString(), ex.ToString()));
                    }
                }
            }

            _sh.Open();
        }
Esempio n. 4
0
 public void ServicePath(EndPointConfiguration configuration)
 {
     _path          = configuration.Route;
     _title         = configuration.DocumentationConfiguration.Title ?? GenerateTitle(configuration);
     _versionString = configuration.DocumentationConfiguration.VersionString ?? GenerateVersionString();
     _urlBase       = configuration.DocumentationConfiguration.CustomBaseUrl;
 }
Esempio n. 5
0
        private void ProcessAssets(EndPointConfiguration configuration)
        {
            SetupExtractAssetPath();

            ExtractZipFile();

            WriteCustomCss(configuration);

            CreateBundles();
        }
Esempio n. 6
0
        public void SetConfiguration(EndPointConfiguration endPointConfiguration)
        {
            _configuration = endPointConfiguration;

            var routes = new Dictionary <string, List <IExposedMethodInformation> >();

            foreach (var information in _configuration.Methods.Values)
            {
                foreach (var routeName in information.RouteNames)
                {
                    if (!routes.TryGetValue(routeName, out var methodList))
                    {
                        methodList = new List <IExposedMethodInformation>();

                        routes[routeName] = methodList;
                    }

                    if (!methodList.Contains(information))
                    {
                        methodList.Add(information);
                    }
                }
            }

            _dataPackages = new List <JsonDataPackage>();

            var sortedRoutes = routes.OrderBy(kvp => kvp.Key);

            foreach (var route in sortedRoutes)
            {
                var methods = new List <RpcMethodInfo>();

                route.Value.Sort((x, y) => string.Compare(x.MethodName, y.MethodName, StringComparison.OrdinalIgnoreCase));

                foreach (var methodInformation in route.Value)
                {
                    methods.Add(GenerateInfoForMethod(route.Key, methodInformation));
                }

                if (methods.Count > 0)
                {
                    _dataPackages.Add(new JsonDataPackage
                    {
                        Route       = _configuration.Route,
                        DisplayName = route.Key,
                        Methods     = methods
                    });
                }
            }

            _typeDefinitions = _typeDefinitionPackageProvider.GetTypeDefinitions(_dataPackages).ToList();
            _xmlDocumentationProvider.PopulateMethodDocumentation(_dataPackages, _typeDefinitions);
        }
Esempio n. 7
0
        /// <summary>
        /// Configure the connecter.
        /// </summary>
        /// <param name="id">The id of this connector.</param>
        /// <param name="config">The configuration to use to connect to the database</param>
        /// <param name="handler">The callback to invoke when the connecter state changes</param>
        public virtual void Configure(string id, EndPointConfiguration config, IDataHandler handler)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException("id");
            }
            _id = id;

            _config  = config ?? throw new ArgumentNullException("config");
            _handler = handler ?? throw new ArgumentNullException("handler");

            _data = new List <IEntityCollection>();
        }
Esempio n. 8
0
        private EndPoint Start(EndPointConfiguration configuration)
        {
            var endpoint = new IPEndPoint(configuration.Address, configuration.Port);

            if (configuration.Security == null)
            {
                return(new InsecureEndPoint(Server, endpoint, NetworkConfiguration));
            }
            else
            {
                return(new SecureEndPoint(Server, endpoint, configuration.Security, NetworkConfiguration));
            }
        }
Esempio n. 9
0
 /// <summary>
 /// Create a publisher.
 /// </summary>
 /// <param name="type">Fully qualified name of the publisher class</param>
 /// <param name="id">Id of the publisher</param>
 /// <param name="config">The config parameters for connecting to the data end point</param>
 /// <returns>A new publisher</returns>
 public static IPublisher CreatePublisher(PublisherConfiguration config, EndPointConfiguration endpointConfig)
 {
     try
     {
         var publisher = ComponentRegistration.CreateInstance <IPublisher>(config.Type);
         publisher.Configure(config.Id, endpointConfig);
         return(publisher);
     }
     catch (Exception e)
     {
         _logger.Error(e);
     }
     return(null);
 }
        private void RegisterDependencies(IServiceCollection services)
        {
            services.AddSimpleIdentityServerWebSite(opt =>
            {
                opt.IsHttpsAuthentication   = true;
                opt.IsCertificateSelfSigned = true;
                opt.Certificate             = CertificateProvider.Get();
                opt.DockerApiUri            = new Uri(_simpleIdentityServerOptions.DockerApiUrl);
            });
            var endPointConfiguration = new EndPointConfiguration(_simpleIdentityServerOptions.InstancePatternUrl);

            services.AddInstance <IEndPointConfiguration>(endPointConfiguration);
            services.AddSimpleIdentityServerEf(_simpleIdentityServerOptions.ConnectionString);
        }
Esempio n. 11
0
 /// <summary>
 /// Create a connecter with a state change handler that will get invoked when the connecter's state changes.
 /// </summary>
 /// <param name="type">Fully qualified name of the connecter class and assembly, comma seperated.</param>
 /// <param name="id">The id of the connector.</param>
 /// <param name="config">The config parameters for connecting to the data source</param>
 /// <param name="handler">The handler to signal with blocks of data</param>
 /// <returns>A new connecter</returns>
 public static IReader CreateReader(string type, string id, EndPointConfiguration config, IDataHandler handler)
 {
     try
     {
         var connector = ComponentRegistration.CreateInstance <IReader>(type);
         connector.Configure(id, config, handler);
         return(connector);
     }
     catch (Exception e)
     {
         _logger.Error(e);
     }
     return(null);
 }
Esempio n. 12
0
        /// <summary>
        /// Create an end point config.
        /// </summary>
        /// <param name="id">The id of the config</param>
        /// <param name="propertyKey">The property key</param>
        /// <param name="propertyValue">The property value</param>
        /// <returns>A new config</returns>
        public static EndPointConfiguration CreateEndPointConfig(string id, string propertyKey, string propertyValue)
        {
            var properties = new Dictionary <string, string>();

            properties.Add(propertyKey, propertyValue);
            var config = new EndPointConfiguration
            {
                Id         = id,
                User       = "******",
                Password   = "******",
                Properties = properties
            };

            return(config);
        }
Esempio n. 13
0
        protected virtual string GenerateTitle(EndPointConfiguration configuration)
        {
            var method = configuration.Methods.Values.FirstOrDefault()?.MethodInfo;

            if (method != null)
            {
                var title = method.DeclaringType.FullName;
                var index = title.IndexOf('.');

                if (index > 0)
                {
                    return(title.Substring(0, index));
                }
            }

            return("Api");
        }
Esempio n. 14
0
        private void WriteCustomCss(EndPointConfiguration configuration)
        {
            var cssPath = Path.Combine(ExtractedAssetPath, "css", "custom.css");

            using (var customCssFile = File.Open(cssPath, FileMode.Create))
            {
                using (var streamWriter = new StreamWriter(customCssFile))
                {
                    var width = configuration.DocumentationConfiguration.MenuWidth;

                    if (width.HasValue)
                    {
                        streamWriter.WriteLine($".docs-sidebar .docs-nav{{width:{width}rem}}");
                        streamWriter.WriteLine($".off-canvas .off-canvas-sidebar{{width:{width}rem}}");
                    }

                    streamWriter.Write(configuration.DocumentationConfiguration.CustomCss);
                }
            }
        }
Esempio n. 15
0
        public static IdPSSODescriptorConfiguration BuildIdPSSODescriptorConfiguration()
        {
            var idPSSODescriptorConfiguration = new IdPSSODescriptorConfiguration
            {
                ValidUntil   = new DateTimeOffset(DateTime.Now.AddDays(100)),
                Organisation = MetadataHelper.BuildOrganisationConfiguration(),
                WantAuthenticationRequestsSigned = true,
                CacheDuration      = TimeSpan.FromDays(100),
                RoleDescriptorType = typeof(IdentityProviderSingleSignOnDescriptor),
                ErrorUrl           = new Uri("http://localhost:60879/api/Account/Error")
            };

            idPSSODescriptorConfiguration.NameIdentifierFormats.Add(new Uri("urn:oasis:names:tc:SAML:2.0:nameid-format:transient"));
            idPSSODescriptorConfiguration.NameIdentifierFormats.Add(new Uri("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"));
            idPSSODescriptorConfiguration.SingleLogoutServices.Add(new EndPointConfiguration
            {
                Binding  = new Uri("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"),
                Location = new Uri("http://localhost:60879/api/Account/SSOLogout")
            });
            //supported protocols
            idPSSODescriptorConfiguration.ProtocolSupported.Add(new Uri("urn:oasis:names:tc:SAML:2.0:protocol"));
            //key descriptors
            var keyDescriptorConfiguration = MetadataHelper.BuildKeyDescriptorConfiguration();

            foreach (var k in keyDescriptorConfiguration)
            {
                idPSSODescriptorConfiguration.KeyDescriptors.Add(k);
            }

            //assertinon service
            var endPointConfiguration = new EndPointConfiguration
            {
                Binding  = new Uri(ProtocolBindings.HttpRedirect),
                Location = new Uri("https://localhost:44342/sso/login")
            };

            idPSSODescriptorConfiguration.SignOnServices.Add(endPointConfiguration);

            return(idPSSODescriptorConfiguration);
        }
Esempio n. 16
0
        public void SQLPrinterReader_Success()
        {
            var logger    = new MockLogger();
            var collector = new MockCollector(logger);
            var sqlReader = new MockSQLReader();
            var reader    = new SQLPrinterReader(sqlReader, logger, collector);
            var handler   = new MockHandler();
            var config    = new EndPointConfiguration()
            {
                Id       = "2",
                Password = "******",
                User     = "******",
            };

            config.Properties.Add("ServerName", "localhost");
            config.Properties.Add("Database", "MdmPrinter");
            config.Properties.Add("SqlCommand", "SELECT * FROM PRINTER");
            config.Properties.Add("Top", "100");

            reader.Configure("1", config, handler);
            reader.Run(new Dictionary <string, string>()).Wait();
            collector.GetTotalEventCount().Should().Be(1);
        }
Esempio n. 17
0
        public static async Task <TReturn> GetAsync <TReturn>(this HttpClient client, EndPointConfiguration endPointConfiguration, object value)
        {
            var queryParameters = value is int?value.ToString() : "?" + GetQueryString(value);

            endPointConfiguration.Address += queryParameters;

            return(await GetAsync <TReturn>(client, endPointConfiguration));
        }
Esempio n. 18
0
        /// <summary>
        /// Starts the Manager
        /// </summary>
        public void Start()
        {
            if (Started || _Starting)
            {
                return;
            }

            try
            {
                _Starting = true;

                if (Config == null)
                {
                    ReadConfig();
                }

                //See if there is any remoting end poit.
                //There can be only one remoting end point.
                //See if there are any WCF end point. Thre can be more WCF end points.
                EndPointConfiguration remotingEpc = null;
                bool areAnyWcfEps = false;

                foreach (string key in Config.EndPoints.Keys)
                {
                    EndPointConfiguration epc = Config.EndPoints[key];
                    if (epc.RemotingMechanism == RemotingMechanism.TcpBinary)
                    {
                        if (remotingEpc != null)
                        {
                            throw new DoubleRemotingEndPointException("Cannot set two EndPoint where Rempting Mechanism is set to TcpBinary");
                        }

                        remotingEpc = epc;
                    }
                    else
                    {
                        areAnyWcfEps = true;
                    }
                }

                if (remotingEpc != null)
                {
                    StartTcpBinary(remotingEpc);
                }

                if (areAnyWcfEps)
                {
                    StartWCF();
                }


                logger.Debug("Configuring storage...");
                ManagerStorageFactory.CreateManagerStorage(Config);
                if (!ManagerStorageFactory.ManagerStorage().VerifyConnection())
                {
                    throw new Exception("Error connecting to manager storage. Please check manager log file for details.");
                }

                logger.Debug("Configuring internal shared class...");
                InternalShared common = InternalShared.GetInstance(Config);

                logger.Debug("Starting dispatcher thread");
                dispatcher.Start();

                logger.Info("Starting watchdog thread");
                watchdog.Start();

                //start a seperate thread to init-known executors, since this may take a while.
                _InitExecutorsThread      = new Thread(new ThreadStart(InitExecutors));
                _InitExecutorsThread.Name = "InitExecutorsThread";
                _InitExecutorsThread.Start();

                Config.Serialize();

                Started = true;

                try
                {
                    if (ManagerStartEvent != null)
                    {
                        ManagerStartEvent(this, new EventArgs());
                    }
                }
                catch { }
            }
            catch (Exception ex)
            {
                Stop();
                logger.Error("Error Starting Manager Container", ex);
                throw ex;
            }
            finally
            {
                _Starting = false;
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Create an entire stack.
        /// </summary>
        /// <param name="readerId"></param>
        /// <param name="config"></param>
        /// <returns></returns>
        public static IStack CreateStack(string readerId, CollectorConfiguration config)
        {
            var stack = ComponentRegistration.CreateInstance <IStack>(config.StackType);

            foreach (var readerConfig in config.Readers)
            {
                if (readerConfig.Id == readerId)
                {
                    var newReaderId = Guid.NewGuid().ToString();

                    List <IPublisher>   publishers   = new List <IPublisher>();
                    List <ITransformer> transformers = new List <ITransformer>();
                    foreach (var transformerConfig in config.Transformers)
                    {
                        if (transformerConfig.ReaderId == readerId)
                        {
                            var newTransformerId = Guid.NewGuid().ToString();
                            foreach (var publisherConfig in config.Publishers)
                            {
                                if (publisherConfig.TransformerId == transformerConfig.Id)
                                {
                                    foreach (var endpoint in config.EndPoints)
                                    {
                                        if (endpoint.Id == publisherConfig.EndpointId)
                                        {
                                            var newEndpoint = new EndPointConfiguration()
                                            {
                                                Id       = Guid.NewGuid().ToString(),
                                                Password = endpoint.Password,
                                                User     = endpoint.User
                                            };
                                            foreach (var key in endpoint.Properties.Keys)
                                            {
                                                newEndpoint.Properties.Add(key, endpoint.Properties[key]);
                                            }

                                            var newPublisherConfig = new PublisherConfiguration()
                                            {
                                                Id            = Guid.NewGuid().ToString(),
                                                EndpointId    = newEndpoint.Id,
                                                TransformerId = newTransformerId,
                                                Type          = publisherConfig.Type
                                            };
                                            var publisher = CreatePublisher(newPublisherConfig, endpoint);
                                            publishers.Add(publisher);
                                        }
                                    }
                                }
                            }
                            var newTransformerConfig = new TransformerConfiguration()
                            {
                                Id       = newTransformerId,
                                Type     = transformerConfig.Type,
                                ReaderId = newReaderId,
                            };
                            foreach (var mapper in transformerConfig.Mappers)
                            {
                                var newMapperConfig = new MapperConfiguration()
                                {
                                    Id                   = mapper.Id,
                                    DataType             = mapper.DataType,
                                    TransformerId        = newTransformerId,
                                    Type                 = mapper.Type,
                                    SourceTargetMappings = mapper.SourceTargetMappings
                                };
                                foreach (var converter in mapper.PipedConverters)
                                {
                                    var newConverter = CopyConfig(converter);
                                    newMapperConfig.PipedConverters.Add(converter);
                                }
                                foreach (var converter in mapper.Converters)
                                {
                                    var newConverter = CopyConfig(converter);
                                    newMapperConfig.Converters.Add(converter);
                                }
                                newTransformerConfig.Mappers.Add(newMapperConfig);
                            }
                            var transformer = CreateTransformer(newTransformerConfig, stack);
                            transformers.Add(transformer);
                        }
                    }
                    foreach (var endpoint in config.EndPoints)
                    {
                        if (readerConfig.EndpointId.Equals(endpoint.Id))
                        {
                            var newEndpoint = new EndPointConfiguration()
                            {
                                Id       = Guid.NewGuid().ToString(),
                                Password = endpoint.Password,
                                User     = endpoint.User
                            };
                            foreach (var key in endpoint.Properties.Keys)
                            {
                                newEndpoint.Properties.Add(key, endpoint.Properties[key]);
                            }
                            var reader = CreateReader(readerConfig.Type, newReaderId, newEndpoint, stack);
                            stack.Configure(reader, transformers, publishers);
                            break;
                        }
                    }
                    break;
                }
            }
            return(stack);
        }
Esempio n. 20
0
        public void StartTcpBinary(EndPointConfiguration epc)
        {
            EndPoint ownEP = new EndPoint(epc.Port, RemotingMechanism.TcpBinary);

            logger.Debug("Configuring remoting...");

            RemotingConfiguration.Configure(
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, RemotingConfigFile), false);

            //TODO: for hierarchical grids
            //				RemoteEndPoint managerEP = null;
            //				if (Config.Intermediate)
            //				{
            //					managerEP = new RemoteEndPoint(
            //						Config.ManagerHost,
            //						Config.ManagerPort,
            //						RemotingMechanism.TcpBinary
            //						);
            //				}

            logger.Debug("Registering tcp channel on port: " + ownEP.Port);

            _Chnl = new TcpChannel(epc.Port);
            ChannelServices.RegisterChannel(_Chnl, false);

            //since this is a single call thing, thread safety isnt an issue

            logger.Debug("Registering well known service type");

            RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(GManager), "Alchemi_Node",
                WellKnownObjectMode.SingleCall);

            // TODO: hierarchical grids ignored until after v1.0.0

            /*
             * _Dedicated = dedicated;
             * _Id = id;
             *
             * if (Manager != null)
             * {
             *  if (_Id == "")
             *  {
             *      Log("Registering new executor ...");
             *      _Id = Manager.Executor_RegisterNewExecutor(null, new ExecutorInfo);
             *      Log("New ExecutorID = " + _Id);
             *  }
             *
             *  try
             *  {
             *      try
             *      {
             *          ConnectToManager();
             *      }
             *      catch (InvalidExecutorException)
             *      {
             *          Log("Invalid executor! Registering new executor ...");
             *          _Id = Manager.Executor_RegisterNewExecutor(null, new ExecutorInfo);
             *          Log("New ExecutorID = " + _Id);
             *          ConnectToManager();
             *      }
             *  }
             *  catch (ConnectBackException)
             *  {
             *      Log("Couldn't connect as dedicated executor. Reverting to non-dedicated executor.");
             *      _Dedicated = false;
             *      ConnectToManager();
             *  }
             * }
             */
        }
Esempio n. 21
0
 public void Configure(EndPointConfiguration configuration)
 {
     _configuration = configuration;
     _assetProvider.Configure(configuration);
 }
Esempio n. 22
0
 public void Configure(EndPointConfiguration configuration)
 {
     _replacementValueProvider.ServicePath(configuration);
 }
Esempio n. 23
0
 /// <summary>
 /// Configure content serializer
 /// </summary>
 /// <param name="configuration"></param>
 public void Configure(EndPointConfiguration configuration)
 {
 }
Esempio n. 24
0
 public virtual void Configure(string id, EndPointConfiguration config)
 {
     _id     = id;
     _config = config;
 }
Esempio n. 25
0
        /// <summary>
        /// Método que realiza un POST al Servicio especificado
        /// </summary>
        ///<param name="client">HttpClient con la instancia</param>
        /// <param name="serviceName">Nombre del Servicio a utilizar</param>
        /// <param name="value">Parámetros a utilizar para invocar el Servicio</param>
        /// <returns></returns>
        public static async Task <TReturn> PostAsync <TReturn, TInput>(this HttpClient client, string serviceName, TInput value, Guid?activityId = null)
            where TReturn : IIntegrationServiceBaseResponse, new()
        {
            //using (var trace = new TracerDb())
            //{
            var success = false;

            //Obtiene la configuración del EndPoint del Servicio de acuerdo al Nombre de la Integración
            //var endPointSection = EndPointConfigurationManager.GetPolicyConfiguration(serviceName);
            var endPointSection = new EndPointConfiguration {
                Address = ""
            };

            //var currentRetry = endPointSection.Retries;

            //do
            //{
            try
            {
                // Checkea el intento actual de la llamada, si es distinto al de la configuración aplica el Task.Delay de acuerdo a la configuración
                //if (currentRetry != endPointSection.Retries)
                //    await Task.Delay(endPointSection.Wait);

                // Setea los headers para la petición
                SetHttpClientSettings(client, endPointSection.Policies);
                client.Timeout = new TimeSpan(0, 0, 10, 0);

                var response = await client.PostAsJsonAsync(endPointSection.Address, value).ConfigureAwait(false);

                success = response.IsSuccessStatusCode;

                var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                client.DefaultRequestHeaders.Add("ResultString", responseString);

                //if (endPointSection.Trace)
                //    trace.TraceInformation("jsonString: [{0}], IsSuccessStatusCode: [{1}]", responseString, response.IsSuccessStatusCode,
                //            new TraceMainData(value, 0, serviceName, activityId: activityId));

                if (response.IsSuccessStatusCode)
                {
                    var responseService = await response.Content.ReadAsAsync <TReturn>().ConfigureAwait(false);

                    return(responseService);
                }

                //trace.TraceError(
                //"Ha ocurrido un error con el resultado de la llamada al Servicio: [{0}], ReasonPhrase:[{1}], StatusCode: [{2}], Reintento:[{3}]",
                //endPointSection.Address, response.ReasonPhrase, response.StatusCode, currentRetry, new TraceMainData(value, 0, serviceName, activityId: activityId));

                //currentRetry--;
            }
            catch (Exception ex)
            {
                var error = string.Format("Message: {0}, StackTrace: {1}", ex.Message, ex.StackTrace);
                if (ex.InnerException != null)
                {
                    error = string.Format("Message: {0}, StackTrace: {1}", ex.InnerException.Message, ex.InnerException.StackTrace);
                    if (ex.InnerException.InnerException != null)
                    {
                        error = string.Format("Message: {0}, StackTrace: {1}", ex.InnerException.InnerException.Message, ex.InnerException.InnerException.StackTrace);
                    }
                }

                //trace.TraceError("Se ha generado una excepción: [{0}], Se setea el Reintento: [{1}], Link: [{2}]",
                //    error, currentRetry, endPointSection.Address, new TraceMainData(value, 0, serviceName, activityId: activityId));

                //currentRetry--;
            }
            //} while (!success && currentRetry > 0);
            //}

            return(new TReturn {
                IsValid = false
            });
        }
Esempio n. 26
0
        public static async Task <TReturn> GetAsync <TReturn>(this HttpClient client, EndPointConfiguration endPointConfiguration)
        {
            var success = false;

            try
            {
                // Setea los headers para la petición
                SetHttpClientSettings(client, endPointConfiguration.Policies);
                var response = await client.GetAsync(endPointConfiguration.Address).ConfigureAwait(false);

                var jsonString = await response.Content.ReadAsStringAsync();

                success = response.IsSuccessStatusCode;
                // Si el Response es Success, Deserializa el json string en un objeto Generic T
                if (response.IsSuccessStatusCode)
                {
                    return(await response.Content.ReadAsAsync <TReturn>());
                }
            }
            catch (Exception ex)
            {
            }

            throw new ServiceResponseException(Messages.ServiceInternalError, endPointConfiguration.Address);
        }