public ActionResult <Strategy> PostStrategySimul(int id, int countryId, int regionId, IFormCollection form)
        {
            var strategy = _context.mStrategy.Where(s => s.Id == id && s.ImplementingClass != null).FirstOrDefault();

            if (strategy == null)
            {
                return(NotFound());
            }
            var body = form.ToDictionary(k => k.Key, v => v.Value);

            var proxy          = new StrategyProxy();
            var strategyResult = proxy.OnRequest(body, strategy, _context, countryId, regionId);
            var properties     = strategyResult.GetType().GetProperties();
            var resultType     = properties[1].GetValue(strategyResult, null);
            var msg            = properties[2].GetValue(strategyResult, null);

            //if (strategyResult != null)
            if (resultType.Equals("S"))
            {
                var simulAdapter = new SimulAdapter();
                var simulInput   = simulAdapter.OnAdapt(_context, strategy, countryId, regionId, body);
                var result       = simulInput.ExecuteSimulation();
                return(Ok(result));
            }

            return(BadRequest(new { type = resultType, msg }));
        }
예제 #2
0
        public async Task <IActionResult> SavePriceCriteria(IFormCollection formdata)
        {
            try
            {
                var priceCriteriaJson = formdata.ToDictionary(x => x.Key, x => x.Value)
                                        .Where(element => element.Key.Equals("priceCriteria")).Select(key => key.Value).ToList()[0];
                var criterias     = JsonConvert.DeserializeObject <ListCriteriasModels>(priceCriteriaJson);
                var priceCriteria = new PriceCriteria <ListCriteriasModels>();
                await priceCriteria.SavedAsync(criterias);

                return(new JsonResult(new
                {
                    message = "Сохранено"
                })
                {
                    StatusCode = 200
                });
            }
            catch
            {
            }

            return(new JsonResult(new
            {
                message = "Ошибка сохранения"
            })
            {
                StatusCode = 500
            });
        }
예제 #3
0
        public async Task <IActionResult> Edit(int id, IFormCollection form)
        {
            var dictionary = form.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            await _editor.EditOne($"ProductDrafts/{id}", dictionary);

            return(RedirectToAction("PleaseWait"));
        }
예제 #4
0
        public static TransactionResponse GetTransactionResponse(IFormCollection form)
        {
            //Dictionary<string, string> inDictionary = form.AllKeys.ToDictionary(x=> x, v=> form[v]);
            Dictionary <string, object> inDictionary = new Dictionary <string, object>();

            inDictionary = form.ToDictionary(x => x.Key, x => (object)x.Value);
            string inJson = JsonConvert.SerializeObject(inDictionary);
            TransactionResponse response = JsonConvert.DeserializeObject <TransactionResponse>(inJson);

            return(response);
        }
        public async Task <IActionResult> PaymentCallback([FromForm] IFormCollection form)
        {
            if (form is null)
            {
                return(BadRequest("Payment data is required"));
            }

            var dictionary = form.ToDictionary(k => k.Key, k => WebUtility.UrlDecode(k.Value.ToString()));
            var value      = JObject.FromObject(dictionary);

            return(OkOrBadRequest(await _callbackDispatcher.ProcessCallback(value)));
        }
        private async Task <Dictionary <string, string> > GetFormDataAsync(HttpContext httpContext)
        {
            if (httpContext.Request.HasFormContentType && httpContext.Request.Body.CanRead)
            {
                var formOptions = new FormOptions {
                    BufferBody = true
                };
                IFormCollection form = await httpContext.Request.ReadFormAsync(formOptions);

                return(form.ToDictionary(k => k.Key, v => v.Value.ToString(), StringComparer.InvariantCultureIgnoreCase));
            }
            return(new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase));
        }
예제 #7
0
        public async Task <ActionResult> Edit(Guid id, IFormCollection collection)
        {
            try
            {
                TEntry entry = new TEntry
                {
                    Id = id
                };
                entry.SetValues(collection.ToDictionary(s => s.Key, s => s.Value));
                TEntry item = await dataService.UpdateItem(entry);

                return(RedirectToAction(nameof(Index), new { id = item.Id }));
            }
            catch
            {
                return(View());
            }
        }
예제 #8
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            if (Request.Path == new PathString("/api/Account/SSOLogon"))
            {
                if (string.Equals(this.Request.Method, "POST", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(this.Request.ContentType) && (this.Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) && this.Request.Body.CanRead))
                {
                    if (!this.Request.Body.CanSeek)
                    {
                        this._logger.WriteVerbose("Buffering request body");
                        MemoryStream memoryStream = new MemoryStream();
                        await this.Request.Body.CopyToAsync((Stream)memoryStream);

                        memoryStream.Seek(0L, SeekOrigin.Begin);
                        this.Request.Body = (Stream)memoryStream;
                    }

                    IFormCollection form = await this.Request.ReadFormAsync();

                    //ToDo: clean up get the associated request
                    var protocolFactory = this._resolver.Resolve <Func <string, IProtocolHandler> >();
                    var protocolHanlder = protocolFactory(Bindings.Http_Post);

                    var protocolContext = new SamlProtocolContext
                    {
                        ResponseContext = new HttpPostResponseContext
                        {
                            AuthenticationMethod = base.Options.AuthenticationType,
                            Form = form.ToDictionary(x => x.Key, v => form.Get(v.Key)) as IDictionary <string, string>
                        }
                    };
                    await protocolHanlder.HandleResponse(protocolContext);

                    var responseContext = protocolContext.ResponseContext as HttpPostResponseContext;
                    var identity        = responseContext.Result;
                    if (identity != null)
                    {
                        return(new AuthenticationTicket(identity, new AuthenticationProperties()));
                    }
                }
            }
            return(null);
        }
예제 #9
0
        public IActionResult Index([FromForm] IFormCollection data)
        {
            var result = HandleRequest(data);
            var values = data
                         .OrderBy(x => x.Key, StringComparer.Ordinal)
                         .Select(x => $"  {x.Key}: {x.Value}\n");

            //logger.LogWarning("{0} {1}\nQuery: {2}\nValue:\n{3}\n{4}",
            //                  HttpContext.Request.Method,
            //                  HttpContext.Request.GetDisplayUrl(),
            //                  HttpContext.Request.QueryString,
            //                  string.Join("", values),
            //                  DumpResult(result));

            requestLogger.Log(new LastmApiRequest(
                                  data["method"],
                                  data.ToDictionary(x => x.Key, x => x.Value),
                                  result));

            return(result);
        }
예제 #10
0
        public async Task <IActionResult> DrugsExpensive(IFormCollection form)
        {
            var processingNDrugs = new ProcessingNDrugs();
            var messages         = new List <JsonResult>();
            var keysform         = form.ToDictionary(x => x.Key, x => x.Value).ToList();
            IEnumerable <IEnumerable <string> > splitDrugs;
            List <DrugNarcoticsModel>           listDrugs;

            foreach (var information in keysform)
            {
                switch (information.Key)
                {
                case "narcoticDrugsView":
                    var drugs = await Task.Run(() => processingNDrugs.GetDrugs());

                    if (drugs != null)
                    {
                        if (drugs.Count == 0)
                        {
                            messages.Add(new JsonResult(new
                            {
                                typemessage = "complite",
                                message     = "Список наркотических препарат пуст"
                            })
                            {
                                StatusCode = 200
                            });
                        }

                        messages.Add(new JsonResult(new
                        {
                            typemessage = "drugs",
                            message     = drugs
                        })
                        {
                            StatusCode = 200
                        });
                    }

                    break;

                case "narcoticDrugsAdd":
                    var newKey = await Task.Run(() => processingNDrugs.GetNewKey());

                    if (newKey == -1)
                    {
                        messages.Add(new JsonResult(new
                        {
                            typemessage = "error",
                            message     = "Ошибка чтении файла 'NDrugsReestr.xml' наркотических препаратов"
                        })
                        {
                            StatusCode = 500
                        });
                    }

                    splitDrugs = information.Value.ToString().Split(',').SplitArray(3);
                    listDrugs  =
                        splitDrugs.Select(x =>
                    {
                        var enumX = x.ToList();
                        return(new DrugNarcoticsModel
                        {
                            Id = newKey++,
                            NameDrug = enumX[0],
                            IncludeDate = enumX[1].ToDateTime(),
                            OutDate = enumX[2].ToDateTime()
                        });
                    }).ToList();


                    var resultAdd = await Task.Run(() => processingNDrugs.Add(listDrugs));

                    if (!resultAdd)
                    {
                        messages.Add(new JsonResult(new
                        {
                            typemessage = "error",
                            message     = "Ошибка при сохранении наркотических препаратов"
                        })
                        {
                            StatusCode = 500
                        });
                    }

                    messages.Add(new JsonResult(new
                    {
                        typemessage = "complite",
                        message     = "Новые препараты успешно внесены в список"
                    })
                    {
                        StatusCode = 200
                    });
                    break;

                case "narcoticDrugsEdit":
                    splitDrugs = information.Value.ToString().Split(',').SplitArray(4);
                    listDrugs  =
                        splitDrugs.Select(x =>
                    {
                        var enumX = x.ToList();
                        return(new DrugNarcoticsModel
                        {
                            Id = int.Parse(enumX[0]),
                            NameDrug = enumX[1],
                            IncludeDate = enumX[2].ToDateTime(),
                            OutDate = enumX[3].ToDateTime()
                        });
                    }).ToList();

                    var resultEdit = await Task.Run(() => processingNDrugs.Edit(listDrugs));

                    if (!resultEdit)
                    {
                        messages.Add(new JsonResult(new
                        {
                            typemessage = "error",
                            message     = "Ошибка при изменении препаратов"
                        })
                        {
                            StatusCode = 500
                        });
                        break;
                    }

                    messages.Add(new JsonResult(new
                    {
                        typemessage = "complite",
                        message     = "Препараты успешно изменены"
                    })
                    {
                        StatusCode = 200
                    });
                    break;

                default:
                    messages.Add(new JsonResult(new
                    {
                        typemessage = "error",
                        message     = "Ошибка чтения несущестующего параметра формы"
                    })
                    {
                        StatusCode = 500
                    });
                    break;
                }
            }

            return(new JsonResult(new { listmessages = messages }));
        }
예제 #11
0
 public static SlashCommand ToSlashCommand(this IFormCollection form)
 {
     return(new SlashCommand(form.ToDictionary(f => f.Key, f => f.Value.First())));
 }
예제 #12
0
 public static Dictionary <string, StringValues> Sanitise(IFormCollection form)
 {
     return(Sanitise(form.ToDictionary(k => k.Key, v => v.Value)));
 }
예제 #13
0
        private JObject ToJSON(IFormCollection formCollection)
        {
            var dict = formCollection.ToDictionary(s => s.Key, s => s.Value);

            return(JObject.Parse(JsonConvert.SerializeObject(dict)));
        }
예제 #14
0
 public static Dictionary <string, string> ToDictionary(IFormCollection requestForm)
 {
     return(requestForm?.ToDictionary(k => k.Key, k => requestForm[k.Key].ToString()));
 }
예제 #15
0
 public static async Task <Dictionary <string, string> > ToDictionary(this IFormCollection Form)
 {
     return(Form.ToDictionary(x => x.Key, x => x.Value.ToString()));
 }
예제 #16
0
 public static IDictionary <string, string> ToDictionary(this IFormCollection original)
 {
     return(original.ToDictionary(i => i.Key, i => i.Value.ToString()));
 }
예제 #17
0
        public async Task <IActionResult> Upload()
        {
            // admin and managers can upload files
            bool hasPermission = await userHasRole("Admin") || await userHasRole("Manager");

            if (!hasPermission)
            {
                return(BadRequest());
            }

            ApplicationUser user = await _userManager.GetUserAsync(User);

            IFormCollection   requestForm       = Request.Form;
            FileUploadRequest fileUploadRequest = new FileUploadRequest();
            long fileSize = 0;

            fileUploadRequest.File = requestForm.Files.FirstOrDefault();
            var dict = requestForm.ToDictionary(x => x.Key, x => x.Value.ToString());

            var dir              = dict["dir"];
            var uploadForGroup   = dict["uploadForGroup"];
            var uploadAsCategory = dict["uploadAsCategory"];
            var description      = dict["description"];

            fileUploadRequest.TargertTargetDirectory = dir;
            fileUploadRequest.Category    = Int32.Parse(uploadAsCategory);
            fileUploadRequest.Group       = Int32.Parse(uploadForGroup);
            fileUploadRequest.Description = description;

            var fileId = Guid.NewGuid().ToString();

            string filePath = GetTargetFilePath(fileUploadRequest.Group, user.Id, fileId + Path.GetExtension(fileUploadRequest.File.FileName));

            using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
            {
                await fileUploadRequest.File.CopyToAsync(fileStream);

                fileSize = fileStream.Length;
            }

            int?groupId = null;

            if (fileUploadRequest.Group > 0)
            {
                groupId = fileUploadRequest.Group;
            }

            int?categoryId = null;

            if (fileUploadRequest.Category > 0)
            {
                categoryId = fileUploadRequest.Category;
            }

            StoredFile storedFile = new StoredFile
            {
                FileSize          = fileSize,
                ApplicationUserId = user.Id,
                Name           = fileUploadRequest.File.FileName,
                FilePath       = filePath,
                FileCategoryId = categoryId,
                GroupId        = groupId,
                ParentDirPath  = dir,
                Description    = description
            };

            _context.StoredFiles.Add(storedFile);
            _context.SaveChanges();

            await _activityLogService.AddActivityAsync(user.UserName, "Uploaded : " + fileUploadRequest.File.FileName, LogLevelType.INFO.Id, storedFile.Id);

            JObject o = new JObject
            {
                { "fileId", storedFile.Id },
                { "name", fileUploadRequest.File.FileName },
                { "uploadDate", DateTime.Now },
                { "size", fileSize },
                { "parent", dir },
                { "locked", false }
            };

            return(Json(o));
        }