public List <MenuItem> SortShopMenuByCategories(List <string> comingCategories, out DefaultError outError)
        {
            outError = new DefaultError();
            List <MenuItem> result     = new List <MenuItem>();
            List <MenuItem> menuItems  = GetShopMenu(out DefaultError error);
            List <int>      categories = ConverComingCategories(comingCategories);

            if (menuItems == null)
            {
                outError.ErrorMessage = error.ErrorMessage;
                return(new List <MenuItem>());
            }
            if (categories == null)
            {
                outError.ErrorMessage = "Ошибка сортировки меню";
                return(new List <MenuItem>());
            }
            foreach (MenuItem menuItem in menuItems)
            {
                if (categories.Contains((int)menuItem.Product.ProductType))
                {
                    result.Add(menuItem);
                }
                else
                {
                    continue;
                }
            }
            return(result);
        }
 public void EditClient(AddEditClient clientFromView, out DefaultError outError)
 {
     if (CheckClient(clientFromView, out outError))
     {
         ClientsRepository.EditClient(SetClientData(clientFromView));
     }
 }
 internal IdSiteRuntimeException(DefaultError error)
     : base(error)
 {
     if (!Supports(error))
     {
         throw new ArgumentException("Error type not supported; must be one of: " + string.Join(",", SupportedErrors));
     }
 }
 public void DelClient(string clientId, out DefaultError outError)
 {
     outError = new DefaultError();
     if (ClientsRepository.GetClientById(clientId) == null)
     {
         outError.ErrorMessage = "Ошибка удаления. Клиент отсутствует в базе!";
         return;
     }
     ClientsRepository.DelClient(clientId);
 }
Esempio n. 5
0
 public void DelProduct(string id, out DefaultError outError)
 {
     outError = new DefaultError();
     if (ProductRepository.GetProductById(id) == null)
     {
         outError.ErrorMessage = "Ошибка удаления! Товар отсутствует в базе данных!";
         return;
     }
     ProductRepository.DelProduct(id);
 }
        public List <Client> GetAllClients(out DefaultError outError)
        {
            outError = new DefaultError();
            List <Client> result = ConvertDbClientListToClientList(ClientsRepository.GetAllClients());

            if (result == null || !result.Any())
            {
                outError.ErrorMessage = "Список клиентов пуст!";
                return(new List <Client>());
            }
            return(result);
        }
Esempio n. 7
0
        public List <Product> GetAllProducts(out DefaultError outError)
        {
            outError = new DefaultError();
            List <Product> result = ConvertDbProductListToProductList(ProductRepository.GetAllProducts());

            if (result == null || !result.Any())
            {
                outError.ErrorMessage = "Список продуктов пуст!!!";
            }

            return(result);
        }
        private bool CheckClient(AddEditClient clientFromView, out DefaultError outError)
        {
            outError = new DefaultError();
            if (!String.IsNullOrEmpty(outError.ErrorMessage = CheckClientNull(clientFromView)))
            {
                return(false);
            }

            if (!String.IsNullOrEmpty(outError.ErrorMessage = CheckClientData(clientFromView)))
            {
                return(false);
            }

            return(true);
        }
        public List <MenuItem> GetShopMenu(out DefaultError outError)
        {
            List <MenuItem> shopMenu = new List <MenuItem>();

            outError = new DefaultError();
            List <DbMenuItem> dbShopMenu      = ShopMenuRepository.GetDbShopMenu();
            List <Product>    shopMenuProduct = productServices.GetProductsByIdList(GetMenuItemsIdList(dbShopMenu));

            shopMenu = SetShopMenu(dbShopMenu, shopMenuProduct);
            if (shopMenu == null || !shopMenu.Any())
            {
                outError.ErrorMessage = "Ошибка формирования меню";
                return(new List <MenuItem>());
            }
            return(shopMenu);
        }
Esempio n. 10
0
        public void AddProduct(AddEditProduct newProductFromView, out DefaultError outError)
        {
            outError = new DefaultError();

            if (!String.IsNullOrEmpty(outError.ErrorMessage = CheckProductNullFromView(newProductFromView)))
            {
                return;
            }

            if (!String.IsNullOrEmpty(outError.ErrorMessage = CheckProductDataFromView(newProductFromView)))
            {
                return;
            }

            ProductRepository.AddProductInBD(SetProductData(newProductFromView));
        }
Esempio n. 11
0
        private IHttpResponse HandleResponseOrError(IHttpResponse response)
        {
            if (response.TransportError ||
                response.IsClientError() ||
                response.IsServerError())
            {
                DefaultError error = null;
                error = response.HasBody
                    ? new DefaultError(this.GetBody <IError>(response))
                    : DefaultError.FromHttpResponse(response);

                throw new ResourceException(error);
            }

            return(response);
        }
        public List <Client> SearchClientsByEmail(string email, out DefaultError outError)
        {
            outError = new DefaultError();
            if (String.IsNullOrWhiteSpace(email))
            {
                outError.ErrorMessage = "Ошибка ввода. Пустое значение.";
                return(new List <Client>());
            }
            List <Client> result = ConvertDbClientListToClientList(ClientsRepository.SearchClientsByEmail(email));

            if (!result.Any())
            {
                outError.ErrorMessage = "Клиентов с введенным E-mail не найдено!";
                return(new List <Client>());
            }
            return(result);
        }
Esempio n. 13
0
        public List <Product> GetProductsByName(string name, out DefaultError outError)
        {
            outError = new DefaultError();
            if (name == null)
            {
                outError.ErrorMessage = "Ошибка ввода названия. Пустое значение!";
                return(new List <Product>());
            }
            List <Product> result = ConvertDbProductListToProductList(ProductRepository.GetProductsByName(name));

            if (result == null || !result.Any())
            {
                outError.ErrorMessage = "Продукт с данным название отсутствует!";
                return(new List <Product>());
            }
            return(result);
        }
        public List <Client> SearchClientsByLastName(string lastName, out DefaultError outError)
        {
            outError = new DefaultError();
            if (String.IsNullOrWhiteSpace(lastName))
            {
                outError.ErrorMessage = "Ошибка ввода. Пустое значение.";
                return(new List <Client>());
            }
            List <Client> result = ConvertDbClientListToClientList(ClientsRepository.GetClientsByLastName(lastName));

            if (!result.Any())
            {
                outError.ErrorMessage = "Клиентов с введенной фамилией не найдено!";
                return(new List <Client>());
            }
            return(result);
        }
Esempio n. 15
0
        public void EditProduct(AddEditProduct productFromView, out DefaultError outError)
        {
            outError = new DefaultError();

            if (!String.IsNullOrEmpty(outError.ErrorMessage = CheckProductNullFromView(productFromView)))
            {
                return;
            }

            if (ProductRepository.GetProductById(productFromView.ProductId) == null)
            {
                outError.ErrorMessage = "Продукт с таким Id отсутствует в базе!";
                return;
            }
            if (!String.IsNullOrEmpty(outError.ErrorMessage = CheckProductDataFromView(productFromView)))
            {
                return;
            }

            ProductRepository.EditProduct(SetProductData(productFromView));
        }
Esempio n. 16
0
        public static string UploadImg(HttpRequestBase Requst, string modelType, out DefaultError outError)
        {
            outError = new DefaultError();
            string resultImageRes = "";

            foreach (string file in Requst.Files)
            {
                var upload = Requst.Files[file];
                if (upload != null)
                {
                    string fileName = modelType + "_" + GeneratorId.GenerateId() + ".jpg";   /*Path.GetFileName(upload.FileName) Если нужно имя файла*/
                    upload.SaveAs(HttpContext.Current.Server.MapPath("~/Files/" + fileName));
                    resultImageRes = fileName;
                }
                else
                {
                    outError.ErrorMessage = "Ошибка загрузки файла!";
                    return(resultImageRes);
                }
            }
            return(resultImageRes);
        }
Esempio n. 17
0
        public List <Product> GetProductsByCategory(string filter, out DefaultError outError)
        {
            outError = new DefaultError();
            int category = (int)CategoryConverter.RusStringToEnum(filter);

            if (category == 1)
            {
                return(GetAllProducts(out DefaultError error));
            }

            List <Product> result = ConvertDbProductListToProductList(ProductRepository.GetProductsByCategory(category));

            if (result == null)
            {
                outError.ErrorMessage = "Ошибка формирования результата фильтрации по категории!";
                return(new List <Product>());
            }
            if (!result.Any())
            {
                outError.ErrorMessage = "Нет продуктов в данной категории!";
                return(new List <Product>());
            }
            return(result);
        }
Esempio n. 18
0
 internal ResourceException(DefaultError error)
     : base(error.Message)
 {
     this.Error = error;
     this.constructedErrorMessage = BuildExceptionMessage(error);
 }
Esempio n. 19
0
        /// <summary>
        /// Gets a list of possible operations
        /// </summary>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="DefaultErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <IPage <Operation> > > ListWithHttpMessagesAsync(Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
            }
            // Construct URL
            var           _baseUrl         = Client.BaseUri.AbsoluteUri;
            var           _url             = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.WorkloadMonitor/operations").ToString();
            List <string> _queryParameters = new List <string>();

            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new DefaultErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    DefaultError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <DefaultError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <IPage <Operation> >();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Page <Operation> >(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Esempio n. 20
0
 internal InvalidIdSiteTokenException(DefaultError error)
     : base(error)
 {
 }
 internal IdSiteSessionTimeoutException(DefaultError error)
     : base(error)
 {
 }
Esempio n. 22
0
        private TReturned SaveCore <T, TReturned>(T resource, string href, QueryString queryParams, HttpHeaders headers, bool create)
            where T : class
            where TReturned : class
        {
            if (string.IsNullOrEmpty(href))
            {
                throw new ArgumentNullException(nameof(href));
            }

            var canonicalUri = new CanonicalUri(this.uriQualifier.EnsureFullyQualified(href), queryParams);

            this.logger.Trace($"Synchronously saving resource of type {typeof(T).Name} to {canonicalUri.ToString()}", "DefaultDataStore.SaveCore");

            ISynchronousFilterChain chain = new DefaultSynchronousFilterChain(this.defaultSyncFilters as DefaultSynchronousFilterChain)
                                            .Add(new DefaultSynchronousFilter((req, next, logger) =>
            {
                bool contentTypeIsPresent = !string.IsNullOrEmpty(req.Headers?.ContentType);

                bool contentTypeIsFormUrlEncoded =
                    contentTypeIsPresent &&
                    string.Equals(req.Headers.ContentType, HttpHeaders.MediaTypeApplicationFormUrlEncoded, StringComparison.OrdinalIgnoreCase);

                string postBody = contentTypeIsFormUrlEncoded
                        ? new FormUrlEncoder(req.Properties).ToString()
                        : this.serializer.Serialize(req.Properties);

                var httpRequest = new DefaultHttpRequest(
                    HttpMethod.Post,
                    req.Uri,
                    queryParams: null,
                    headers: req.Headers,
                    body: postBody,
                    bodyContentType: contentTypeIsPresent ? req.Headers.ContentType : DefaultContentType);

                var response       = this.Execute(httpRequest);
                var responseBody   = this.GetBody <T>(response);
                var responseAction = this.GetPostAction(req, response);

                bool responseHasData      = responseBody.Any();
                bool responseIsProcessing = response.StatusCode == 202;
                bool responseOkay         = responseHasData || responseIsProcessing;

                if (!responseOkay)
                {
                    throw new ResourceException(DefaultError.WithMessage("Unable to obtain resource data from the API server."));
                }

                if (responseIsProcessing)
                {
                    this.logger.Warn($"Received a 202 response, returning empty result. Href: '{canonicalUri.ToString()}'", "DefaultDataStore.SaveCoreAsync");
                }

                return(new DefaultResourceDataResult(responseAction, typeof(TReturned), req.Uri, response.StatusCode, responseBody));
            }));

            Map propertiesMap = null;

            var abstractResource = resource as AbstractResource;

            if (abstractResource != null)
            {
                // Serialize properties
                propertiesMap = this.resourceConverter.ToMap(abstractResource);

                var  extendableInstanceResource = abstractResource as AbstractExtendableInstanceResource;
                bool includesCustomData         = extendableInstanceResource != null;
                if (includesCustomData)
                {
                    var customDataProxy = (extendableInstanceResource as IExtendableSync).CustomData as DefaultCustomDataProxy;

                    // Apply custom data deletes
                    if (customDataProxy.HasDeletedProperties())
                    {
                        if (customDataProxy.DeleteAll)
                        {
                            this.DeleteCore <ICustomData>(extendableInstanceResource.CustomData.Href);
                        }
                        else
                        {
                            customDataProxy.DeleteRemovedCustomDataProperties(extendableInstanceResource.CustomData.Href);
                        }
                    }

                    // Merge in custom data updates
                    if (customDataProxy.HasUpdatedCustomDataProperties())
                    {
                        propertiesMap["customData"] = customDataProxy.UpdatedCustomDataProperties;
                    }

                    // Remove custom data updates from proxy
                    extendableInstanceResource.ResetCustomData();
                }
            }

            // In some cases, all we need to save are custom data property deletions, which is taken care of above.
            // So, we should just refresh with the latest data from the server.
            // This doesn't apply to CREATEs, though, because sometimes we need to POST a null body.
            bool nothingToPost = propertiesMap.IsNullOrEmpty();

            if (!create && nothingToPost)
            {
                return(this.AsSyncInterface.GetResource <TReturned>(canonicalUri.ToString()));
            }

            var requestAction = create
                ? ResourceAction.Create
                : ResourceAction.Update;
            var request = new DefaultResourceDataRequest(requestAction, typeof(T), canonicalUri, headers, propertiesMap, false);

            var result = chain.Filter(request, this.logger);

            return(this.resourceFactory.Create <TReturned>(result.Body, resource as ILinkable));
        }