public async Task <IActionResult> MigrateEnvironment([FromBody] ODataActionParameters value) { if (!this.ModelState.IsValid || value == null) { return(new BadRequestObjectResult(this.ModelState)); } if (!value.ContainsKey("sourceName") || string.IsNullOrEmpty(value["sourceName"]?.ToString())) { return(new BadRequestObjectResult(value)); } var sourceName = value["sourceName"]?.ToString(); if (!value.ContainsKey("newName") || string.IsNullOrEmpty(value["newName"]?.ToString())) { return(new BadRequestObjectResult(value)); } var newName = value["newName"]?.ToString(); var newArtifactStoreId = value["newArtifactStoreId"]?.ToString(); Guid id; if (string.IsNullOrEmpty(newArtifactStoreId)) { id = Guid.NewGuid(); } else if (!Guid.TryParse(newArtifactStoreId, out id)) { return(new BadRequestObjectResult(newArtifactStoreId)); } this.CurrentContext.AddModel(new ArtifactStore(id.ToString("N", System.Globalization.CultureInfo.InvariantCulture))); var command = this.Command <MigrateEnvironmentCommand>(); await command.Process(this.CurrentContext, sourceName, newName, id).ConfigureAwait(false); return(new ObjectResult(command)); }
public void Can_DeserializePayload_WithPrimitiveParameters(string actionName, IEdmAction expectedAction, ODataPath path) { // Arrange const int Quantity = 1; const string ProductCode = "PCode"; string body = "{" + string.Format(@" ""Quantity"": {0} , ""ProductCode"": ""{1}"" , ""Birthday"": ""2015-02-27"", ""BkgColor"": ""Red"", ""InnerColor"": null", Quantity, ProductCode) + "}"; ODataMessageWrapper message = new ODataMessageWrapper(GetStringAsStream(body)); message.SetHeader("Content-Type", "application/json"); ODataMessageReader reader = new ODataMessageReader(message as IODataRequestMessage, new ODataMessageReaderSettings(), _model); ODataDeserializerContext context = new ODataDeserializerContext() { Path = path, Model = _model }; // Act ODataActionParameters payload = _deserializer.Read(reader, typeof(ODataActionParameters), context) as ODataActionParameters; IEdmAction action = ODataActionPayloadDeserializer.GetAction(context); // Assert Assert.Same(expectedAction, action); Assert.NotNull(payload); Assert.True(payload.ContainsKey("Quantity")); Assert.Equal(Quantity, payload["Quantity"]); Assert.True(payload.ContainsKey("ProductCode")); Assert.Equal(ProductCode, payload["ProductCode"]); Assert.True(payload.ContainsKey("Birthday")); Assert.Equal(new Date(2015, 2, 27), payload["Birthday"]); Assert.True(payload.ContainsKey("BkgColor")); AColor bkgColor = Assert.IsType <AColor>(payload["BkgColor"]); Assert.Equal(AColor.Red, bkgColor); Assert.True(payload.ContainsKey("InnerColor")); Assert.Null(payload["InnerColor"]); }
public void RejectVacation([FromODataUri] int key, ODataActionParameters parameters) { var vacationRequest = _vacationRequestRepository.Get(key); vacationRequest.Status = VacationRequestStatus.Denied; _vacationRequestRepository.Update(vacationRequest); string reason = parameters.ContainsKey("Reason") ? parameters["Reason"].ToString() : string.Empty; _vacationNotificationService.NotifyStatusChange(vacationRequest, reason); }
public async Task <IActionResult> GetGiftCards([FromBody] ODataActionParameters parameters) { if (!parameters.ContainsKey("startDate")) { parameters.Add("startDate", RequiredErrorMessage); return(new BadRequestObjectResult(parameters)); } if (!parameters.ContainsKey("endDate")) { parameters.Add("endDate", RequiredErrorMessage); return(new BadRequestObjectResult(parameters)); } var startDate = (DateTimeOffset)parameters["startDate"]; var endDate = (DateTimeOffset)parameters["endDate"]; var result = await Command <GetGiftCardsCommand>().Process(CurrentContext, startDate, endDate); return(new ObjectResult(result)); }
public IActionResult ImportCsvProducts([FromBody] ODataActionParameters value) { if (!ModelState.IsValid || value == null) { return(new BadRequestObjectResult(ModelState)); } if (!value.ContainsKey("importFile")) { return(new BadRequestObjectResult(value)); } if (!(value["importFile"] is FormFile formFile)) { return(new BadRequestObjectResult("Import file not correct type")); } var memoryStream = new MemoryStream(); formFile.CopyTo(memoryStream); var file = new FormFile(memoryStream, 0L, formFile.Length, formFile.Name, formFile.FileName); var updateMode = value["mode"].ToString(); var errorThreshold = 100; if (value.ContainsKey("errorThreshold")) { errorThreshold = int.Parse(value["errorThreshold"].ToString()); } var publishEntities = true; if (value.ContainsKey("publish") && bool.TryParse(value["publish"].ToString(), out var result)) { publishEntities = result; } return(new ObjectResult(ExecuteLongRunningCommand(() => Command <ImportCsvProductsCommand>().Process(CurrentContext, file, updateMode, errorThreshold, publishEntities)))); }
public async Task <IActionResult> SetCartLineProperties([FromBody] ODataActionParameters value) { if (!this.ModelState.IsValid) { return((IActionResult) new BadRequestObjectResult(this.ModelState)); } if (!value.ContainsKey(Constants.Settings.CartId)) { return((IActionResult) new BadRequestObjectResult((object)value)); } var id = value[Constants.Settings.CartId]; if (string.IsNullOrEmpty(id?.ToString())) { return((IActionResult) new BadRequestObjectResult((object)value)); } var cartId = id.ToString(); var cartLineProperties = new CartLineProperties(); if (value.ContainsKey(Constants.Settings.CartLineProperties)) { var cartlinePropObj = value[Constants.Settings.CartLineProperties]; if (!string.IsNullOrEmpty(cartLineProperties?.ToString())) { cartLineProperties = JsonConvert.DeserializeObject <CartLineProperties>(cartlinePropObj.ToString()); } } var command = this.Command <SetCartLinePropertiesCommand>(); await Task.Delay(1); var runCommand = await command.Process(this.CurrentContext, cartId, cartLineProperties, $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}"); return((IActionResult) new ObjectResult((object)runCommand)); }
public async Task <IActionResult> GetOrdernumberForCart([FromBody] ODataActionParameters value) { if (!value.ContainsKey("cartId")) { return(new BadRequestObjectResult(value)); } var cartId = (string)value["cartId"]; var ordernumber = await Command <AssignOrdernumberCommand>().Process(CurrentContext, cartId).ConfigureAwait(false); return(new ObjectResult(ordernumber)); }
public async Task <IActionResult> GetDeliveryTime([FromBody] ODataActionParameters value) { if (!this.ModelState.IsValid) { return(new BadRequestObjectResult(this.ModelState)); } if (!value.ContainsKey("itemIds") || (value["itemIds"] as JArray) == null || !value.ContainsKey("primaryInventorySetId") || (value["primaryInventorySetId"] as string) == null || !value.ContainsKey("secondaryInventorySetId") || (value["secondaryInventorySetId"] as string) == null) { return(new BadRequestObjectResult(value)); } var itemIds = (JArray)value["itemIds"]; var primaryInventorySetId = value["primaryInventorySetId"] as string; var secondaryInventorySetId = value["secondaryInventorySetId"] as string; var result = await Command <GetDeliveryTimeCommand>().Process(CurrentContext, itemIds?.ToObject <IEnumerable <string> >(), primaryInventorySetId, secondaryInventorySetId).ConfigureAwait(false); return(new ObjectResult(result)); }
public ActionResult GetPermissions(ODataActionParameters parameters) { ActionResult result = NoContent(); if (parameters.ContainsKey("keys") && parameters.ContainsKey("typeName")) { List <string> keys = new List <string>(parameters["keys"] as IEnumerable <string>); string typeName = parameters["typeName"].ToString(); ITypeInfo typeInfo = ObjectSpace.TypesInfo.PersistentTypes.FirstOrDefault(t => t.Name == typeName); if (typeInfo != null) { IList entityList = ObjectSpace.GetObjects(typeInfo.Type, new InOperator(typeInfo.KeyMember.Name, keys)); List <ObjectPermission> objectPermissions = new List <ObjectPermission>(); foreach (object entity in entityList) { ObjectPermission objectPermission = CreateObjectPermission(typeInfo, entity); objectPermissions.Add(objectPermission); } result = Ok(objectPermissions); } } return(result); }
public async Task <IActionResult> ExportPriceBooks([FromBody] ODataActionParameters value) { Condition.Requires(value, nameof(value)).IsNotNull(); string fileName = value["fileName"].ToString(); string mode = value["mode"].ToString(); int maximumItemsPerFile = 500; if (value.ContainsKey("maximumItemsPerFile")) { maximumItemsPerFile = int.Parse(value["maximumItemsPerFile"].ToString()); } return(await Command <ExportPriceBooksCommand>().Process(this.CurrentContext, fileName, mode, maximumItemsPerFile)); }
public async Task <IActionResult> RunMinionNow([FromBody] ODataActionParameters value) { CommandsController commandsController = this; if (!commandsController.ModelState.IsValid || value == null) { return((IActionResult) new BadRequestObjectResult(commandsController.ModelState)); } if (value.ContainsKey("minionFullName") && value.ContainsKey("environmentName")) { var minionFullName = value["minionFullName"].ToString(); var environmentName = value["environmentName"].ToString(); if ((!string.IsNullOrEmpty(minionFullName != null ? minionFullName.ToString() : (string)null)) && (!string.IsNullOrEmpty(environmentName != null ? environmentName.ToString() : (string)null))) { List <Policy> policies = new List <Policy>(); RunMinionNowCommand command = commandsController.Command <RunMinionNowCommand>(); var resutlt = await command.Process(commandsController.CurrentContext, minionFullName, environmentName, policies); return((IActionResult) new ObjectResult((object)command)); } } return((IActionResult) new BadRequestObjectResult((object)value)); }
public async Task <IActionResult> UpdateCartLineGiftBox([FromBody] ODataActionParameters value) { if (!ModelState.IsValid) { return(new BadRequestObjectResult(ModelState)); } if (!value.ContainsKey(Actions.UpdateCartLineGiftBox.CartId) || string.IsNullOrEmpty(value[Actions.UpdateCartLineGiftBox.CartId].ToString()) || !value.ContainsKey(Actions.UpdateCartLineGiftBox.CartLineId) || string.IsNullOrEmpty(value[Actions.UpdateCartLineGiftBox.CartLineId].ToString()) || !value.ContainsKey(Actions.UpdateCartLineGiftBox.IsGiftBox)) { return(new BadRequestObjectResult(value)); } var cartId = value[Actions.UpdateCartLineGiftBox.CartId].ToString(); var cartLineId = value[Actions.UpdateCartLineGiftBox.CartLineId].ToString(); var isGiftBox = (bool)value[Actions.UpdateCartLineGiftBox.IsGiftBox]; var command = Command <UpdateCartLineGiftBoxCommand>(); var commandResult = await command.Process(CurrentContext, cartId, cartLineId, isGiftBox); return(new ObjectResult(command)); }
public async Task <IActionResult> RemoveWishlist([FromBody] ODataActionParameters value) { if (!value.ContainsKey(WishlistConstants.CUSTOMERID) || string.IsNullOrEmpty(value[WishlistConstants.CUSTOMERID]?.ToString())) { return(new BadRequestObjectResult(value)); } var customerId = value[WishlistConstants.CUSTOMERID].ToString(); string productId = value[WishlistConstants.PRODUCTID].ToString(); var removeWishlistCommand = this.Command <RemoveWishlistCommand>(); await removeWishlistCommand.Process(this.CurrentContext, customerId, productId); return(new ObjectResult(removeWishlistCommand)); }
public async Task <IActionResult> SendVote([FromODataUri] Guid key, ODataActionParameters parameters) { try { var currentUser = this.HttpContext.User; var apartmentIdClaim = currentUser.Claims.FirstOrDefault(x => x.Type == "apartment_id"); if (apartmentIdClaim == null || !Guid.TryParse(apartmentIdClaim.Value, out var apartmentId)) { return(this.BadRequest("Неизвестный пользователь.")); } var apartment = await this._apartmentService.GetApartmentByIdAsync(apartmentId); if (apartment == null) { return(this.BadRequest("Неизвестный пользователь.")); } var vote = await this._voteService.GetVoteByIdAsync(key); if (vote == null) { return(this.BadRequest("Голосование не найдено.")); } if (parameters == null || !parameters.ContainsKey("VariantId") || !Guid.TryParse(parameters["VariantId"].ToString(), out var variantId) || vote.Variants.All(x => x.Id != variantId)) { return(this.BadRequest("Выбранный ответ не найден.")); } if (vote.Variants.SelectMany(x => x.ApartmentVoteChoices).Any(x => x.ApartmentId == apartmentId)) { return(this.BadRequest("Вы уже приняли участие в этом голосовании.")); } await this._voteService.CreateVoteChoiseAsync(variantId, apartmentId, vote.UseVoteRate?apartment.VoteRate : (double?)null); return(this.NoContent()); } catch (Exception) { return(this.BadRequest("Произошла непредвиденная ошибка. Пожалуйста обратитесь к администратору.")); } }
public async Task <IActionResult> AddIngenicoPayment([FromBody] ODataActionParameters value) { CommandsController commandsController = this; if (!commandsController.ModelState.IsValid || value == null) { return((IActionResult) new BadRequestObjectResult(commandsController.ModelState)); } if (!value.ContainsKey("cartId") || value["cartId"] == null || !value.ContainsKey("payment") || value["payment"] == null) { return((IActionResult) new BadRequestObjectResult(value)); } string cartId = value["cartId"].ToString(); IngenicoPaymentComponent paymentComponent = JsonConvert.DeserializeObject <IngenicoPaymentComponent>(value["payment"].ToString()); AddPaymentsCommand command = commandsController.Command <AddPaymentsCommand>(); Cart cart = await command.Process(commandsController.CurrentContext, cartId, new List <PaymentComponent>() { paymentComponent }); return((IActionResult) new ObjectResult((object)command)); }
public async Task <IActionResult> GetNextCounterValue([FromBody] ODataActionParameters value) { if (!this.ModelState.IsValid) { return(new BadRequestObjectResult(this.ModelState)); } if (!value.ContainsKey("counterName")) { return(new BadRequestObjectResult(value)); } var counterName = (string)value["counterName"]; var result = await Command <GetNextValueCommand>().Process(CurrentContext, counterName).ConfigureAwait(false); return(new ObjectResult(result)); }
public async Task <IActionResult> RemoveWishListLine([FromBody] ODataActionParameters value) { if (!ModelState.IsValid || value == null) { return(new BadRequestObjectResult(ModelState)); } if (!value.ContainsKey("wishListId") || string.IsNullOrEmpty(value["wishListId"]?.ToString()) || !value.ContainsKey("wishListLineId") || string.IsNullOrEmpty(value["wishListLineId"]?.ToString())) { return(new BadRequestObjectResult(value)); } var wishListId = value["wishListId"].ToString(); var wishListLineId = value["wishListLineId"].ToString(); var command = Command <RemoveWishListLineCommand>(); var wishList = await command.Process(CurrentContext, wishListId, wishListLineId); return(new ObjectResult(command)); }
public async Task <IActionResult> ImportEntities([FromBody] ODataActionParameters request) { if (!this.ModelState.IsValid || request == null) { return((IActionResult) new BadRequestObjectResult(this.ModelState)); } if (!request.ContainsKey("importFile") || request["importFile"] == null) { return((IActionResult) new BadRequestObjectResult((object)request)); } IFormFile formFile = (IFormFile)request["importFile"]; MemoryStream memoryStream = new MemoryStream(); formFile.CopyTo((Stream)memoryStream); FormFile file = new FormFile((Stream)memoryStream, 0L, formFile.Length, formFile.Name, formFile.FileName); try { InitializeEnvironment(); var sb = new StringBuilder(); using (var reader = new StreamReader(file.OpenReadStream())) { while (reader.Peek() >= 0) { sb.AppendLine(reader.ReadLine()); } } var jsonString = sb.ToString(); var entities = JsonConvert.DeserializeObject <EntityCollectionModel>(jsonString, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }); var importEntitiesArgument = new ImportEntitiesArgument(entities); var command = this.Command <ImportCommerceEntitiesCommand>(); var result = await command.Process(this.CurrentContext, importEntitiesArgument); return((IActionResult) new ObjectResult((object)this.ExecuteLongRunningCommand(() => command.Process(this.CurrentContext, importEntitiesArgument)))); } catch (Exception ex) { return(new ObjectResult(ex)); } }
public virtual async Task <IActionResult> ComposerTemplatesByIds([FromBody] ODataActionParameters parameters) { ComposerTemplatesController composerTemplatesController = this; if (!composerTemplatesController.ModelState.IsValid) { return(new BadRequestObjectResult(Enumerable.Empty <ComposerTemplate>())); } if (!parameters.ContainsKey("rawIds") || !(parameters["rawIds"] is JArray)) { return(new BadRequestObjectResult(Enumerable.Empty <ComposerTemplate>())); } var templateIds = (parameters["rawIds"] as JArray)?.ToObject <string[]>(); var composerTemplates = await composerTemplatesController.Command <GetComposerTemplatesCommand>().Process(composerTemplatesController.CurrentContext, templateIds).ConfigureAwait(false); return(new ObjectResult(composerTemplates)); }
public async Task <string> CreateOfflineOrder([FromBody] ODataActionParameters value) { var command = this.Command <CreateOfflineOrderCommand>(); if (!value.ContainsKey("Order")) { return("Bad Request, Cannot Find Order key"); } var inputArgs = JsonConvert.DeserializeObject <OfflineStoreOrderArgument>(value["Order"].ToString()); var storeName = Regex.Replace(inputArgs.StoreDetails.Name, "[^0-9a-zA-Z]+", ""); inputArgs.ShopName = storeName; var result = await command.Process(this.CurrentContext, inputArgs); return(JsonConvert.SerializeObject(result)); }
public IHttpActionResult RemoveUser([FromODataUri] int orgKey, ODataActionParameters parameters) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (parameters.ContainsKey("userId")) { var userId = (int)parameters["userId"]; var result = _organizationService.RemoveUser(orgKey, userId); return (result.Ok ? StatusCode(HttpStatusCode.NoContent) : FromOperationFailure(result.Error)); } return(BadRequest("No user ID specified")); }
public async Task <IActionResult> AddWishListLineItem([FromBody] ODataActionParameters value) { CommandsController commandsController = this; if (!commandsController.ModelState.IsValid || value == null) { return((IActionResult) new BadRequestObjectResult(commandsController.ModelState)); } if (value.ContainsKey("wishlistId")) { object obj1 = value["wishlistId"]; if (!string.IsNullOrEmpty(obj1 != null ? obj1.ToString() : (string)null) && value.ContainsKey("itemId")) { object obj2 = value["itemId"]; if (!string.IsNullOrEmpty(obj2 != null ? obj2.ToString() : (string)null) && value.ContainsKey("quantity")) { object obj3 = value["quantity"]; if (!string.IsNullOrEmpty(obj3 != null ? obj3.ToString() : (string)null)) { string cartId = value["wishlistId"].ToString(); string str = value["itemId"].ToString(); Decimal result; if (!Decimal.TryParse(value["quantity"].ToString(), out result)) { return((IActionResult) new BadRequestObjectResult((object)value)); } AddWishListLineItemCommand command = commandsController.Command <AddWishListLineItemCommand>(); CartLineComponent line = new CartLineComponent() { ItemId = str, Quantity = result }; Cart cart = await command.Process(commandsController.CurrentContext, cartId, line).ConfigureAwait(false); return((IActionResult) new ObjectResult((object)command)); } } } } return((IActionResult) new BadRequestObjectResult((object)value)); }
public IActionResult CalcByRatingAction(ODataActionParameters parameters) { if (parameters == null) { return(Ok($"In CalcByRating Action Null parameters")); } if (parameters.Count == 0) { return(Ok($"In CalcByRating Action Empty parameters")); } if (parameters.ContainsKey("order")) { return(Ok($"In CalcByRating Action order = {parameters["order"]}")); } else { return(Ok($"In CalcByRating Action without order value")); } }
public async Task Can_DeserializePayload_WithEntityCollectionParameters(IEdmAction expectedAction, ODataPath path) { // Arrange ODataMessageWrapper message = new ODataMessageWrapper(await GetStringAsStreamAsync(EntityCollectionPayload)); message.SetHeader("Content-Type", "application/json"); ODataMessageReader reader = new ODataMessageReader(message as IODataRequestMessage, new ODataMessageReaderSettings(), _model); ODataDeserializerContext context = new ODataDeserializerContext() { Path = path, Model = _model }; // Act ODataActionParameters payload = await _deserializer.ReadAsync(reader, typeof(ODataActionParameters), context) as ODataActionParameters; IEdmAction action = ODataActionPayloadDeserializer.GetAction(context); // Assert Assert.Same(expectedAction, action); Assert.NotNull(payload); Assert.True(payload.ContainsKey("Id")); Assert.Equal(1, payload["Id"]); IList <Customer> customers = (payload["Customers"] as IEnumerable <Customer>).ToList(); Assert.NotNull(customers); Assert.Equal(2, customers.Count); Customer customer = customers[0]; Assert.NotNull(customer); Assert.Equal(109, customer.Id); Assert.Equal("Avatar", customer.Name); customer = customers[1]; Assert.NotNull(customer); Assert.Equal(901, customer.Id); Assert.Equal("Robot", customer.Name); }
public async Task <IActionResult> TestSimulationSetup([FromBody] ODataActionParameters value) { if (!ModelState.IsValid || value == null) { return((IActionResult) new BadRequestObjectResult(this.ModelState)); } if (!value.ContainsKey("cartId")) { return((IActionResult) new BadRequestObjectResult((object)value)); } var cartId = value["cartId"].ToString(); var command = Command <TestSimulationCommand>(); var result = await command.Process(this.CurrentContext, cartId); if (result == null) { return((IActionResult) new BadRequestObjectResult($"Cart : {cartId} was not found.")); } return((IActionResult) new ObjectResult((object)command)); }
public async Task <IActionResult> SynchronizeCatalog([FromBody] ODataActionParameters value) { if (!ModelState.IsValid || value == null) { return(new BadRequestObjectResult(ModelState)); } if (!value.ContainsKey("catalogId")) { return(new BadRequestObjectResult(value)); } var catalogId = value["catalogId"].ToString(); if (string.IsNullOrWhiteSpace(catalogId)) { return(new BadRequestObjectResult(value)); } var command = Command <SynchronizeCatalogCommand>(); await command.Process(CurrentContext, catalogId); return(new ObjectResult(command)); }
public IActionResult UpsValidateAddress([FromBody] ODataActionParameters value) { if (!value.ContainsKey(Constants.Address.AddressLine1)) { return((IActionResult) new BadRequestObjectResult((object)value)); } if (!value.ContainsKey(Constants.Address.City)) { return((IActionResult) new BadRequestObjectResult((object)value)); } if (!value.ContainsKey(Constants.Address.State)) { return((IActionResult) new BadRequestObjectResult((object)value)); } if (!value.ContainsKey(Constants.Address.ZipCode)) { return((IActionResult) new BadRequestObjectResult((object)value)); } var inputAddress = new InputAddress { AddressLine1 = value[Constants.Address.AddressLine1].ToString(), City = value[Constants.Address.City].ToString(), State = value[Constants.Address.State].ToString(), ZipCode = value[Constants.Address.ZipCode].ToString(), CountryCode = "US", //value[Constants.Address.CountryCode].ToString(), AddressLine2 = value.ContainsKey(Constants.Address.AddressLine2) ? value[Constants.Address.AddressLine2].ToString() : string.Empty, ConsigneeName = value.ContainsKey(Constants.Address.ConsigneeName) ? value[Constants.Address.ConsigneeName].ToString() : Constants.Address.DefaultConsigneeName, BuildingName = value.ContainsKey(Constants.Address.BuildingName) ? value[Constants.Address.BuildingName].ToString() : Constants.Address.DefaultBuildingName }; var command = this.Command <UpsValidateAddressCommand>(); var result = command.Process(CurrentContext, inputAddress); return(new ObjectResult(result)); }
public IHttpActionResult Create(ODataActionParameters parameters) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } User user = null; if (parameters.ContainsKey("user")) { user = parameters["user"] as User; Validate(user); // this will set the ModelState if not valid - it doesn't http://stackoverflow.com/questions/39484185/model-validation-in-odatacontroller } var organizationId = 0; if (parameters.ContainsKey("organizationId")) { organizationId = (int)parameters["organizationId"]; } var sendMailOnCreation = false; if (parameters.ContainsKey("sendMailOnCreation")) { sendMailOnCreation = (bool)parameters["sendMailOnCreation"]; } if (user?.Email != null && EmailExists(user.Email)) { ModelState.AddModelError(nameof(user.Email), "Email is already in use."); } // user is being created as global admin if (user?.IsGlobalAdmin == true) { // only other global admins can create global admin users if (!AuthorizationContext.HasPermission(new AdministerGlobalPermission(GlobalPermission.GlobalAdmin))) { ModelState.AddModelError(nameof(user.IsGlobalAdmin), "You don't have permission to create a global admin user."); } } if (user?.HasStakeHolderAccess == true) { // only global admins can create stakeholder access if (!AuthorizationContext.HasPermission(new AdministerGlobalPermission(GlobalPermission.StakeHolderAccess))) { ModelState.AddModelError(nameof(user.HasStakeHolderAccess), "You don't have permission to issue stakeholder access."); } } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var createdUser = _userService.AddUser(user, sendMailOnCreation, organizationId); return(Created(createdUser)); }
private static void VerifyActionParameters(ODataActionParameters parameters) { Assert.True(parameters.ContainsKey("modifiedDate")); Assert.True(parameters.ContainsKey("modifiedTime")); Assert.True(parameters.ContainsKey("nullableModifiedDate")); Assert.True(parameters.ContainsKey("nullableModifiedTime")); Assert.True(parameters.ContainsKey("dates")); Assert.Equal(new Date(2015, 3, 1), parameters["modifiedDate"]); Assert.Equal(new TimeOfDay(1, 5, 6, 8), parameters["modifiedTime"]); Assert.Null(parameters["nullableModifiedDate"]); Assert.Null(parameters["nullableModifiedTime"]); IEnumerable<Date> dates = parameters["dates"] as IEnumerable<Date>; Assert.NotNull(dates); Assert.Equal(2, dates.Count()); }
public HttpResponseMessage ValidateXML(ODataActionParameters parameters) { if (!ModelState.IsValid || !parameters.ContainsKey("documentContent")) { throw new HttpResponseException(HttpStatusCode.BadRequest); } try { var data = (string)parameters["documentContent"]; XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(data); // TODO: Тук може да се прочете Header-a на заявлението и да се определи типа на заявлението (DocumentTypeURI) // Използвайки УРИ-то във валидацията още тук ще се връща съобщение, че не се потвърждава. // Ако няма Header ще се използва Namespace-a. string rootNamespaceURI = xmlDocument.DocumentElement.NamespaceURI; string documentName = xmlDocument.DocumentElement.Name; Regex rx = new Regex(@"[\d|\w]{1,4}-\d{4,6}$$"); string documentUri = rx.Match(rootNamespaceURI).ToString(); //string documentUri = "0009-000146"; string codeBase = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase; UriBuilder uri = new UriBuilder(codeBase);//remove "File:" prefix string uriPath = Uri.UnescapeDataString(uri.Path); string path = Path.GetDirectoryName(uriPath); string documentNamePrefix = documentUri.Length > 0 ? documentUri + "_" : ""; string documentFileName = documentNamePrefix + documentName + ".xsd"; //Uri documentXMLUri = new Uri(ConfigurationManager.AppSettings["XSDDirectoryPath"].ToString() + documentFileName); Uri documentXMLUri = new Uri(path + "\\" + documentFileName); EservicesXmlResolver xmlResolver = new EservicesXmlResolver(); using (var reader = new XmlTextReader((StringReader)xmlResolver.GetEntity(documentXMLUri, null, null))) { XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.XmlResolver = xmlResolver; schemaSet.Add(rootNamespaceURI, reader); schemaSet.Compile(); xmlDocument.Schemas.Add(schemaSet); xmlDocument.Validate(null); } return(new HttpResponseMessage(HttpStatusCode.OK)); } catch (XmlException) { throw new HttpResponseException( this.Request.CreateResponse( HttpStatusCode.OK, new ODataError { Message = "0006-000069: Невалидна структура на обекта съгласно XML дефиницията му, вписана в регистъра на информационните обекти.", MessageLanguage = "bg-BG", ErrorCode = "0006-000069" } ) ); } catch (XmlSchemaValidationException) { throw new HttpResponseException( this.Request.CreateResponse( HttpStatusCode.OK, new ODataError { Message = "0006-000069: Невалидна структура на обекта съгласно XML дефиницията му, вписана в регистъра на информационните обекти.", MessageLanguage = "bg-BG", ErrorCode = "0006-000069" } ) ); } catch (Exception) { throw new HttpResponseException(HttpStatusCode.InternalServerError); } }
public async Task<IHttpActionResult> ReportAbuse([FromODataUri] Guid key, ODataActionParameters parameters) { if (!ModelState.IsValid || !parameters.ContainsKey("report")) { return BadRequest(); } var report = (Report)parameters["report"]; var successfullyVoted = _commentsManager.ReportAbuse(report); if (successfullyVoted) { try { await _commentsManager.SaveChanges(); return StatusCode(HttpStatusCode.Accepted); } catch (DbUpdateConcurrencyException) { return BadRequest(); } } return StatusCode(HttpStatusCode.Forbidden); }
public async Task <IActionResult> CreateStoreInventory([FromBody] ODataActionParameters value) { if (!value.ContainsKey("Stores") || !(value["Stores"] is JArray)) { return((IActionResult) new BadRequestObjectResult((object)value)); } if (!value.ContainsKey("ProductsToAssociate") || !(value["ProductsToAssociate"] is JArray)) { return((IActionResult) new BadRequestObjectResult((object)value)); } JArray jarray = (JArray)value["Stores"]; JArray jarrayProducts = (JArray)value["ProductsToAssociate"]; var storeInfos = jarray != null?jarray.ToObject <IEnumerable <StoreDetailsModel> >() : (IEnumerable <StoreDetailsModel>)null; var productsToAssociate = jarrayProducts != null?jarrayProducts.ToObject <IEnumerable <string> >() : (IEnumerable <string>)null; string catalogName = null; // You need to have catalog mentioned if you are not providing a list of products to update inventory. if (productsToAssociate == null || string.IsNullOrEmpty(productsToAssociate.FirstOrDefault())) { if (!value.ContainsKey("Catalog")) { return((IActionResult) new BadRequestObjectResult((object)value)); } catalogName = Convert.ToString(value["Catalog"]); } List <CreateStoreInventorySetArgument> args = new List <CreateStoreInventorySetArgument>(); foreach (var store in storeInfos) { var storeName = Regex.Replace(store.StoreName, "[^0-9a-zA-Z]+", ""); CreateStoreInventorySetArgument arg = new CreateStoreInventorySetArgument(storeName, store.StoreName, store.StoreName); // Default to US if no country code provided if (string.IsNullOrEmpty(store.Country)) { store.Country = "US"; } arg.Address = store.Address; arg.City = store.City; arg.Abbreviation = store.Abbreviation; arg.State = store.State; arg.ZipCode = store.ZipCode; arg.Long = store.Long; arg.Lat = store.Lat; arg.StoreName = store.StoreName; arg.CountryCode = store.Country; args.Add(arg); } var command = this.Command <CreateStoreInventoryCommand>(); var result = await command.Process(this.CurrentContext, args, productsToAssociate.ToList(), catalogName); if (result == null) { return((IActionResult) new BadRequestObjectResult((object)value)); } return(new ObjectResult(command)); }
public bool MyAction(ODataActionParameters parameters) { Assert.True(parameters.ContainsKey("Customer")); ODataActionTests.Customer customer = parameters["Customer"] as ODataActionTests.Customer; Assert.NotNull(customer); Assert.Equal(101, customer.ID); Assert.Equal("Avatar", customer.Name); Assert.True(parameters.ContainsKey("Customers")); ValidateCustomers((parameters["Customers"] as IEnumerable<ODataActionTests.Customer>).ToList()); return true; }