public IList<string> ReturnValuesAsList(IFormCollection form) { var valuesList = new List<string>(); valuesList.Add(form["field1"]); valuesList.Add(form["field2"]); return valuesList; }
public IActionResult Create(IFormCollection form) { var DependencyGroupID = Convert.ToInt32(form["id"]); List<string> usersListOfTestRuns = form["TestRunID"].ToList(); string CreationMessage = "Dependencies created for" + System.Environment.NewLine; foreach(var TestRunID in usersListOfTestRuns) { Dependency dependency = new Dependency(); DependencyGroup dependencyGroup = _context.DependencyGroup.SingleOrDefault (t => t.DependencyGroupID == DependencyGroupID); dependency.DependencyGroupID = DependencyGroupID; dependency.TestRunID = Convert.ToInt32(TestRunID); CreationMessage = CreationMessage + "Dependency Group: " + dependencyGroup.Name + " & TestRunID: " + TestRunID; _context.Dependency.Add(dependency); } _context.SaveChanges(); if (ModelState.IsValid) { HttpContext.Session.SetString("Message", CreationMessage); return RedirectToAction("Details", new RouteValueDictionary(new { controller = "DependencyGroups", action = "Details", ID = DependencyGroupID })); } return RedirectToAction("Details", new RouteValueDictionary(new { controller = "DependencyGroups", action = "Details", ID = DependencyGroupID })); }
public async Task<IActionResult> Create(CampaignSummaryModel campaign, IFormCollection form) { if (campaign == null) { return HttpBadRequest(); } if (!User.IsTenantAdmin(campaign.TenantId)) { return HttpUnauthorized(); } if (ModelState.IsValid) { if (form.Files.Count > 0) { // If the form contains a file, upload it and update the ImageUrl. if (form.Files[0] != null) { var file = form.Files[0]; if (file.IsAcceptableImageContentType()) { campaign.ImageUrl = await _imageService.UploadCampaignImageAsync(campaign.Id, campaign.TenantId, form.Files[0]); } else { ModelState.AddModelError("ImageUrl", "You must upload a valid image file for the logo (.jpg, .png, .gif)"); return View(campaign); } } } int id = _bus.Send(new EditCampaignCommand { Campaign = campaign }); return RedirectToAction("Details", new {id = id, area = "Admin" }); } return View("Edit", campaign); }
public IActionResult Edit(long id, IFormCollection formCollection) { var model = ToCarouselWidgetFormModel(formCollection); foreach (var item in model.Items) { if (item.UploadImage != null) { if (!string.IsNullOrWhiteSpace(item.Image)) { _mediaService.DeleteMedia(item.Image); } item.Image = SaveFile(item.UploadImage); } } if (ModelState.IsValid) { var widgetInstance = _widgetInstanceRepository.Query().FirstOrDefault(x => x.Id == id); widgetInstance.Name = model.Name; widgetInstance.WidgetZoneId = model.WidgetZoneId; widgetInstance.Data = JsonConvert.SerializeObject(model.Items); _widgetInstanceRepository.SaveChange(); return Ok(); } return new BadRequestObjectResult(ModelState); }
private static HttpContext GetMockHttpContext(IFormCollection formCollection, bool hasForm = true) { var httpContext = new Mock<HttpContext>(); httpContext.Setup(h => h.Request.ReadFormAsync(It.IsAny<CancellationToken>())) .Returns(Task.FromResult(formCollection)); httpContext.Setup(h => h.Request.HasFormContentType).Returns(hasForm); return httpContext.Object; }
public FormFeature(IFormCollection form) { if (form == null) { throw new ArgumentNullException(nameof(form)); } Form = form; }
public ActionResult ReturnFileContent(IFormCollection form) { var file = form.Files.GetFile("File"); using (var reader = new StreamReader(file.OpenReadStream())) { var fileContent = reader.ReadToEnd(); return Content(fileContent); } }
public static Dictionary<string, string> GenerateDic(IFormCollection form,string prefix) { Dictionary<string, string> dic = new Dictionary<string, string>(); int count = 0; foreach (var item in form.Keys) { if (item.StartsWith(prefix)) count++; } for (int i = 0; i < count / 2; i++) { //dic.Add(form.Get(string.Format("{0}{1}][name]",prefix, i)), form.Get(string.Format("records[{0}][val]", i))); dic.Add(form[string.Format("{0}{1}][name]", prefix, i)], form[string.Format("{0}{1}][val]", prefix, i)]); } return dic; }
/// <summary> /// Creates a value provider for <see cref="IFormCollection"/>. /// </summary> /// <param name="bindingSource">The <see cref="BindingSource"/> for the data.</param> /// <param name="values">The key value pairs to wrap.</param> /// <param name="culture">The culture to return with ValueProviderResult instances.</param> public FormValueProvider( BindingSource bindingSource, IFormCollection values, CultureInfo culture) : base(bindingSource) { if (bindingSource == null) { throw new ArgumentNullException(nameof(bindingSource)); } if (values == null) { throw new ArgumentNullException(nameof(values)); } _values = values; _culture = culture; }
public IActionResult Post(IFormCollection formCollection) { var model = ToSpaceBarWidgetFormModel(formCollection); if (ModelState.IsValid) { var widgetInstance = new WidgetInstance { Name = model.Name, WidgetId = 5, WidgetZoneId = model.WidgetZoneId, PublishStart = model.PublishStart, PublishEnd = model.PublishEnd, DisplayOrder = model.DisplayOrder, Data = JsonConvert.SerializeObject(model.Items) }; _widgetInstanceRepository.Add(widgetInstance); _widgetInstanceRepository.SaveChanges(); return(Ok()); } return(new BadRequestObjectResult(ModelState)); }
public ActionResult Delete(int id, IFormCollection collection) { try { HttpClient client = newConnection.InitializeClient(); HttpResponseMessage res = client.DeleteAsync($"api/Posts/{id}").Result; if (res.IsSuccessStatusCode) { return(RedirectToAction("Index")); } else { throw new Exception(res.ReasonPhrase); } //return NotFound(); } catch { throw new Exception("Can't complete the process"); } }
public ActionResult Create(IFormCollection collection) { try { // TODO: Add insert logic here Product product = new Product(); product.ProductName = collection["ProductName"]; product.Brand = collection["Brand"]; product.Price = decimal.Parse(collection["Price"]); product.StockQuantity = int.Parse(collection["StockQuantity"]); product.Spec = collection["Spec"]; product.ManufactorId = int.Parse(collection["ManufactorId"]); product.Description = collection["Description"]; _context.Product.Add(product); _context.SaveChanges(); return(RedirectToAction(nameof(Index))); } catch { return(View()); } }
public ActionResult Edit(int id, IFormCollection collection) { try { Product product = _context.Product.Find(id); product.ProductName = collection["ProductName"]; product.Brand = collection["Brand"]; product.Price = decimal.Parse(collection["Price"]); product.StockQuantity = int.Parse(collection["StockQuantity"]); product.Spec = collection["Spec"]; product.ManufactorId = int.Parse(collection["ManufactorId"]); product.Description = collection["Description"]; _context.SaveChanges(); // TODO: Add update logic here return(RedirectToAction(nameof(Index))); } catch { return(View()); } }
public ActionResult Edit(Location location, IFormCollection collection) { try { // TODO: Add update logic here var signedInUserId = Convert.ToInt64(HttpContext.Session.GetString("StudioLoggedInUserId")); location.DateLastModified = DateTime.Now; location.LastModifiedBy = signedInUserId; _databaseConnection.Entry(location).State = EntityState.Modified; _databaseConnection.SaveChanges(); //display notification TempData["display"] = "You have successfully modified the Location!"; TempData["notificationtype"] = NotificationType.Success.ToString(); return(RedirectToAction("Index")); } catch { return(View()); } }
public ActionResult Edit(int id, IFormCollection collection) { Usuario u = null; try { u = ru.ObtenerPorId(id); u.Nombre = collection["Nombre"]; u.Apellido = collection["Apellido"]; u.Email = collection["Email"]; u.TipoCuenta = Convert.ToInt32(collection["TipoCuenta"]); ru.Modificacion(u); TempData["Alerta"] = $"Datos del usuario #'{u.Id}' modificados correctamente."; return(RedirectToAction(nameof(Index))); } catch (Exception ex) { ViewData["Error"] = ex.Message; TempData["ErrorM"] = "Error desconocido."; return(View(u)); } }
public JsonResult Gravar(IFormCollection form) { if (form.Keys.Count > 0) { int id = 0; int.TryParse(form["Id"], out id); string nome = form["Nome"].ToString().Trim(); DateTime inicio = DateTime.MinValue; DateTime.TryParse(form["Inicio"], out inicio); DateTime fim = DateTime.MinValue; DateTime.TryParse(form["Fim"], out fim); string msgFeedback = form["MsgFeedBack"].ToString().Trim(); string guid = form["Guid"].ToString().Trim(); int idUsuario = int.Parse(Request.Cookies["idUsuario"].ToString()); QuestionarioViewModel q = new QuestionarioViewModel(); q.Id = id; q.Nome = nome; q.Inicio = inicio; q.Fim = fim; q.MsgFeedback = msgFeedback; q.Guid = guid; q.UsuarioId = idUsuario; cl.QuestionarioController ctlQuestionario = new cl.QuestionarioController(); if (ctlQuestionario.Gravar(q) > 0) { return(Json("")); } else { return(Json("Erro ao gravar o questionário: " + q.Nome.ToUpper())); } } else { return(Json("O formulário submetido não contem valores válidos.")); } }
public static async Task <string> FormProcess(HttpRequest request) { string hovaten = ""; bool luachon = false; string email = ""; string password = ""; string thongbao = ""; if (request.Method == "POST") { IFormCollection _form = request.Form; hovaten = _form["hovaten"].FirstOrDefault() ?? ""; thongbao = $@"Dữ liệu post - email: {email} - hovaten: {hovaten} - password: {password} - luachon: {luachon} "; } string format = await File.ReadAllTextAsync("wwwroot/html/formtest.html"); // Đọc nội dung HTML từ file string formhtml = string.Format(format, hovaten, email, luachon ? "checked" : ""); return(formhtml + thongbao); }
public ActionResult Delete(int id, IFormCollection collection) { try { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"DELETE FROM Computer WHERE Id = @id"; cmd.Parameters.Add(new SqlParameter("@id", id)); cmd.ExecuteNonQuery(); } } return(RedirectToAction(nameof(Index))); } catch { return(View("DeleteError")); } }
public ActionResult Mostrar(IFormCollection formulario) { List <Transacao> transacoes = new List <Transacao>(); StreamReader reader = new StreamReader(caminho, true); List <string> nomes = new List <string>(); while (!reader.EndOfStream) { string[] info = reader.ReadLine().Split(';'); Transacao t = new Transacao() { NumeroTransacao = int.Parse(info[0]), Descricao = info[1], tipo = info[2], valor = double.Parse(info[3]), data = System.DateTime.Parse(info[4]) }; transacoes.Add(t); } return(View()); }
// POST: ApiKey/Create public IActionResult Create(IFormCollection collection) { try { var userId = User.Claims.FirstOrDefault(x => x.Type == "sub").Value; var apiKeyModel = _queryEntities.RetrieveApiKey(userId); //Check if we already have a record for Api Key, if not create new if (string.IsNullOrEmpty(apiKeyModel.Id)) { apiKeyModel.ApiKey = $"{Guid.NewGuid().ToString()}.{userId}"; apiKeyModel.Id = userId; _queryEntities.SaveApiKeyAsync(apiKeyModel); } return(View(nameof(Index), apiKeyModel)); } catch { return(View()); } }
public async Task <IActionResult> UserManagement(IFormCollection formCollection, string submitButton) { var ids = formCollection["userId"].ToString().Split(new char[] { ',' }); foreach (var item in ids) { var user = _db.Users.Find(item); if (user == null) { return(RedirectToAction("Index")); } else if (submitButton == "Delete") { await _userManager.UpdateSecurityStampAsync(user); _db.Users.Remove(user); _db.SaveChanges(); } else if (submitButton == "Block") { await _userManager.UpdateSecurityStampAsync(user); user.LockoutStatus = true; await _userManager.SetLockoutEnabledAsync(user, true); await _userManager.SetLockoutEndDateAsync(user, DateTime.Today.AddYears(100)); } else if (submitButton == "Unblock") { user.LockoutStatus = false; await _userManager.SetLockoutEnabledAsync(user, false); } } if (ids.Contains(_userManager.GetUserId(User)) && submitButton != "Unblock") { await _signInManager.SignOutAsync(); } return(RedirectToAction("Index")); }
public ActionResult Cadastro(IFormCollection form) { UsuarioModel usuarioModel = new UsuarioModel( nome: form["nome"], email: form["email"], senha: form["senha"], data: DateTime.Parse(form["dataNascimento"]) ); // usuarioModel.Nome = form["nome"]; // usuarioModel.Email = form["email"]; // usuarioModel.DataNascimento = DateTime.Parse (form["dataNascimento"]); // usuarioModel.Senha = form["senha"]; // UsuarioRepositorio usuarioRepositorio = new UsuarioRepositorio(); // UsuarioRepositorioSerializacao usuarioRepositorio = new UsuarioRepositorioSerializacao(); UsuarioRepositorio.Cadastrar(usuarioModel); ViewBag.Mensagem = "Usuário Cadastrado"; return(View()); }
public ServerReturn UpdateSrtFile(IFormCollection postData) { if (postData.Files.Count == 0) { return new ServerReturn { error = -1, error_msg = "没有上传文件" } } ; var file = postData.Files[0]; // 是否合并字幕内容 var ismergeStr = postData["ismerge"].LastOrDefault(); bool ismerge = false; if (!string.IsNullOrEmpty(ismergeStr)) { bool.TryParse(ismergeStr, out ismerge); } using (var stream = file.OpenReadStream()) { var bytes = new byte[file.Length]; stream.Read(bytes, 0, (int)file.Length); var extension = new FileInfo(file.FileName).Extension; if (extension.IndexOf(".vtt") > -1) { bu.UploadVttFile(UserId, file.FileName, bytes, ismerge); } else { bu.UploadSrtFile(UserId, file.FileName, bytes, ismerge); } } return(new ServerReturn { }); }
public IActionResult Audit(int id, IFormCollection collection) { var dto = new AuditModel(); TryUpdateModelAsync(dto); if (ModelState.IsValid) { var result = _service.Audit(id, dto.AuditProfit, dto.ActualServiceAmount, CurrentUser.No, CurrentUser.Name); if (result > 0) { return(RedirectToAction(nameof(Index))); } ModelState.AddModelError(string.Empty, "审核失败"); } var entity = _db.Load <Approval>(id); ViewBag.Entity = entity; return(View(dto)); }
public ActionResult Edit(int id, IFormCollection collection) { try { // TODO: Add update logic here var booking = bookingList.Where(t => t.Id == id).FirstOrDefault(); booking.TourID = Convert.ToInt32(collection["TourID"]); booking.TourName = collection["TourName"]; booking.ClientID = Convert.ToInt32(collection["ClientID"]); booking.DepartureDate = Convert.ToDateTime(collection["DepartureDate"]); booking.NumberOfPeople = Convert.ToInt32(collection["NumberOfPeople"]); booking.FullName = collection["FullName"]; booking.Email = collection["Email"]; booking.ContactNo = Convert.ToInt32(collection["contactNo"]); booking.SpecialRequest = collection["SpecialRequest"]; return(RedirectToAction(nameof(Index))); } catch { return(View()); } }
public ActionResult Create(IFormCollection collection) { try { if (Convert.ToInt32(collection["CustID"]) > 0) { int custID = Convert.ToInt32(collection["CustID"]); TempData["CustID"] = custID; int stoID = Convert.ToInt32(collection["StoID"]); TempData["StoID"] = stoID; lib.Customer Cust = irepOrigCust.GetCustomers(cusid: custID).First(); string custName = Cust.FullName; TempData["CustName"] = custName; } return(RedirectToAction(nameof(Edit))); } catch { return(View()); } }
public virtual async Task<IActionResult> CustomerSubscriptionsPOST(IFormCollection formCollection) { foreach (var key in formCollection.Keys) { var value = formCollection[key]; if (value.Equals("on") && key.StartsWith("biss", StringComparison.InvariantCultureIgnoreCase)) { var id = key.Replace("biss", "").Trim(); if (int.TryParse(id, out var subscriptionId)) { var subscription = await _backInStockSubscriptionService.GetSubscriptionByIdAsync(subscriptionId); if (subscription != null && subscription.CustomerId == (await _workContext.GetCurrentCustomerAsync()).Id) { await _backInStockSubscriptionService.DeleteSubscriptionAsync(subscription); } } } } return RedirectToRoute("CustomerBackInStockSubscriptions"); }
public ActionResult Create(IFormCollection collection, Models.Contact contact) { Domain.Contact dmc = new Contact(); dmc.FirstName = contact.FirstName; dmc.MiddleName = contact.MiddleName; dmc.LastName = contact.LastName; dmc.Mobile = contact.Mobile; dmc.WorkPhone = contact.WorkPhone; dmc.HomePhone = contact.HomePhone; dmc.Email = contact.Email; try { db.Add(dmc); db.Save(); return(RedirectToAction(nameof(Index))); } catch { return(View()); } }
public IActionResult Register([FromForm] IFormCollection form) //string name, string surname, string email, string telephone, string password) { var name = form["name"]; var surname = form["surname"]; var email = form["email"]; var telephone = form["telephone"]; var password = form["password"]; AccountDto accountDto = new AccountDto { Name = name, Surname = surname, Email = email, Telephone = telephone, Password = password }; Account account = new Account { Name = accountDto.Name, Surname = accountDto.Surname, Email = accountDto.Email, Telephone = accountDto.Telephone, }; //map dto to entity //var account = _mapper.Map<Account>(accountDto); try { //save _accountService.Create(account, accountDto.Password); return(Redirect("/Login/Index/")); } catch (AppException ex) { //return error if there was an exception return(BadRequest(new { message = ex.Message })); } }
public IActionResult seatSelectionBookingPhase3(IFormCollection fc) { ViewBag.ShowId = fc["ShowId"]; showId = Int32.Parse(fc["ShowId"]); var Show = _context.Shows.FirstOrDefault(x => x.ShowId == showId); var Movie = _context.Movies.FirstOrDefault(x => x.MovieName == Show.MovieName); ViewBag.MovieName = Movie.MovieName; ViewBag.Url = Movie.PosterUrl; ViewBag.Language = Movie.Language; ViewBag.Genre = Movie.Genre; ViewBag.Director = Movie.Director; ViewBag.Duretion = Movie.Duretion; ViewBag.ReleaseDate = Movie.ReleaseDate; ViewBag.TheaterName = Show.TheaterName; ViewBag.StartTime = Show.StartTime; ViewBag.ScreenNo = Show.ScreenNo; ViewBag.Date = Show.Date; ViewBag.Price = Show.Price; return(View()); }
public void ImportCustomer(IFormCollection file) { try { var csv = file.Files.FirstOrDefault(); var customers = csv.ReadAsList(); List <Customer> customersToAdd = new List <Customer>(); customers.ForEach(x => customersToAdd.Add(new Customer { Name = x })); _context.Customer.AddRange(customersToAdd); _context.SaveChanges(); } catch (Exception e) { Console.WriteLine(e); throw; } }
public IActionResult UploadPackage(IFormCollection formItems) { try { var formFile = formItems.Files[0]; var clusterName = formItems["clustername"][0]; var extension = formFile.FileName.Substring(formFile.FileName.LastIndexOf('.')); if (extension != ".zip") { return(new ObjectResult(new { error = "不支持" + extension + "类型的文件" })); } _swift.PublishJobPackage(clusterName, (FormFile)formFile); return(new ObjectResult(new { error = "" })); } catch (Exception ex) { return(new ObjectResult(new { error = ex.Message })); } }
public async Task <bool> UploadFile(IFormCollection formData) { string uploadFolderPath = Path.Combine(host.WebRootPath, "uploads"); var file = formData.Files.GetFile("file"); var fileName = ContentDispositionHeaderValue .Parse(file.ContentDisposition).FileName.Trim('"'); var filePath = Path.Combine("uploads", "Files\\" + fileName); var fullPath = Path.Combine(uploadFolderPath, "Files\\" + fileName); if (await context.UploadedFiles.AnyAsync(upf => upf.Name == fileName)) { return(false); } if (!Directory.Exists(uploadFolderPath + "\\Files")) { Directory.CreateDirectory(uploadFolderPath + "\\Files"); } using (var stream = new FileStream(fullPath, FileMode.Create)) { await file.CopyToAsync(stream); // Import the file to the folder } var uploadedFile = new UploadedFile() { Name = fileName, Location = filePath, DateUploaded = DateTime.Now.ToString() }; await context.UploadedFiles.AddAsync(uploadedFile); await context.SaveChangesAsync(); return(true); }
public async Task <IActionResult> Put(long id, IFormCollection formCollection) { var model = ToCarouselWidgetFormModel(formCollection); foreach (var item in model.Items) { if (item.UploadImage != null) { if (!string.IsNullOrWhiteSpace(item.Image)) { await _mediaService.DeleteMediaAsync(item.Image); } item.Image = await SaveFile(item.UploadImage); } } if (ModelState.IsValid) { var widgetInstance = await _widgetInstanceRepository.Query().FirstOrDefaultAsync(x => x.Id == id); if (widgetInstance == null) { return(NotFound()); } widgetInstance.Name = model.Name; widgetInstance.PublishStart = model.PublishStart; widgetInstance.PublishEnd = model.PublishEnd; widgetInstance.WidgetZoneId = model.WidgetZoneId; widgetInstance.DisplayOrder = model.DisplayOrder; widgetInstance.Data = JsonConvert.SerializeObject(model.Items); await _widgetInstanceRepository.SaveChangesAsync(); return(Accepted()); } return(BadRequest(ModelState)); }
public IActionResult RegistrarPedido(IFormCollection form) { System.Console.WriteLine(form["nome"]); System.Console.WriteLine(form["endereco"]); System.Console.WriteLine(form["telefone"]); System.Console.WriteLine(form["email"]); System.Console.WriteLine(form["hamburguer"]); System.Console.WriteLine(form["shake"]); Pedido pedido = new Pedido(); Cliente cliente = new Cliente(); cliente.Nome = form["nome"]; cliente.Endereco = form["endereco"]; cliente.Telefone = form["telefone"]; cliente.Email = form["email"]; pedido.Cliente = cliente;//linkando o pedido ao cliente //Forma 2 - Usa parâmetros nos contrutores Hamburguer hamburguer = new Hamburguer( Nome: form["hamburguer"] ); pedido.Hamburguer = hamburguer; // Forma 3 Resumo da forma 1 Shake shake = new Shake() { Nome = form["Shake"] }; pedido.Shake = shake; Repositorio.Inserir(pedido); return(RedirectToAction("Index", "Home")); }
public ActionResult Delete(int id, IFormCollection collection) { try { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "Delete from Instructor where id = @id"; cmd.Parameters.Add(new SqlParameter("@id", id)); cmd.ExecuteNonQuery(); } } return(RedirectToAction(nameof(Index))); } catch { return(View()); } }
public IActionResult Order(IFormCollection collection) { OrderModel order = new OrderModel(); long id = 0; order.customer_name = collection["customer_name"]; order.address = collection["customer_address"]; order.customer_phone = collection["customer_phone"].ToString(); order.delivery_time = Convert.ToDateTime(collection["customer_time_delivery"]); order.customer_note = collection["customer_note"]; order.total = 0; order.count = 0; if (HttpContext.Session.GetString("cart") != null) { string obj = HttpContext.Session.GetString("cart"); // Lấy giá trị của session có key = cart var cart = JsonConvert.DeserializeObject <List <CartModel> >(obj); // Chuyển đổi giá trị từ string sang object đã được JSONConvert List <OrderDetailModel> listproduct = new List <OrderDetailModel>(); foreach (var product in cart) { order.total += product.product_price * product.quantity; order.count += product.quantity; } id = InsertOrder(order); foreach (var product in cart) { OrderDetailModel detail = new OrderDetailModel(); detail.order_id = (int)id; detail.product_id = product.product_id; detail.count = product.quantity; detail.price = product.product_price; detail.total = product.product_price * detail.count; bool check = InsertDetailOrder(detail); } HttpContext.Session.Remove("cart"); } return(RedirectToAction("OrderComplete", "Store", new { @id = id })); }
public async Task <IActionResult> Edit(String userId, IFormCollection collection) { var user = await _userManager.FindByIdAsync(userId); if (user == null) { return(NotFound($"Unable to load user with ID '{UserId}'")); } if (ModelState.IsValid) { user.FirstName = Input.FirstName; user.LastName = Input.LastName; string actualRole = (await _userManager.GetRolesAsync(user)).FirstOrDefault(); if (actualRole == null) { // Set user role await _userManager.AddToRoleAsync(user, Input.Role); } else if (!actualRole.Equals(Input.Role)) { // User has already a role, so first delete the actual role await _userManager.RemoveFromRoleAsync(user, actualRole); // Then, set the new role await _userManager.AddToRoleAsync(user, Input.Role); } // Update Security Stamp in order to refresh user cookie await _userManager.UpdateSecurityStampAsync(user); await _userManager.UpdateAsync(user); } return(RedirectToAction(nameof(Index))); }
public IActionResult user_registration(IFormCollection form) { string name = form["Name"].ToString(); string email = form["Email"].ToString(); string pwd = form["Password"].ToString(); string phn = form["PhoneNo"].ToString(); string gender = form["Gender"].ToString(); string langs = ""; if (form["C++"].ToString() == "true,false") { langs = langs + "C++" + ", "; } if (form["Java"].ToString() == "true,false") { langs = langs + "Java" + ", "; } if (form["Python"].ToString() == "true,false") { langs = langs + "Python"; } string details = ""; details += "Name : " + name + "\n"; details += "Email : " + email + "\n"; details += "Password : "******"\n"; details += "Phone no : " + phn + "\n"; details += "Gender : " + gender + ""; details += "Languages known : " + langs + "\n"; ViewBag.Details = details; ViewBag.Nm = "Name : " + name; ViewBag.Email = "Email : " + email; ViewBag.Pwd = "Password : "******"Phone no : " + phn; ViewBag.Gender = "Gender : " + gender; ViewBag.Langs = "Languages known : " + langs; return(View()); }
public IActionResult Create(IFormCollection formCollection) { var model = ToCarouselWidgetFormModel(formCollection); if (ModelState.IsValid) { foreach(var item in model.Items) { item.Image = SaveFile(item.UploadImage); } var widgetInstance = new WidgetInstance { Name = model.Name, WidgetId = 1, WidgetZoneId = model.WidgetZoneId, Data = JsonConvert.SerializeObject(model.Items) }; _widgetInstanceRepository.Add(widgetInstance); _widgetInstanceRepository.SaveChange(); return Ok(); } return new BadRequestObjectResult(ModelState); }
private async Task<IFormCollection> InnerReadFormAsync(CancellationToken cancellationToken) { if (!HasFormContentType) { throw new InvalidOperationException("Incorrect Content-Type: " + _request.ContentType); } cancellationToken.ThrowIfCancellationRequested(); if (_options.BufferBody) { _request.EnableRewind(_options.MemoryBufferThreshold, _options.BufferBodyLengthLimit); } FormCollection formFields = null; FormFileCollection files = null; // Some of these code paths use StreamReader which does not support cancellation tokens. using (cancellationToken.Register((state) => ((HttpContext)state).Abort(), _request.HttpContext)) { var contentType = ContentType; // Check the content-type if (HasApplicationFormContentType(contentType)) { var encoding = FilterEncoding(contentType.Encoding); using (var formReader = new FormReader(_request.Body, encoding) { ValueCountLimit = _options.ValueCountLimit, KeyLengthLimit = _options.KeyLengthLimit, ValueLengthLimit = _options.ValueLengthLimit, }) { formFields = new FormCollection(await formReader.ReadFormAsync(cancellationToken)); } } else if (HasMultipartFormContentType(contentType)) { var formAccumulator = new KeyValueAccumulator(); var boundary = GetBoundary(contentType, _options.MultipartBoundaryLengthLimit); var multipartReader = new MultipartReader(boundary, _request.Body) { HeadersCountLimit = _options.MultipartHeadersCountLimit, HeadersLengthLimit = _options.MultipartHeadersLengthLimit, BodyLengthLimit = _options.MultipartBodyLengthLimit, }; var section = await multipartReader.ReadNextSectionAsync(cancellationToken); while (section != null) { ContentDispositionHeaderValue contentDisposition; ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition); if (HasFileContentDisposition(contentDisposition)) { // Enable buffering for the file if not already done for the full body section.EnableRewind(_request.HttpContext.Response.RegisterForDispose, _options.MemoryBufferThreshold, _options.MultipartBodyLengthLimit); // Find the end await section.Body.DrainAsync(cancellationToken); var name = HeaderUtilities.RemoveQuotes(contentDisposition.Name) ?? string.Empty; var fileName = HeaderUtilities.RemoveQuotes(contentDisposition.FileName) ?? string.Empty; FormFile file; if (section.BaseStreamOffset.HasValue) { // Relative reference to buffered request body file = new FormFile(_request.Body, section.BaseStreamOffset.Value, section.Body.Length, name, fileName); } else { // Individually buffered file body file = new FormFile(section.Body, 0, section.Body.Length, name, fileName); } file.Headers = new HeaderDictionary(section.Headers); if (files == null) { files = new FormFileCollection(); } if (files.Count >= _options.ValueCountLimit) { throw new InvalidDataException($"Form value count limit {_options.ValueCountLimit} exceeded."); } files.Add(file); } else if (HasFormDataContentDisposition(contentDisposition)) { // Content-Disposition: form-data; name="key" // // value // Do not limit the key name length here because the mulipart headers length limit is already in effect. var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name); MediaTypeHeaderValue mediaType; MediaTypeHeaderValue.TryParse(section.ContentType, out mediaType); var encoding = FilterEncoding(mediaType?.Encoding); using (var reader = new StreamReader(section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true)) { // The value length limit is enforced by MultipartBodyLengthLimit var value = await reader.ReadToEndAsync(); formAccumulator.Append(key, value); if (formAccumulator.ValueCount > _options.ValueCountLimit) { throw new InvalidDataException($"Form value count limit {_options.ValueCountLimit} exceeded."); } } } else { System.Diagnostics.Debug.Assert(false, "Unrecognized content-disposition for this section: " + section.ContentDisposition); } section = await multipartReader.ReadNextSectionAsync(cancellationToken); } if (formAccumulator.HasValues) { formFields = new FormCollection(formAccumulator.GetResults(), files); } } } // Rewind so later readers don't have to. if (_request.Body.CanSeek) { _request.Body.Seek(0, SeekOrigin.Begin); } if (formFields != null) { Form = formFields; } else if (files != null) { Form = new FormCollection(null, files); } else { Form = FormCollection.Empty; } return Form; }
protected static Dictionary<string, string> GetIgnoredFormValues(IFormCollection form, Func<string, bool> ignore) { Dictionary<string, string> ignoredFormValues = new Dictionary<string, string>(); foreach (string key in form.Keys) { if (ignore(key)) { ignoredFormValues.Add(key, form[key]); } } return ignoredFormValues; }
public void UploadResult(int? id, IFormCollection Form) { TestRun testRun = _context.TestRun.Single(t => t.TestRunID == id); Test test = _context.Test.Single(t => t.TestID == testRun.TestID); var TestReportContents = Form.Single(t => t.Key == "TestReportDetails").Value; TestReportDetails testReportDetails = JsonConvert.DeserializeObject<TestReportDetails>(TestReportContents); var DateTimeForFilename = StringClass.sanitiseDateTimeStringForFilename(testReportDetails.strStartTime); var frameworkLogDirectory = Path.Combine("TestRunnerLogs", DateTimeForFilename); Directory.CreateDirectory(frameworkLogDirectory); var frameworkLogFilePath = Path.Combine("TestRunnerLogs", DateTimeForFilename, Form.First().Key); System.IO.File.WriteAllText(frameworkLogFilePath, Form.First().Value); AddTestRunnerLog(frameworkLogFilePath, Form.First().Key, testRun.TestRunner.Value, DateTimeForFilename); var resultDirectory = Path.Combine(strResultsDirectory, testRun.TestRunID.ToString(), DateTimeForFilename); Directory.CreateDirectory(resultDirectory); string screenshotList = Form.Single(t => t.Key == "ListOfScreenshots").Value; List<ScreenshotDetails> ListOfScreenshotDetails = JsonConvert.DeserializeObject<List<ScreenshotDetails>>(screenshotList); var screenshotFolder = Path.Combine(strScreenshotsDirectory, testRun.TestRunID.ToString(), DateTimeForFilename); Directory.CreateDirectory(screenshotFolder); var ResultID = AddResultOfID(testRun, resultDirectory, screenshotFolder, testReportDetails, test, testRun.TestEnvironmentID.Value); string stepDetailsList = Form.Single(t => t.Key == "ListOfStepDetails").Value; List<StepDetails> ListOfStepDetails = JsonConvert.DeserializeObject<List<StepDetails>>(stepDetailsList); StoreStepDetailsList(ListOfStepDetails, ResultID); StoreScreenshotDetailsList(ListOfScreenshotDetails, screenshotFolder, ResultID); foreach (var item in ListOfScreenshotDetails) { string imageString = Form.Single(t => t.Key == item.strStepID).Value; byte[] imageByteArray = JsonConvert.DeserializeObject<byte[]>(imageString); var screenshotFilePath = Path.Combine(screenshotFolder, item.strStepID); System.IO.File.WriteAllBytes(screenshotFilePath + ".png", imageByteArray); } }
private CarouselWidgetForm ToCarouselWidgetFormModel(IFormCollection formCollection) { var model = new CarouselWidgetForm(); model.Name = formCollection["name"]; model.WidgetZoneId = int.Parse(formCollection["widgetZoneId"]); int numberOfItems = int.Parse(formCollection["numberOfItems"]); for (var i = 0; i < numberOfItems; i++) { var item = new CarouselWidgetItemForm(); item.Caption = formCollection[$"items[{i}][caption]"]; item.TargetUrl = formCollection[$"items[{i}][targetUrl]"]; item.Image = formCollection[$"items[{i}][image]"]; item.UploadImage = formCollection.Files[$"items[{i}][uploadImage]"]; model.Items.Add(item); } return model; }
private static IDictionary ToDictionary(IFormCollection query, Func<string, bool> isFormFieldIgnored) { var dict = new Dictionary<string, string>(); foreach (var value in query.Where(v => isFormFieldIgnored(v.Key) == false)) { dict[value.Key] = string.Join(",", value.Value); } return dict; }
public SamlMessage(IFormCollection form) { this.form = form; }
public OwinRequest(IReadableStringCollection query, IFormCollection body) { _query = query; _body = body; }
public IActionResult Create(TestRunnerGroup testRunnerGroup, IFormCollection form) { if (ModelState.IsValid) { _context.TestRunnerGroup.Add(testRunnerGroup); _context.SaveChanges(); _context.Update(testRunnerGroup); foreach (var projectID in form["Projects"]) { var project = _context.Project.Single(t => t.ID == Convert.ToInt32(projectID)); _context.Update(project); project.TestRunnerGroupID = testRunnerGroup.TestRunnerGroupID; _context.SaveChanges(); } foreach (var folderID in form["Folders"]) { var folder = _context.Folder.Single(t => t.FolderID == Convert.ToInt32(folderID)); _context.Update(folder); folder.TestRunnerGroupID = testRunnerGroup.TestRunnerGroupID; _context.SaveChanges(); } foreach (var groupID in form["Groups"]) { var group = _context.Group.Single(t => t.GroupID == Convert.ToInt32(groupID)); _context.Update(group); group.TestRunnerGroupID = testRunnerGroup.TestRunnerGroupID; _context.SaveChanges(); } foreach (var runID in form["Runs"]) { var run = _context.Run.Single(t => t.GroupID == Convert.ToInt32(runID)); _context.Update(run); run.TestRunnerGroupID = testRunnerGroup.TestRunnerGroupID; _context.SaveChanges(); } HttpContext.Session.SetString("Message", "Test Runner Group: " + testRunnerGroup.Name + " successfully created"); return RedirectToAction("Details", new RouteValueDictionary(new { controller = "TestRunnerGroups", action = "Details", ID = testRunnerGroup.TestRunnerGroupID })); } return RedirectToAction("Details", new RouteValueDictionary(new { controller = "TestRunnerGroups", action = "Details", ID = testRunnerGroup.TestRunnerGroupID })); }
public IActionResult Edit(TestRunnerGroup testRunnerGroup, IFormCollection form) { if (ModelState.IsValid) { _context.Update(testRunnerGroup); var id = testRunnerGroup.TestRunnerGroupID; var projectsSelected = form["Projects"].ToList(); var projects = _context.Project; foreach (var project in projects) { _context.Update(project); if (projectsSelected.Any(t => Convert.ToInt32(t) == project.ID)) { project.TestRunnerGroupID = id; } else { project.TestRunnerGroupID = null; } } var foldersSelected = form["Folders"].ToList(); var folders = _context.Folder; foreach (var folder in folders) { _context.Update(folder); if (foldersSelected.Any(t => Convert.ToInt32(t) == folder.FolderID)) { folder.TestRunnerGroupID = id; } else { folder.TestRunnerGroupID = null; } } var groupsSelected = form["Groups"].ToList(); var groups = _context.Group; foreach (var group in groups) { _context.Update(group); if (groupsSelected.Any(t => Convert.ToInt32(t) == group.GroupID)) { group.TestRunnerGroupID = id; } else { group.TestRunnerGroupID = null; } } var runsSelected = form["Runs"].ToList(); var runs = _context.Run; foreach (var run in runs) { _context.Update(run); if (runsSelected.Any(t => Convert.ToInt32(t) == run.RunID)) { run.TestRunnerGroupID = id; } else { run.TestRunnerGroupID = null; } } _context.SaveChanges(); HttpContext.Session.SetString("Message", "Test Runner Group: " + testRunnerGroup.Name + " successfully edited"); return RedirectToAction("Details", new RouteValueDictionary(new { controller = "TestRunnerGroups", action = "Details", ID = testRunnerGroup.TestRunnerGroupID })); } return RedirectToAction("Index"); }
public static async Task Donate(IFormCollection Form, HttpContext Context) { var ok = true; string error_message = null; var name = Form[Forms.HelpElect.Keys.Name]; var email = Form[Forms.HelpElect.Keys.Email]; double amount = -1; double.TryParse(Form[Forms.HelpElect.Keys.Amount], out amount); if (amount < 5) { ok = false; error_message = "Sorry, due to credit card processing fees the minimum contribution is $5."; } var cc_number = Form[Forms.HelpElect.Keys.CreditCard + Site.Form.Constants.Parameter.Suffix.CreditCard.Number].Replace(" ", string.Empty); string cc_exp = Form[Forms.HelpElect.Keys.CreditCard + Site.Form.Constants.Parameter.Suffix.CreditCard.Expiration]; byte cc_month = 0; short cc_year = 0; if (cc_exp != null && cc_exp.Length >= 4) { byte.TryParse(cc_exp.Substring(0, 2), out cc_month); short.TryParse(cc_exp.Substring(cc_exp.Length - 2), out cc_year); if (cc_month >= 1 && cc_month <= 12 && cc_year > 14) { // valid expiration dates } else { ok = false; if (error_message == null) { error_message = "Please enter a valid expiration date. (e.g. \"08/16\")"; } else { error_message = "<br />Please enter a valid expiration date. (e.g. \"08/16\")"; } } } else { ok = false; if (error_message == null) { error_message = "Please enter a valid expiration date. (e.g. \"08/16\")"; } else { error_message = "<br />Please enter a valid expiration date. (e.g. \"08/16\")"; } } var cc_cvv = Form[Forms.HelpElect.Keys.CreditCard + Site.Form.Constants.Parameter.Suffix.CreditCard.Code]; var cc_city = Form[Forms.HelpElect.Keys.CreditCard + Site.Form.Constants.Parameter.Suffix.CreditCard.AddressCity]; var cc_state = Form[Forms.HelpElect.Keys.CreditCard + Site.Form.Constants.Parameter.Suffix.CreditCard.AddressState]; var cc_zip = Form[Forms.HelpElect.Keys.CreditCard + Site.Form.Constants.Parameter.Suffix.CreditCard.AddressPostalCode]; if (ok) { External.Stripe.Response stripe = (External.Stripe.Response) new External.Stripe().Charge(amount, $"Donation from {name}, {email}", cc_number, cc_month, cc_year, cc_cvv, name, null, null, cc_state, cc_zip, null); if (stripe != null) { if (stripe.Success) { await Context.Response.WriteAsync(Response.Substitute(Forms.HelpElect.HtmlID.DonateFormContainer, $"<div class=\"tac\">Thanks! Your contribution has been received and a confirmation email will be sent to {email} shortly.</div>")); var confirmation = new External.Email() {To = email, Subject = "Thank you for your contribution to Denton for City Council", Body = $"Thank you for your generous contribution of ${amount} to my campaign. It means a lot to have your support.\r\n\r\nThanks again,\r\nJosh Denton"}; var notification = new External.Email() { To = Application.HelpElect.Donate.ConfirmationEmail, Subject = $"Denton for City Council: New Donation ${amount}", Body = $"A new contribution was received from: {name}\r\nAmount: ${amount}\r\n\r\nEmail Address: {email}\r\nCity: {cc_city}\r\nState: {cc_state}\r\nZip Code: {cc_zip}" }; await Task.WhenAll(new Task[] { confirmation.Send(), notification.Send() }); } else { if (stripe.Error != null) { if (stripe.Error is External.Stripe.Response.StripeException.APIError) { await Context.Response.WriteAsync(Response.Error("Sorry, there was an error with the credit card processor. Please try again shortly.", true)); } else if (stripe.Error is External.Stripe.Response.StripeException.CardError) { await Context.Response.WriteAsync(Response.Error("Sorry, there was an error with the credit card. Message: " + stripe.Error.Message, true)); } else if (stripe.Error is External.Stripe.Response.StripeException.InvalidRequestError) { await Context.Response.WriteAsync(Response.Error("Sorry, there was an error processing your credit card.", true)); } } else { await Context.Response.WriteAsync(Response.Error("Sorry, there was an error processing your credit card.", true)); } } } else { await Context.Response.WriteAsync(Response.Error("Sorry, there was an error processing your credit card.", true)); } } else { await Context.Response.WriteAsync(Response.Error(error_message, true)); } }
public static async Task Support(IFormCollection Form, HttpContext Context) { var name = Form[Forms.HelpElect.Keys.Name]; var email = Form[Forms.HelpElect.Keys.Email]; var address = Form[Forms.HelpElect.Keys.Address]; bool bumpersticker = false, yardsign = false; bool.TryParse(Form[Forms.HelpElect.Keys.BumperSticker], out bumpersticker); bool.TryParse(Form[Forms.HelpElect.Keys.YardSign], out yardsign); var message = "Thanks! Your information has been received."; if (bumpersticker) { if (yardsign) { // bumpersticker AND yardsign message = "Thank you for support, I will reach out to you this week about delivering your Denton for City Council yard sign and bumper sticker soon."; } else { // bumpersticker BUT NOT yardsign message = "Thank you for support, I will reach out to you this week about delivering your Denton for City Council bumper sticker soon."; } } else { if (yardsign) { // NOT bumpersticker BUT yardsign message = "Thank you for support, I will reach out to you this week about delivering your Denton for City Council yard sign soon."; } } await new External.Email() { To = Application.HelpElect.Support.Email, Subject = "Denton for City Council: New Supporter", Body = $"A new user, {name}, has pledged support on the website.\r\n\r\nEmail: {email}\r\nAddress: {address}\r\n\r\nYard Sign: {(yardsign ? "Yes" : "No")}\r\nBumper Sticker: {(bumpersticker ? "Yes" : "No")}" }.Send(); await Context.Response.WriteAsync(Response.Substitute(Forms.HelpElect.HtmlID.SupportFormContainer, $"<div class=\"tac\">{message}</div>")); }
public WebService(Server server, HttpContext context, string[] paths, IFormCollection form = null) { //get parameters from request body, including ViewState ID string viewstate = ""; object[] parms = new object[0]; byte[] bytes = new byte[0]; string data = ""; int dataType = 0; //0 = ajax, 1 = form post, 2 = multi-part form if (form == null) { using (MemoryStream ms = new MemoryStream()) { context.Request.Body.CopyTo(ms); bytes = ms.ToArray(); } data = Encoding.UTF8.GetString(bytes, 0, bytes.Length); }else { dataType = 2; } if (data.Length > 0) { if (data.IndexOf("Content-Disposition") > 0) { //multi-part file upload dataType = 2; } else if (data.IndexOf("{") >= 0 && data.IndexOf("}") > 0 && data.IndexOf(":") > 0) { //JSON post data Dictionary<string, object> attr = JsonConvert.DeserializeObject<Dictionary<string, object>>(data); parms = new object[attr.Count - 1]; int x = 0; string val = ""; foreach (KeyValuePair<string, object> item in attr) { val = item.Value.ToString(); ; if (item.Key == "viewstateId") { viewstate = val; } else { //convert value into integer or float if (IsNumeric(val)) { if (val.IndexOf('.') >= 0) { parms[x] = float.Parse(val); } else { parms[x] = Int32.Parse(val); } } else { parms[x] = item.Value; } x = x + 1; } } } else if (data.IndexOf("=") >= 0) { //form post data dataType = 1; } } else { //get viewstate from query string viewstate = context.Request.Query["v"]; } R = new Core(server, context, viewstate, "service"); R.Page.GetPageUrl(); //load service class from URL path string className = "Rennder.Services." + paths[1]; string methodName = paths[2]; if(paths.Length == 4) { className += "." + paths[2]; methodName = paths[3]; } Type type =Type.GetType(className); Service service = (Service)Activator.CreateInstance(type, new object[] { R, paths }); if (dataType == 1) { //form post data string[] items = R.Server.UrlDecode(data).Split('&'); string[] item; for(int x = 0; x < items.Length; x++) { item = items[x].Split('='); service.Form.Add(item[0], item[1]); } }else if(dataType == 2) { //multi-part file upload service.Files = form.Files; } //execute method from service class MethodInfo method = type.GetMethod(methodName); object result = method.Invoke(service, parms); if(result != null) { switch (result.GetType().FullName) { case "Rennder.WebRequest": //send raw content (HTML) WebRequest res = (WebRequest)result; context.Response.ContentType = res.contentType; context.Response.WriteAsync(res.html); break; default: //JSON serialize web service response string serialized = "{\"type\":\"" + result.GetType().FullName + "\", \"d\":" + JsonConvert.SerializeObject(result) + "}"; context.Response.ContentType = "text/json"; context.Response.WriteAsync(serialized); break; } }else { context.Response.ContentType = "text/json"; context.Response.WriteAsync("{\"type\":\"Empty\",\"d\":{}}"); } //finally, unload the Rennder Core: //close SQL connection, save ViewState, save User info R.Unload(); }
private LoginType DetectLoginType(IFormCollection form) { if (!string.IsNullOrEmpty(form.Get("grant_type")) && form.Get("grant_type").Equals("refresh_token")) return LoginType.RefreshToken; if (!string.IsNullOrEmpty(form.Get("cauthorization"))) return LoginType.LoginApiKey; return !string.IsNullOrEmpty(form.Get("deviceKey")) ? LoginType.LoginDevice : LoginType.LoginForm; }
private static NameValueCollection BuildParams(IFormCollection form, IReadableStringCollection query) { var nvc = new NameValueCollection(); if (form != null) foreach (var item in form) nvc[item.Key] = item.Value[0]; foreach (var item in query) nvc[item.Key] = item.Value[0]; return nvc; }
public int ReturnCollectionCount(IFormCollection form) { return form.Count; }
private User GetAuthor(IFormCollection form) { return new User( form["user_id"], form["user_name"], Robot.GetUserRoles(form["user_name"]), form["channel_name"], Id); }
public HttpRequestParams(IReadableStringCollection urlData, IFormCollection formData) { UrlData = urlData; FormData = formData; }
public SamlMessage(IFormCollection form, IOwinContext context, SAML2.Config.Saml2Configuration config) : this(form) { this.context = context; this.config = config; }
public async Task<IFormCollection> ReadFormAsync(CancellationToken cancellationToken) { if (Form != null) { return Form; } if (!HasFormContentType) { throw new InvalidOperationException("Incorrect Content-Type: " + _request.ContentType); } cancellationToken.ThrowIfCancellationRequested(); _request.EnableRewind(); IDictionary<string, StringValues> formFields = null; var files = new FormFileCollection(); // Some of these code paths use StreamReader which does not support cancellation tokens. using (cancellationToken.Register(_request.HttpContext.Abort)) { var contentType = ContentType; // Check the content-type if (HasApplicationFormContentType(contentType)) { var encoding = FilterEncoding(contentType.Encoding); formFields = await FormReader.ReadFormAsync(_request.Body, encoding, cancellationToken); } else if (HasMultipartFormContentType(contentType)) { var formAccumulator = new KeyValueAccumulator(); var boundary = GetBoundary(contentType); var multipartReader = new MultipartReader(boundary, _request.Body); var section = await multipartReader.ReadNextSectionAsync(cancellationToken); while (section != null) { var headers = new HeaderDictionary(section.Headers); ContentDispositionHeaderValue contentDisposition; ContentDispositionHeaderValue.TryParse(headers[HeaderNames.ContentDisposition], out contentDisposition); if (HasFileContentDisposition(contentDisposition)) { // Find the end await section.Body.DrainAsync(cancellationToken); var file = new FormFile(_request.Body, section.BaseStreamOffset.Value, section.Body.Length) { Headers = headers, }; files.Add(file); } else if (HasFormDataContentDisposition(contentDisposition)) { // Content-Disposition: form-data; name="key" // // value var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name); MediaTypeHeaderValue mediaType; MediaTypeHeaderValue.TryParse(headers[HeaderNames.ContentType], out mediaType); var encoding = FilterEncoding(mediaType?.Encoding); using (var reader = new StreamReader(section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true)) { var value = await reader.ReadToEndAsync(); formAccumulator.Append(key, value); } } else { System.Diagnostics.Debug.Assert(false, "Unrecognized content-disposition for this section: " + headers[HeaderNames.ContentDisposition]); } section = await multipartReader.ReadNextSectionAsync(cancellationToken); } formFields = formAccumulator.GetResults(); } } // Rewind so later readers don't have to. _request.Body.Seek(0, SeekOrigin.Begin); Form = new FormCollection(formFields, files); return Form; }
public WebService(Server server, HttpContext context, string[] paths, IFormCollection form = null) { //get parameters from request body, including page id var parms = new Dictionary<string, string>(); object[] paramVals; var param = ""; byte[] bytes = new byte[0]; string data = ""; string pageId = ""; int dataType = 0; //0 = ajax, 1 = HTML form post, 2 = multi-part form (with file uploads) //figure out what kind of data was sent with the request if (form == null) { //get POST data from request using (MemoryStream ms = new MemoryStream()) { context.Request.Body.CopyTo(ms); bytes = ms.ToArray(); } data = Encoding.UTF8.GetString(bytes, 0, bytes.Length); }else { //form files exist dataType = 2; } if (data.Length > 0) { if (data.IndexOf("Content-Disposition") > 0) { //multi-part file upload dataType = 2; } else if (data.IndexOf("{") >= 0 && data.IndexOf("}") > 0 && data.IndexOf(":") > 0) { //get method parameters from POST S.ajax.post() Dictionary<string, object> attr = JsonConvert.DeserializeObject<Dictionary<string, object>>(data); foreach (KeyValuePair<string, object> item in attr) { if(item.Key == "pageId") { pageId = item.Value.ToString(); }else { parms.Add(item.Key.ToLower(), item.Value.ToString()); } } } else if (data.IndexOf("=") >= 0) { //HTML form POST data dataType = 1; } } else { //get method parameters from query string foreach(var key in context.Request.Query.Keys) { parms.Add(key.ToLower(), context.Request.Query[key].ToString()); } } //start building Web API response (find method to execute & return results) S = new Core(server, context); //load service class from URL path string className = "Websilk.Services." + paths[1]; string methodName = paths[2]; if(paths.Length == 4) { className += "." + paths[2]; methodName = paths[3]; } var service = GetService(className); if (S.Util.Str.IsNumeric(pageId)) { service.pageId = int.Parse(pageId); } if (dataType == 1) { //parse HTML form POST data and send to new Service instance string[] items = S.Server.UrlDecode(data).Split('&'); string[] item; for(var x = 0; x < items.Length; x++) { item = items[x].Split('='); service.Form.Add(item[0], item[1]); } }else if(dataType == 2) { //send multi-part file upload data to new Service instance service.Files = form.Files; } //execute method from new Service instance Type type = Type.GetType(className); MethodInfo method = type.GetMethod(methodName); //try to cast params to correct types ParameterInfo[] methodParams = method.GetParameters(); paramVals = new object[methodParams.Length]; for(var x = 0; x < methodParams.Length; x++) { //find correct key/value pair param = ""; foreach(var item in parms) { if(item.Key == methodParams[x].Name.ToLower()) { param = item.Value; } } //cast params to correct (supported) types switch (methodParams[x].ParameterType.Name.ToLower()) { case "int32": paramVals[x] = Int32.Parse(param); break; case "boolean": paramVals[x] = param.ToLower() == "true" ? true : false; break; case "double": paramVals[x] = double.Parse(param); break; default: paramVals[x] = param; break; } } object result = method.Invoke(service, paramVals); //finally, unload the Websilk Core: //close SQL connection, save User info, etc (before sending response) S.Unload(); if (result != null) { switch (result.GetType().FullName) { case "Websilk.Services.WebRequest": //send raw content (HTML) var res = (Services.WebRequest)result; context.Response.ContentType = res.contentType; context.Response.WriteAsync(res.html); break; default: //JSON serialize web service response string serialized = "{\"type\":\"" + result.GetType().FullName + "\", \"d\":" + JsonConvert.SerializeObject(result) + "}"; context.Response.ContentType = "text/json"; context.Response.WriteAsync(serialized); break; } }else { context.Response.ContentType = "text/json"; context.Response.WriteAsync("{\"type\":\"Empty\",\"d\":{}}"); } }