Пример #1
0
        public async Task <doGetItemsInfoResponse> GetItemsInfoAsync(
            long[] offerIds,
            bool includeAttributes,
            bool includeDeliveryOptions,
            bool includeDescription,
            CancellationToken cancellationToken)
        {
            Assure.ArgumentNotNull(offerIds, nameof(offerIds));
            const int MaxItemsPerRequest = 10;

            if (offerIds.Length > MaxItemsPerRequest)
            {
                throw new NotSupportedException($"Max '{MaxItemsPerRequest}' items per request is supported.");
            }

            var requestVersionKeyInfo = await GetVersionKeyAsync(cancellationToken);

            try
            {
                var client = new servicePortClient();

                // session id can't be cached in cloud since WebApi bind session id to IP
                // todo: refactor after static IP for all external requests
                var loginResponse = await client.doLoginAsync(
                    new doLoginRequest(
                        _webApiLogin,
                        _webApiPassword,
                        CountryId,
                        _webApiKey,
                        requestVersionKeyInfo.VersionKey));

                cancellationToken.ThrowIfCancellationRequested();

                var response = await client.doGetItemsInfoAsync(
                    new doGetItemsInfoRequest(
                        loginResponse.sessionHandlePart,
                        offerIds,
                        getDesc : includeDescription ? 1 : 0,               // description
                        getImageUrl : 0,
                        getAttribs : includeAttributes ? 1 : 0,             // attributes (including state)
                        getPostageOptions : includeDeliveryOptions ? 1 : 0, // delivery options
                        getCompanyInfo : 0,
                        getProductInfo : 0,
                        getAfterSalesServiceConditions : 0,
                        getEan : 0,
                        getAdditionalServicesGroup : 0));

                cancellationToken.ThrowIfCancellationRequested();

                return(response);
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                if (ex.Message?.StartsWith("Niepoprawna wersja", StringComparison.OrdinalIgnoreCase) == true)
                {
                    // most likely version key is invalidated
                    lock (_versionKeyLocker)
                    {
                        // if it's first request with invalidated version key
                        if (_versionKeyInfo != null &&
                            _versionKeyInfo.IssuedOn == requestVersionKeyInfo.IssuedOn)
                        {
                            // cause version key refresh on the next request
                            _versionKeyInfo = null;
                        }
                    }
                }

                throw new AllegroPlRequestException("Request to WebApi failed.", ex);
            }
        }
Пример #2
0
        private async Task <TData> SendPostRequestAsync <TData>(
            string actionPath,
            object request,
            CancellationToken cancellationToken)
            where TData : class, new()
        {
            Assure.ArgumentNotNull(actionPath, nameof(actionPath));
            if (!actionPath.StartsWith("/"))
            {
                actionPath = "/" + actionPath;
            }

            // request new integration log manager
            var integrationLogManager = _serviceProvider.GetRequiredService <IIntegrationLogManager>();

            integrationLogManager.StartNewLogRecord(ExternalSystems.EK, IntegrationRequestDirectionEnum.FromKioskBrainsServer);
            integrationLogManager.LogToRequest("Request", $"POST {actionPath}");

            try
            {
                string responseBody;
                try
                {
                    var requestJson = JsonConvert.SerializeObject(request);

                    integrationLogManager.LogToRequest("Body", requestJson);

                    using (var httpClient = new HttpClient())
                    {
                        httpClient.DefaultRequestHeaders.Add("X-API-KEY", "KWLG@10213FKWll@)=!kkf!_dfWN");
                        var httpResponse = await httpClient.PostAsync(
                            new Uri(_settings.ApiUrl + actionPath),
                            new StringContent(requestJson, Encoding.UTF8, "application/json"),
                            cancellationToken);

                        responseBody = await httpResponse.Content.ReadAsStringAsync();

                        integrationLogManager.LogToResponse("StatusCode", ((int)httpResponse.StatusCode).ToString());
                        integrationLogManager.LogToResponse("Body", responseBody);

                        if (!httpResponse.IsSuccessStatusCode)
                        {
                            throw new Ek4CarRequestException($"Request to API failed, response code {(int)httpResponse.StatusCode}, body: {responseBody}");
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (Ek4CarRequestException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    throw new Ek4CarRequestException("Request to API failed, no response.", ex);
                }

                ResponseWrapper <TData> response;
                try
                {
                    response = JsonConvert.DeserializeObject <ResponseWrapper <TData> >(responseBody);
                }
                catch (Exception ex)
                {
                    throw new Ek4CarRequestException("Bad format of API response.", ex);
                }

                if (response == null)
                {
                    throw new Ek4CarRequestException("API response is null.");
                }

                if (!response.Success)
                {
                    throw new Ek4CarRequestException($"API request failed, error: '{response.Error?.Message}'.");
                }

                await integrationLogManager.CompleteLogRecordAsync();

                return(response.Data);
            }
            catch (OperationCanceledException)
            {
                // cancelled - do not save log record

                throw;
            }
            catch (Exception ex)
            {
                integrationLogManager.LogToResponse("Error", ex);

                await integrationLogManager.CompleteLogRecordAsync();

                throw;
            }
        }
Пример #3
0
        public static Task DeleteFileAsync(string filePath)
        {
            Assure.ArgumentNotNull(filePath, nameof(filePath));

            return(Task.Run(() => File.Delete(filePath)));
        }
Пример #4
0
        public static void AddKioskBrainsApplication(
            this IServiceCollection services,
            WafHostEnum wafHost,
            IConfiguration configuration)
        {
            Assure.ArgumentNotNull(configuration, nameof(configuration));

            JsonDefaultSettings.Initialize();

            // Settings
            services.Configure <EkSearchSettings>(configuration.GetSection("EkSearchSettings"));

            // Memory Cache
            services.AddMemoryCache();

            // Persistent Cache
            services.AddScoped <IPersistentCache, DbPersistentCache>();

            // DB Context
            services.AddDbContextPool <KioskBrainsContext>(options =>
                                                           options
                                                           .UseSqlServer(configuration.GetConnectionString("KioskBrainsContext"))
                                                           .ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning)));

            if (wafHost == WafHostEnum.Web)
            {
                // Authentication
                services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidIssuer    = JwtAuthOptions.Issuer,

                        ValidateAudience = true,
                        ValidAudience    = JwtAuthOptions.Audience,

                        ValidateLifetime = true,

                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey         = JwtAuthOptions.GetSymmetricSecurityKey(),
                    };
                });

                // Add CurrentUser
                services.AddCurrentUser();
            }

            // WAF
            services.AddWaf(
                wafHost,
                appActionAssemblyNames: AppActionAssemblyNames,
                appManagerAssemblyNames: AppActionAssemblyNames);

            // Integration Log
            services.AddTransient <IIntegrationLogManager, IntegrationLogManager>();

            // Notifications
            services.Configure <NotificationManagerSettings>(configuration.GetSection("NotificationManagerSettings"));
            services.AddScoped <INotificationManager, NotificationManager>();

            //Repo and services
            services.AddScoped <ITranslateService, TranslateService>();

            services.AddScoped <IReadOnlyRepository, ReadOnlyRepository <KioskBrainsContext> >();
            services.AddScoped <IWriteOnlyRepository, WriteOnlyRepository <KioskBrainsContext> >();

            // Common Clients
            services.Configure <KioskProxyClientSettings>(configuration.GetSection("KioskProxyClientSettings"));
            services.AddScoped <KioskProxyClient>();
            services.Configure <AzureStorageSettings>(configuration.GetSection("AzureStorageSettings"));
            services.AddScoped <AzureStorageClient>();
        }
Пример #5
0
        public SocketIoPortProvider(SocketSettings socketSettings)
        {
            Assure.ArgumentNotNull(socketSettings, nameof(socketSettings));

            _socketSettings = socketSettings;
        }
Пример #6
0
        public async Task <Models.SearchOffersResponse> SearchOffersAsync(
            string phrase,
            string categoryId,
            OfferStateEnum state,
            OfferSortingEnum sorting,
            int offset,
            int limit,
            CancellationToken cancellationToken)
        {
            Assure.ArgumentNotNull(categoryId, nameof(categoryId));

            var parameters = new Dictionary <string, string>
            {
                ["searchMode"]         = "REGULAR", // by title only
                ["category.id"]        = categoryId,
                ["sellingMode.format"] = "BUY_NOW", // exclude auctions (sellingMode.format=AUCTION)
            };

            if (!string.IsNullOrEmpty(phrase))
            {
                parameters["phrase"] = phrase;
            }

            if (state != OfferStateEnum.All)
            {
                string stateFilterValue;
                switch (state)
                {
                case OfferStateEnum.New:
                    stateFilterValue = "11323_1";
                    break;

                case OfferStateEnum.Used:
                    stateFilterValue = "11323_2";
                    break;

                case OfferStateEnum.Recovered:
                    stateFilterValue = "11323_246462";
                    break;

                case OfferStateEnum.Broken:
                    stateFilterValue = "11323_238062";
                    break;

                default:
                    stateFilterValue = null;
                    break;
                }

                parameters[StateFilterId] = stateFilterValue;
            }

            string sortingValue;

            switch (sorting)
            {
            case OfferSortingEnum.Relevance:
                sortingValue = "-relevance";
                break;

            case OfferSortingEnum.PriceAsc:
                sortingValue = "price";
                break;

            case OfferSortingEnum.PriceDesc:
                sortingValue = "-price";
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(sorting), sorting, null);
            }

            parameters["sort"] = sortingValue;

            parameters["offset"] = offset.ToString();
            parameters["limit"]  = limit.ToString();

            var action   = "/offers/listing";
            var response = await GetAsync <Models.SearchOffersResponse>(action, parameters, cancellationToken);

            if (response.Items == null ||
                response.SearchMeta == null)
            {
                throw new AllegroPlRequestException($"Request to API failed, action {action}, {nameof(response.Items)} or {nameof(response.SearchMeta)} is null.");
            }

            return(response);
        }
Пример #7
0
        private ComponentBase CreateComponentInstance(ComponentConfiguration componentConfiguration)
        {
            try
            {
                Assure.ArgumentNotNull(componentConfiguration, nameof(componentConfiguration));
                Assure.ArgumentNotNull(componentConfiguration.ComponentName, nameof(componentConfiguration.ComponentName));
                Assure.ArgumentNotNull(componentConfiguration.ComponentRole, nameof(componentConfiguration.ComponentRole));
                Assure.CheckFlowState(_supportedComponentTypes != null, $"{nameof(ComponentManager)} is not initialized.");

                // ReSharper disable PossibleNullReferenceException
                var componentTypeNames = _supportedComponentTypes.Keys
                                         // ReSharper restore PossibleNullReferenceException
                                         .Where(x => x.EndsWith(componentConfiguration.ComponentName))
                                         .ToArray();
                if (componentTypeNames.Length > 1)
                {
                    throw new ComponentConfigurationException($"More than 1 app component type matches to component name '{componentConfiguration.ComponentName}': {string.Join(", ", componentTypeNames)}.");
                }

                if (componentTypeNames.Length == 0)
                {
                    throw new ComponentConfigurationException($"There is no app component type that matches to component name '{componentConfiguration.ComponentName}'.");
                }

                var    componentType = _supportedComponentTypes[componentTypeNames[0]];
                object componentInstance;
                try
                {
                    componentInstance = Activator.CreateInstance(componentType);
                }
                catch (Exception ex)
                {
                    throw new ComponentConfigurationException($"Instantiation of '{componentType.FullName}' failed with '{ex.Message}'.");
                }

                if (!(componentInstance is ComponentBase typedComponentInstance))
                {
                    throw new ComponentConfigurationException($"Component type '{componentType.FullName}' doesn't inherit {nameof(ComponentBase)}.");
                }

                var contractStateType = typeof(ComponentState);
                // get all properties including private and explicit interface implementations
                // it's done on component level since it's much simpler than to check an hierarchy of contact interfaces
                // TBD: move all checks to contract registration - check entire hierarchy of contact interfaces
                var componentProperties = componentType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                foreach (var componentProperty in componentProperties)
                {
                    var isOperationOrState = false;
                    // check if operation property
                    if (componentProperty.PropertyType.IsConstructedGenericType &&
                        componentProperty.PropertyType.GetGenericTypeDefinition() == typeof(ComponentOperation <,>))
                    {
                        isOperationOrState = true;
                        var operationValue = componentProperty.GetValue(typedComponentInstance);
                        if (operationValue == null)
                        {
                            throw new ComponentConfigurationException($"Component operation '{componentType.FullName}'.{componentProperty.Name} is null after instantiation.");
                        }
                    }

                    // check if state property
                    if (contractStateType.IsAssignableFrom(componentProperty.PropertyType))
                    {
                        isOperationOrState = true;
                        var contractStateValue = componentProperty.GetValue(typedComponentInstance);
                        if (contractStateValue == null)
                        {
                            throw new ComponentConfigurationException($"Component contract state '{componentType.FullName}'.{componentProperty.Name} is null after instantiation.");
                        }

                        var statePropertyName = componentProperty.Name;
                        if (statePropertyName != ContractStatePropertyName
                            // for explicit contract implementations
                            && !statePropertyName.EndsWith("." + ContractStatePropertyName))
                        {
                            throw new ComponentConfigurationException($"Component contract state '{componentType.FullName}'.{componentProperty.Name} is not named '{ContractStatePropertyName}' (required by convention).");
                        }
                    }

                    if (isOperationOrState)
                    {
                        if (componentProperty.CanWrite)
                        {
                            throw new ComponentConfigurationException($"Component operation/state '{componentType.FullName}'.{componentProperty.Name} must be readonly.");
                        }
                    }
                }

                typedComponentInstance.ComponentRole = componentConfiguration.ComponentRole;
                typedComponentInstance.ComponentName = componentConfiguration.ComponentName;
                return(typedComponentInstance);
            }
            catch (Exception ex)
            {
                Log.Error(LogContextEnum.Configuration, $"Component '{componentConfiguration?.ComponentRole} ({componentConfiguration?.ComponentName})' instantiation failed.", ex);
                return(null);
            }
        }
Пример #8
0
        public SocketIoPort(StreamSocket socket)
        {
            Assure.ArgumentNotNull(socket, nameof(socket));

            _socket = socket;
        }
Пример #9
0
        internal ComponentLock(Action componentLockReleaseAction)
        {
            Assure.ArgumentNotNull(componentLockReleaseAction, nameof(componentLockReleaseAction));

            _componentLockReleaseAction = componentLockReleaseAction;
        }
Пример #10
0
 public YandexTranslateClient(IOptions <YandexTranslateClientSettings> settings)
 {
     _settings = settings.Value;
     Assure.ArgumentNotNull(_settings, nameof(_settings));
 }