public static Module GetModuleInfo(FormCollection formInfo) { Module module = new Module(); module.ID = formInfo["ID"].ObjToInt(); module.Name = formInfo["Name"].ObjToStr(); module.Code = formInfo["Code"].ObjToStr(); module.Controller = formInfo["Controller"].ObjToStr(); module.IsEnable = formInfo["IsEnable"] == null ? true : string.Compare(formInfo["IsEnable"], "1") == 0; if (formInfo["ParentId"] != "NULL") { module.ParentId = formInfo["ParentId"].ObjToInt(); } List<string> operations = formInfo.AllKeys.Where(k => k.Contains("op")).ToList(); if (operations.Count > 0) { StringBuilder strOperation = new StringBuilder(); foreach (string operation in operations) { strOperation.Append(operation.Replace("op", "") + ","); } module.Operations = strOperation.Remove(strOperation.Length - 1, 1).ToString(); } return module; }
public FormCollection FetchAll() { FormCollection coll = new FormCollection(); Query qry = new Query(Form.Schema); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; }
/// <summary> /// Add one FormCollection to another. Combines them into one collection. /// </summary> /// <param name="collection">The collection to merge with this one.</param> public void Add(FormCollection collection) { foreach(Form form in collection) { Add(form); } }
public async Task FormCollectionModelBinder_ValidType_BindSuccessful() { // Arrange var formCollection = new FormCollection(new Dictionary<string, StringValues> { { "field1", "value1" }, { "field2", "value2" } }); var httpContext = GetMockHttpContext(formCollection); var bindingContext = GetBindingContext(typeof(IFormCollection), httpContext); var binder = new FormCollectionModelBinder(); // Act var result = await binder.BindModelResultAsync(bindingContext); // Assert Assert.NotEqual(default(ModelBindingResult), result); Assert.True(result.IsModelSet); Assert.Empty(bindingContext.ValidationState); var form = Assert.IsAssignableFrom<IFormCollection>(result.Model); Assert.Equal(2, form.Count); Assert.Equal("value1", form["field1"]); Assert.Equal("value2", form["field2"]); }
public static Form FetchByShortName(string shortName) { FormCollection forms = new FormCollection().Where(Form.Columns.Shortname, shortName).Load(); if (forms.Count() == 0) return null; return forms.First<Form>(); }
public static Role GetRoleInfo(FormCollection formInfo) { Role role = new Role(); role.Name = formInfo["Name"].ObjToStr(); role.Remark = formInfo["Remark"].ObjToStr(); role.IsEnable = formInfo["IsEnable"] == null ? true : string.Compare(formInfo["IsEnable"], "1") == 0; return role; }
protected override IEnumerableValueProvider GetEnumerableValueProvider( BindingSource bindingSource, Dictionary<string, StringValues> values, CultureInfo culture) { var backingStore = new FormCollection(values); return new FormValueProvider(bindingSource, backingStore, culture); }
/// <summary> /// Creates a ControlFinder that will find controls on a specific Form according to their name. /// </summary> /// <param name="name">The name of the Control to find.</param> /// <param name="form">The form to search for the control.</param> public ControlFinder(string name, Form form) { this.name = name; if (form != null) { forms = new FormCollection(); forms.Add(form); } }
/// <summary> /// Constructor used to search for a ToolStripItem in a given form. If the form /// is null we seach in all forms in the current application. /// </summary> /// <param name="name"></param> /// <param name="form"></param> public ToolStripItemFinder(string name, Form form) { this.name = name; if (form != null) { forms = new FormCollection(); forms.Add(form); } }
public FormButtonHitter(Root root) { Root = root; FC = Root.FormCollection; InitializeComponent(); this.Left = FC.gpButtons.Left; this.Top = FC.gpButtons.Top; this.Width = FC.gpButtons.Width; this.Height = FC.gpButtons.Height; }
/// <summary> /// Finds all of the forms with a specified name and returns them in a FormCollection. /// </summary> /// <param name="name">The name of the form to search for.</param> /// <returns>the FormCollection of all found forms.</returns> public FormCollection FindAll(string name) { lock (this) { forms = new FormCollection(); this.name = name; IntPtr desktop = Win32.GetDesktopWindow(); Win32.EnumChildWindows(desktop, new Win32.WindowEnumProc(OnEnumWindow), IntPtr.Zero); return forms; } }
public ActionResult Delete(FormCollection collection) { //try //{ Model.EventService.DeleteEvent(int.Parse(collection["EventID"])); return RedirectToAction("Index"); //} //catch //{ // return View(); //} }
/// <summary> /// Finds all of the forms with a specified name and returns them in a FormCollection. /// </summary> /// <param name="name">The name of the form to search for.</param> /// <returns>the FormCollection of all found forms.</returns> public FormCollection FindAll(string name) { lock(this) { forms = new FormCollection(); this.name = name; if (Environment.OSVersion.Platform != PlatformID.Unix) { IntPtr desktop = Win32.GetDesktopWindow(); Win32.EnumChildWindows(desktop, new Win32.WindowEnumProc(OnEnumWindow), IntPtr.Zero); } return forms; } }
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var response = new HttpResponseMessage(); if (request.RequestUri.AbsoluteUri.StartsWith("https://api.twitter.com/oauth/access_token")) { var formData = new FormCollection(await FormReader.ReadFormAsync(await request.Content.ReadAsStreamAsync())); if (formData["oauth_verifier"] == "valid_oauth_verifier") { if (_requestTokenEndpointInvoked) { var response_Form_data = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("oauth_token", "valid_oauth_token"), new KeyValuePair<string, string>("oauth_token_secret", "valid_oauth_token_secret"), new KeyValuePair<string, string>("user_id", "valid_user_id"), new KeyValuePair<string, string>("screen_name", "valid_screen_name"), }; response.Content = new FormUrlEncodedContent(response_Form_data); } else { response.StatusCode = HttpStatusCode.InternalServerError; response.Content = new StringContent("RequestTokenEndpoint is not invoked"); } return response; } response.StatusCode = (HttpStatusCode)400; return response; } else if (request.RequestUri.AbsoluteUri.StartsWith("https://api.twitter.com/oauth/request_token")) { var response_Form_data = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("oauth_callback_confirmed", "true"), new KeyValuePair<string, string>("oauth_token", "valid_oauth_token"), new KeyValuePair<string, string>("oauth_token_secret", "valid_oauth_token_secret") }; _requestTokenEndpointInvoked = true; response.Content = new FormUrlEncodedContent(response_Form_data); return response; } throw new NotImplementedException(request.RequestUri.AbsoluteUri); }
public void ConstructorCopiesProvidedCollection() { // Arrange NameValueCollection nvc = new NameValueCollection() { { "foo", "fooValue" }, { "bar", "barValue" } }; // Act FormCollection formCollection = new FormCollection(nvc); // Assert Assert.Equal(2, formCollection.Count); Assert.Equal("fooValue", formCollection["foo"]); Assert.Equal("barValue", formCollection["bar"]); }
public ActionResult Create(FormCollection collection) { IQueryable<Group> groups; String grupa = collection["Group"]; Group group = null; groups = Model.GroupService.SearchGroups(grupa); if(!String.IsNullOrEmpty(grupa)) group = groups.Single(m => m.Name == grupa); DateTime from = Convert.ToDateTime(Request.Form["From"]); DateTime to = Convert.ToDateTime(Request.Form["To"]); String name = Request.Form["Name"]; String text = Request.Form["Text"]; Model.EventService.AddEvent(CurrentUser, group, from, to, name, text); return RedirectToAction("Index"); }
public IEnumerable<IResponse> AddressAndPayment(FormCollection values) { var order = new Order(); TryUpdateModel(order); if (string.Equals(values["PromoCode"], PromoCode, StringComparison.OrdinalIgnoreCase) == false) { yield return View(order); } else { var invalid = false; try { order.Username = User.Identity.Name; order.OrderDate = DateTime.Now; //Save Order storeDB.Orders.Add(order); storeDB.SaveChanges(); //Process the order var cart = ShoppingCart.Helper.GetCart(this.HttpContext); cart.CreateOrder(order); } catch { //Invalid - redisplay with errors invalid = true; } if (invalid) { yield return View(order); } else { yield return RedirectToAction("Complete", new { id = order.OrderId }); } } }
public void ConstructorUsesValidatedValuesWhenControllerIsNull() { // Arrange var values = new NameValueCollection() { { "foo", "fooValue" }, { "bar", "barValue" } }; // Act var result = new FormCollection(controller: null, validatedValuesThunk: () => values, unvalidatedValuesThunk: () => { throw new NotImplementedException(); }); // Assert Assert.Equal(2, result.Count); Assert.Equal("fooValue", result["foo"]); Assert.Equal("barValue", result["bar"]); }
public void ConstructorUsesValidatedValuesWhenControllerValidateRequestIsTrue() { // Arrange var values = new NameValueCollection() { { "foo", "fooValue" }, { "bar", "barValue" } }; var controller = new Mock<ControllerBase>().Object; controller.ValidateRequest = true; // Act var result = new FormCollection(controller, validatedValuesThunk: () => values, unvalidatedValuesThunk: () => { throw new NotImplementedException(); }); // Assert Assert.Equal(2, result.Count); Assert.Equal("fooValue", result["foo"]); Assert.Equal("barValue", result["bar"]); }
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var response = new HttpResponseMessage(); if (request.RequestUri.AbsoluteUri.StartsWith("https://login.microsoftonline.com/common/oauth2/v2.0/token")) { var formData = new FormCollection(await FormReader.ReadFormAsync(await request.Content.ReadAsStreamAsync())); if (formData["grant_type"] == "authorization_code") { if (formData["code"] == "ValidCode") { if (formData["redirect_uri"].Count > 0 && ((string)formData["redirect_uri"]).EndsWith("signin-microsoft") && formData["client_id"] == "[ClientId]" && formData["client_secret"] == "[ClientSecret]") { response.Content = new StringContent("{\"token_type\":\"bearer\",\"expires_in\":3600,\"scope\":\"https://graph.microsoft.com/user.read\",\"access_token\":\"ValidAccessToken\",\"refresh_token\":\"ValidRefreshToken\",\"authentication_token\":\"ValidAuthenticationToken\"}"); return response; } } } response.StatusCode = (HttpStatusCode)400; return response; } else if (request.RequestUri.AbsoluteUri.StartsWith("https://graph.microsoft.com/v1.0/me")) { if (request.Headers.Authorization.Parameter == "ValidAccessToken") { response.Content = new StringContent("{\r \"id\": \"fccf9a24999f4f4f\", \r \"displayName\": \"AspnetvnextTest AspnetvnextTest\", \r \"givenName\": \"AspnetvnextTest\", \r \"surname\": \"AspnetvnextTest\", \r \"link\": \"https://profile.live.com/\", \r \"gender\": null, \r \"locale\": \"en_US\", \r \"updated_time\": \"2013-08-27T22:18:14+0000\"\r}"); } else { response.Content = new StringContent("{\r \"error\": {\r \"code\": \"request_token_invalid\", \r \"message\": \"The access token isn't valid.\"\r }\r}", Encoding.UTF8, "text/javascript"); } return response; } throw new NotImplementedException(request.RequestUri.AbsoluteUri); }
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var response = new HttpResponseMessage(); if (request.RequestUri.AbsoluteUri.StartsWith("https://graph.facebook.com/v2.5/oauth/access_token")) { var formData = new FormCollection(await FormReader.ReadFormAsync(await request.Content.ReadAsStreamAsync())); if (formData["grant_type"] == "authorization_code") { if (formData["code"] == "ValidCode") { Helpers.ThrowIfConditionFailed(() => ((string)formData["redirect_uri"]).EndsWith("signin-facebook"), "Redirect URI is not ending with /signin-facebook"); Helpers.ThrowIfConditionFailed(() => formData["client_id"] == "[AppId]", "Invalid client Id received"); Helpers.ThrowIfConditionFailed(() => formData["client_secret"] == "[AppSecret]", "Invalid client secret received"); response.Content = new StringContent("{ \"access_token\": \"ValidAccessToken\", \"expires_in\": \"100\" }"); return response; } response.StatusCode = (HttpStatusCode)400; return response; } } else if (request.RequestUri.AbsoluteUri.StartsWith("https://graph.facebook.com/v2.5/me")) { var queryParameters = new QueryCollection(QueryHelpers.ParseQuery(request.RequestUri.Query)); Helpers.ThrowIfConditionFailed(() => queryParameters["appsecret_proof"].Count > 0, "appsecret_proof is empty"); if (queryParameters["access_token"] == "ValidAccessToken") { response.Content = new StringContent("{\"id\":\"Id\",\"name\":\"AspnetvnextTest AspnetvnextTest\",\"first_name\":\"AspnetvnextTest\",\"last_name\":\"AspnetvnextTest\",\"link\":\"https:\\/\\/www.facebook.com\\/myLink\",\"username\":\"AspnetvnextTest.AspnetvnextTest.7\",\"gender\":\"male\",\"email\":\"AspnetvnextTest\\u0040test.com\",\"timezone\":-7,\"locale\":\"en_US\",\"verified\":true,\"updated_time\":\"2013-08-06T20:38:48+0000\",\"CertValidatorInvoked\":\"ValidAccessToken\"}"); } else { response.Content = new StringContent("{\"error\":{\"message\":\"Invalid OAuth access token.\",\"type\":\"OAuthException\",\"code\":190}}"); } return response; } throw new NotImplementedException(request.RequestUri.AbsoluteUri); }
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var response = new HttpResponseMessage(); if (request.RequestUri.AbsoluteUri.StartsWith("https://www.googleapis.com/oauth2/v3/token")) { var formData = new FormCollection(await FormReader.ReadFormAsync(await request.Content.ReadAsStreamAsync())); if (formData["grant_type"] == "authorization_code") { if (formData["code"] == "ValidCode") { if (formData["redirect_uri"].Count > 0 && ((string)formData["redirect_uri"]).EndsWith("signin-google") && formData["client_id"] == "[ClientId]" && formData["client_secret"] == "[ClientSecret]") { response.Content = new StringContent("{\"access_token\":\"ValidAccessToken\",\"refresh_token\":\"ValidRefreshToken\",\"token_type\":\"Bearer\",\"expires_in\":\"1200\",\"id_token\":\"Token\"}", Encoding.UTF8, "application/json"); return response; } } } response.StatusCode = (HttpStatusCode)400; return response; } else if (request.RequestUri.AbsoluteUri.StartsWith("https://www.googleapis.com/plus/v1/people/me")) { if (request.Headers.Authorization.Parameter == "ValidAccessToken") { response.Content = new StringContent("{ \"kind\": \"plus#person\",\n \"etag\": \"\\\"YFr-hUROXQN7IOa3dUHg9dQ8eq0/2hY18HdHEP8NLykSTVEiAhkKsBE\\\"\",\n \"gender\": \"male\",\n \"emails\": [\n {\n \"value\": \"[email protected]\",\n \"type\": \"account\"\n }\n ],\n \"objectType\": \"person\",\n \"id\": \"106790274378320830963\",\n \"displayName\": \"AspnetvnextTest AspnetvnextTest\",\n \"name\": {\n \"familyName\": \"AspnetvnextTest\",\n \"givenName\": \"FirstName\"\n },\n \"url\": \"https://plus.google.com/106790274378320830963\",\n \"image\": {\n \"url\": \"https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50\"\n },\n \"isPlusUser\": true,\n \"language\": \"en\",\n \"circledByCount\": 0,\n \"verified\": false\n}\n", Encoding.UTF8, "application/json"); } else { response.Content = new StringContent("{\"error\":{\"message\":\"Invalid OAuth access token.\",\"type\":\"OAuthException\",\"code\":190}}"); } return response; } throw new NotImplementedException(request.RequestUri.AbsoluteUri); }
public ActionResult AdjustLeaves(FormCollection collection) { float AL = float.Parse(Request.Form["ALeaves"].ToString(), CultureInfo.InvariantCulture.NumberFormat); float CL = float.Parse(Request.Form["CLeaves"].ToString(), CultureInfo.InvariantCulture.NumberFormat); float SL = float.Parse(Request.Form["SLeaves"].ToString(), CultureInfo.InvariantCulture.NumberFormat); float CPL = float.Parse(Request.Form["CPLLeaves"].ToString(), CultureInfo.InvariantCulture.NumberFormat); int EmpID = Convert.ToInt32(Request.Form["EmpID"].ToString()); string year = Request.Form["LvYear"].ToString(); string EmpLvTypeYearCL = EmpID.ToString() + "A" + year; string EmpLvTypeYearAL = EmpID.ToString() + "B" + year; string EmpLvTypeYearSL = EmpID.ToString() + "C" + year; string EmpLvTypeYearCPL = EmpID.ToString() + "E" + year; var lvTypeAL = db.LvConsumeds.Where(aa => aa.EmpLvTypeYear == EmpLvTypeYearAL).ToList(); var lvTypeCL = db.LvConsumeds.Where(aa => aa.EmpLvTypeYear == EmpLvTypeYearCL).ToList(); var lvTypeSL = db.LvConsumeds.Where(aa => aa.EmpLvTypeYear == EmpLvTypeYearSL).ToList(); var lvTypeCPL = db.LvConsumeds.Where(aa => aa.EmpLvTypeYear == EmpLvTypeYearCPL).ToList(); //Anual if (lvTypeAL.Count > 0) { foreach (var item in lvTypeAL) { item.YearRemaining = (float)AL; item.GrandTotalRemaining = (float)AL; db.SaveChanges(); } } else { LvConsumed lvConsumed = new LvConsumed(); lvConsumed.Year = DateTime.Today.Year.ToString(); lvConsumed.EmpID = EmpID; lvConsumed.JanConsumed = 0; lvConsumed.FebConsumed = 0; lvConsumed.MarchConsumed = 0; lvConsumed.AprConsumed = 0; lvConsumed.MayConsumed = 0; lvConsumed.JuneConsumed = 0; lvConsumed.JulyConsumed = 0; lvConsumed.AugustConsumed = 0; lvConsumed.SepConsumed = 0; lvConsumed.OctConsumed = 0; lvConsumed.NovConsumed = 0; lvConsumed.DecConsumed = 0; lvConsumed.TotalForYear = AL; lvConsumed.YearRemaining = AL; lvConsumed.GrandTotal = AL; lvConsumed.GrandTotalRemaining = AL; lvConsumed.EmpLvType = EmpID.ToString() + "B"; lvConsumed.EmpLvTypeYear = EmpLvTypeYearAL; lvConsumed.LeaveType = "B"; db.LvConsumeds.Add(lvConsumed); db.SaveChanges(); } //Casual if (lvTypeCL.Count > 0) { foreach (var item in lvTypeCL) { item.YearRemaining = (float)CL; item.GrandTotalRemaining = (float)CL; db.SaveChanges(); } } else { LvConsumed lvConsumed = new LvConsumed(); lvConsumed.Year = DateTime.Today.Year.ToString(); lvConsumed.EmpID = EmpID; lvConsumed.JanConsumed = 0; lvConsumed.FebConsumed = 0; lvConsumed.MarchConsumed = 0; lvConsumed.AprConsumed = 0; lvConsumed.MayConsumed = 0; lvConsumed.JuneConsumed = 0; lvConsumed.JulyConsumed = 0; lvConsumed.AugustConsumed = 0; lvConsumed.SepConsumed = 0; lvConsumed.OctConsumed = 0; lvConsumed.NovConsumed = 0; lvConsumed.DecConsumed = 0; lvConsumed.TotalForYear = CL; lvConsumed.YearRemaining = CL; lvConsumed.GrandTotal = CL; lvConsumed.GrandTotalRemaining = CL; lvConsumed.EmpLvType = EmpID.ToString() + "A"; lvConsumed.EmpLvTypeYear = EmpLvTypeYearCL; lvConsumed.LeaveType = "A"; db.LvConsumeds.Add(lvConsumed); db.SaveChanges(); } //Sick if (lvTypeSL.Count > 0) { foreach (var item in lvTypeSL) { item.YearRemaining = (float)SL; item.GrandTotalRemaining = (float)SL; db.SaveChanges(); } } else { LvConsumed lvConsumed = new LvConsumed(); lvConsumed.Year = DateTime.Today.Year.ToString(); lvConsumed.EmpID = EmpID; lvConsumed.JanConsumed = 0; lvConsumed.FebConsumed = 0; lvConsumed.MarchConsumed = 0; lvConsumed.AprConsumed = 0; lvConsumed.MayConsumed = 0; lvConsumed.JuneConsumed = 0; lvConsumed.JulyConsumed = 0; lvConsumed.AugustConsumed = 0; lvConsumed.SepConsumed = 0; lvConsumed.OctConsumed = 0; lvConsumed.NovConsumed = 0; lvConsumed.DecConsumed = 0; lvConsumed.TotalForYear = SL; lvConsumed.YearRemaining = SL; lvConsumed.GrandTotal = SL; lvConsumed.GrandTotalRemaining = SL; lvConsumed.EmpLvType = EmpID.ToString() + "C"; lvConsumed.EmpLvTypeYear = EmpLvTypeYearSL; lvConsumed.LeaveType = "C"; db.LvConsumeds.Add(lvConsumed); db.SaveChanges(); } //CPL if (lvTypeCPL.Count > 0) { foreach (var item in lvTypeCPL) { item.YearRemaining = (float)CPL; item.GrandTotalRemaining = (float)CPL; db.SaveChanges(); } } else { LvConsumed lvConsumed = new LvConsumed(); lvConsumed.Year = DateTime.Today.Year.ToString(); lvConsumed.EmpID = EmpID; lvConsumed.JanConsumed = 0; lvConsumed.FebConsumed = 0; lvConsumed.MarchConsumed = 0; lvConsumed.AprConsumed = 0; lvConsumed.MayConsumed = 0; lvConsumed.JuneConsumed = 0; lvConsumed.JulyConsumed = 0; lvConsumed.AugustConsumed = 0; lvConsumed.SepConsumed = 0; lvConsumed.OctConsumed = 0; lvConsumed.NovConsumed = 0; lvConsumed.DecConsumed = 0; lvConsumed.TotalForYear = CPL; lvConsumed.YearRemaining = CPL; lvConsumed.GrandTotal = CPL; lvConsumed.GrandTotalRemaining = CPL; lvConsumed.EmpLvType = EmpID.ToString() + "E"; lvConsumed.EmpLvTypeYear = EmpLvTypeYearCPL; lvConsumed.LeaveType = "E"; db.LvConsumeds.Add(lvConsumed); db.SaveChanges(); } User LoggedInUser = Session["LoggedUser"] as User; ViewBag.CompanyID = new SelectList(CustomFunction.GetCompanies(db.Companies.ToList(), LoggedInUser), "CompID", "CompName", LoggedInUser.CompanyID); ViewBag.CompanyIDEmp = new SelectList(CustomFunction.GetCompanies(db.Companies.ToList(), LoggedInUser), "CompID", "CompName", LoggedInUser.CompanyID); ViewBag.LocationID = new SelectList(db.Locations.OrderBy(s => s.LocName), "LocID", "LocName"); ViewBag.CatID = new SelectList(db.Categories.OrderBy(s => s.CatName), "CatID", "CatName"); return(View("Index")); }
public ActionResult Edit(string can, string ssc, string csu, FormCollection formCollection) { //Check Exists ClientSubUnitClientAccount clientSubUnitClientAccount = new ClientSubUnitClientAccount(); clientSubUnitClientAccount = clientSubUnitClientAccountRepository.GetClientSubUnitClientAccount(can, ssc, csu); if (clientSubUnitClientAccount == null) { ViewData["ActionMethod"] = "EditPost"; return(View("RecordDoesNotExistError")); } //Access Rights RolesRepository rolesRepository = new RolesRepository(); if (!rolesRepository.HasWriteAccessToClientSubUnit(clientSubUnitClientAccount.ClientSubUnitGuid)) { ViewData["Message"] = "You do not have access to this item"; return(View("Error")); } if (!rolesRepository.HasWriteAccessToClientAccount(clientSubUnitClientAccount.ClientAccountNumber, clientSubUnitClientAccount.SourceSystemCode)) { ViewData["Message"] = "You do not have access to this item"; return(View("Error")); } //Update Item from Form try { UpdateModel(clientSubUnitClientAccount); } catch { string n = ""; foreach (ModelState modelState in ViewData.ModelState.Values) { foreach (ModelError error in modelState.Errors) { n += error.ErrorMessage; } } ViewData["Message"] = "ValidationError : " + n; return(View("Error")); } //Update Item try { clientSubUnitClientAccountRepository.Update(clientSubUnitClientAccount); } catch (SqlException ex) { //Versioning Error if (ex.Message == "SQLVersioningError") { ViewData["ReturnURL"] = "/ClientSubUnitClientAccount.mvc/Edit?clientAccountNumber=" + can + "&ssc=" + ssc + "&csu=" + csu; return(View("VersionError")); } //Generic Error ViewData["Message"] = "There was a problem with your request, please see the log file or contact an administrator for details"; return(View("Error")); } return(RedirectToAction("ListBySubUnit", new { id = clientSubUnitClientAccount.ClientSubUnitGuid })); }
public ActionResult Edit([Bind(Include = "Id,CategoryId,DestinationId,Title,Price,DaysTour,Description,Content,Url,Publish,SortOrder,CreateDate,Status")] Tour tour, FormCollection f) { tour.ModifiedDate = DateTime.Now; if (ModelState.IsValid) { tour.Url = Common.TiegVietKhongDauUrl(Common.NameStandard(tour.Title)); db.Entry(tour).State = EntityState.Modified; db.SaveChanges(); var tourOption = db.TourOptions.Where(x => x.Publish == true).OrderBy(x => x.SortOrder).ToList(); foreach (var item in tourOption) { if (f["tOptions" + item.Id] != "false") { var tOptionRelate = db.TourOptionRelates.Where(x => x.TourId == tour.Id && x.TourOptionId == item.Id).ToList(); if (!tOptionRelate.Any()) { var relate = new TourOptionRelate(); relate.TourId = tour.Id; relate.TourOptionId = item.Id; db.TourOptionRelates.Add(relate); db.SaveChanges(); } } } } return(RedirectToAction("Index")); }
public ActionResult SaveTemplate(TEMPLATEViewModel model, FormCollection collection) { int res = 0; var selectedProjetId = model.listprojetId; var selectedThemeId = model.listThemeId; string ftpdir = ""; if (!string.IsNullOrEmpty(collection["ftpdirs"])) { ftpdir = collection["ftpdirs"]; } if (!string.IsNullOrEmpty(Request.QueryString["currentid"])) { _userId = Guid.Parse(Request.QueryString["currentid"]); Session["currentid"] = Request.QueryString["currentid"]; } else if (!string.IsNullOrEmpty(HttpContext.User.Identity.Name)) { _userId = Guid.Parse(HttpContext.User.Identity.Name); } MODELEViewModel modelVm = new MODELEViewModel(); modelVm = new Modeles().GetDetailsModele((Guid)Session["modeleId"]); Session["Menu"] = "1"; var html = RenderViewAsString("Home", modelVm); TEMPLATE newtemplate = new TEMPLATE(); newtemplate.dateCreation = DateTime.Now; newtemplate.url = model.url; newtemplate.ftpUser = model.ftpUser; newtemplate.ftpPassword = model.ftpPassword; newtemplate.modeleId = (Guid)Session["modeleId"]; newtemplate.ip = model.ip; newtemplate.userId = _userId; newtemplate.PROJET = db.PROJETS.Find(selectedProjetId); newtemplate.projetId = selectedProjetId; var selectedTheme = model.THEME.theme_name; THEME currentTheme = db.THEMES.FirstOrDefault(x => x.theme_name.Contains(selectedTheme.TrimEnd())); if (currentTheme == null) { currentTheme = new THEME { themeId = Guid.NewGuid(), theme_name = selectedTheme }; db.THEMES.Add(currentTheme); db.SaveChanges(); } newtemplate.THEME = currentTheme; newtemplate.themeId = currentTheme.themeId; newtemplate.html = html; var results = newtemplate.templateId = Guid.NewGuid(); db.TEMPLATEs.Add(newtemplate); try { res = db.SaveChanges(); if (res > 0) { var templateName = Session["TemplateName"].ToString(); int nb_menu = (Session["nbmenu"] == null) ? 1 : int.Parse(Session["nbmenu"].ToString()); CreateFiles(nb_menu, html); //Send Ftp string pathParent = Server.MapPath("~/Themes/" + templateName); string pathCss = pathParent + "/css/"; string pathImg = pathParent + "/img"; string pathJs = pathParent + "/js"; int result = SendToFtp(ftpdir, model.url, model.ftpUser, model.ftpPassword, pathCss, pathParent, pathImg, pathJs); //return new FilePathResult(path, "text/html"); if (result == 0) { return(View("CreateTemplateConfirmation")); } else { return(View("ErrorException")); } } else { return(View("ErrorException")); } } catch (Exception ex) { return(View("ErrorException")); } }
private static void SetFormFileBodyContent(HttpRequest request, string content, string name) { const string fileName = "text.txt"; var fileCollection = new FormFileCollection(); var formCollection = new FormCollection(new Dictionary<string, StringValues>(), fileCollection); var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(content)); request.Form = formCollection; request.ContentType = "multipart/form-data; boundary=----WebKitFormBoundarymx2fSWqWSd0OxQqq"; request.Headers["Content-Disposition"] = $"form-data; name={name}; filename={fileName}"; fileCollection.Add(new FormFile(memoryStream, 0, memoryStream.Length, name, fileName) { Headers = request.Headers }); }
public JsonResult Post(FormCollection form) { var item = form["Blah1"]; return(Json(new { success = true })); }
/// <summary> /// Get the tree url using the default action /// </summary> /// <param name="url"></param> /// <param name="treeType"></param> /// <param name="id"></param> /// <param name="queryStrings"></param> /// <returns></returns> public static string GetTreeUrl(this UrlHelper url, Type treeType, HiveId id, FormCollection queryStrings) { return(url.GetTreeUrl("Index", treeType, id, queryStrings)); }
public ActionResult CriarUsuario(FormCollection _form) { List <String> mensagensErro = new List <String>(); int idUsuario = 0; string retorno = "CriarUsuario"; Usuario usuario = new Usuario(); DateTime dataNascimento = new DateTime(); DateTime dataMinima = DateTime.Parse("01/01/1900"); string nasc = _form["txtDataNascimento"]; if (DateTime.TryParse(nasc, out dataNascimento)) { dataNascimento = DateTime.Parse(_form["txtDataNascimento"]); } StringBuilder mensagemInconsistencia = new StringBuilder(); if (string.IsNullOrEmpty(_form["txtUsuario"])) { mensagemInconsistencia.Append("Usuário não preenchido. "); } if (string.IsNullOrEmpty(_form["txtCpf"])) { mensagemInconsistencia.Append("Cpf não preenchido. "); } if (string.IsNullOrEmpty(_form["txtTelefone"])) { mensagemInconsistencia.Append("Telefone celular não preenchido. "); } if (string.IsNullOrEmpty(_form["txtDataNascimento"])) { mensagemInconsistencia.Append("Data de nascimento não preenchida. "); } // Verifica se o cliente tem mais de 18 anos else if ((new DateTime(1, 1, 1) + (DateTime.Today - dataNascimento)).Year - 1 < 18) { mensagemInconsistencia.Append("Data de nascimento (Idade mínima 18 anos). "); } if (string.IsNullOrEmpty(_form["txtEmail"])) { mensagemInconsistencia.Append("E-mail não preenchido. "); } if (string.IsNullOrEmpty(_form["txtPassword"]) || (_form["txtPassword"]).Length < 6) { mensagemInconsistencia.Append("Senha não preenchida. "); } else { string txtUsuario = _form["txtUsuario"]; string txtLogin = _form["txtEmail"]; string txtEmail = _form["txtEmail"]; string txtPassword = _form["txtPassword"]; string txtDataNascimento = _form["txtDataNascimento"]; string txtTelefone = _form["txtTelefone"]; txtTelefone = txtTelefone.Replace("(", "").Replace(")", "").Replace("-", "").Replace(" ", ""); string txtCpf = _form["txtCpf"]; txtCpf = txtCpf.Replace(".", "").Replace("-", ""); usuario.Nome = txtUsuario; usuario.Login = txtLogin; usuario.Email = txtEmail; nasc = _form["txtDataNascimento"]; if (DateTime.TryParse(nasc, out dataNascimento)) { usuario.DataAniversario = DateTime.Parse(_form["txtDataNascimento"]); } usuario.Telefone = txtTelefone; usuario.Cpf_cnpj = txtCpf; usuario.Password = txtPassword; if ((mensagemInconsistencia.Length == 0)) { try { string newPasswordEncrypted = Bcredi.Utils.Utils.Encryption(txtPassword); usuario.Password = newPasswordEncrypted; idUsuario = usuarioService.saveOrUpdate(usuario); ViewBag.TxtLogin = usuario.Login; ViewBag.TxtPassword = txtPassword; ViewBag.TokenResetSenha = usuario.TokenResetSenha; TempData["TempDataLogin"] = usuario.Login; TempData["TempDataPassword"] = txtPassword; TempData["TempDataResetSenha"] = usuario.TokenResetSenha; ViewBag.MensagemUsuarioCriado = "Usuário criado com sucesso!"; retorno = "CadastroRealizado"; //return RedirectToAction("CadastroRealizado", "Usuario"); } catch (Exception ex) { mensagensErro.Add("Não foi possível criar o usuário, tente novamente. " + ex); } return(View(retorno)); } else { ViewBag.mensagemInconsistencia = mensagemInconsistencia; return(View(usuario)); } } return(View(usuario)); }
//儲存日報數量紀錄 public void saveItemRow(FormCollection f) { SYS_USER u = (SYS_USER)Session["user"]; log.Debug("projectId=" + Request["txtProjectId"] + ",prjUid=" + Request["txtPrjUid"] + ",ReportId=" + Request["reportID"]); log.Debug("form Data ItemId=" + Request["planItemId"]); log.Debug("form Data Qty=planItemQty" + Request["planItemQty"]); string projectid = Request["txtProjectId"]; int prjuid = int.Parse(Request["txtPrjUid"]); string strWeather = Request["selWeather"]; string strSummary = Request["txtSummary"]; string strSenceUser = Request["txtSenceUser"]; string strSupervision = Request["txtSupervision"]; string strOwner = Request["txtOwner"]; string strRptDate = Request["reportDate"]; DailyReport newDailyRpt = new DailyReport(); PLAN_DALIY_REPORT RptHeader = new PLAN_DALIY_REPORT(); RptHeader.PROJECT_ID = projectid; RptHeader.WEATHER = strWeather; RptHeader.SUMMARY = strSummary; RptHeader.SCENE_USER_NAME = strSenceUser; RptHeader.SUPERVISION_NAME = strSupervision; RptHeader.OWNER_NAME = strOwner; newDailyRpt.dailyRpt = RptHeader; RptHeader.REPORT_DATE = DateTime.Parse(strRptDate); //取得日報編號 SerialKeyService snService = new SerialKeyService(); if (null == Request["reportID"] || "" == Request["reportID"]) { RptHeader.REPORT_ID = snService.getSerialKey(planService.KEY_ID); RptHeader.CREATE_DATE = DateTime.Now; RptHeader.CREATE_USER_ID = u.USER_ID; } else { RptHeader.REPORT_ID = Request["ReportID"]; RptHeader.CREATE_DATE = DateTime.Parse(Request["txtCreateDate"]); RptHeader.CREATE_USER_ID = Request["txtCreateUserId"]; RptHeader.MODIFY_DATE = DateTime.Now; RptHeader.MODIFY_USER_ID = u.USER_ID; } //建立專案任務資料 (結構是支援多項任務,僅先使用一筆) newDailyRpt.lstRptTask = new List<PLAN_DR_TASK>(); PLAN_DR_TASK RptTask = new PLAN_DR_TASK(); RptTask.PROJECT_ID = projectid; RptTask.PRJ_UID = prjuid; RptTask.REPORT_ID = RptHeader.REPORT_ID; newDailyRpt.lstRptTask.Add(RptTask); //處理料件 newDailyRpt.lstRptItem = new List<PLAN_DR_ITEM>(); if (null != Request["planItemId"]) { string[] aryPlanItem = Request["planItemId"].Split(','); string[] aryPlanItemQty = Request["planItemQty"].Split(','); string[] aryAccumulateQty = Request["accumulateQty"].Split(','); log.Debug("count ItemiD=" + aryPlanItem.Length + ",qty=" + aryPlanItemQty.Length); newDailyRpt.lstRptItem = new List<PLAN_DR_ITEM>(); for (int i = 0; i < aryPlanItem.Length; i++) { PLAN_DR_ITEM item = new PLAN_DR_ITEM(); item.PLAN_ITEM_ID = aryPlanItem[i]; item.PROJECT_ID = projectid; item.REPORT_ID = RptHeader.REPORT_ID; if ("" != aryPlanItemQty[i]) { item.FINISH_QTY = decimal.Parse(aryPlanItemQty[i]); } if ("" != aryAccumulateQty[i]) { item.LAST_QTY = decimal.Parse(aryAccumulateQty[i]); } newDailyRpt.lstRptItem.Add(item); } } //處理出工資料 newDailyRpt.lstWokerType4Show = new List<PLAN_DR_WORKER>(); if (null != Request["txtSupplierId"]) { ///出工廠商 string[] arySupplier = Request["txtSupplierId"].Split(','); ///出工人數 string[] aryWorkerQty = Request["txtWorkerQty"].Split(','); ///備註 string[] aryRemark = Request["txtRemark"].Split(','); for (int i = 0; i < arySupplier.Length; i++) { PLAN_DR_WORKER item = new PLAN_DR_WORKER(); item.REPORT_ID = RptHeader.REPORT_ID; item.SUPPLIER_ID = arySupplier[i]; log.Debug("Supplier Info=" + item.SUPPLIER_ID); if ("" != aryWorkerQty[i].Trim()) { item.WORKER_QTY = decimal.Parse(aryWorkerQty[i]); newDailyRpt.lstWokerType4Show.Add(item); } item.REMARK = aryRemark[i]; } log.Debug("count WorkerD=" + arySupplier.Length); } //處理點工資料 newDailyRpt.lstTempWoker4Show = new List<PLAN_DR_TEMPWORK>(); if (null != Request["txtTempWorkSupplierId"]) { string[] aryTempSupplier = Request["txtTempWorkSupplierId"].Split(','); string[] aryTempWorkerQty = Request["txtTempWorkerQty"].Split(','); string[] aryTempChargeSupplier = Request["txtChargeSupplierId"].Split(','); string[] aryTempWarkRemark = Request["txtTempWorkRemark"].Split(','); string[] aryDoc = Request["doc"].Split(','); for (int i = 0; i < aryTempSupplier.Length; i++) { PLAN_DR_TEMPWORK item = new PLAN_DR_TEMPWORK(); item.REPORT_ID = RptHeader.REPORT_ID; item.SUPPLIER_ID = aryTempSupplier[i]; item.CHARGE_ID = aryTempChargeSupplier[i]; ///處理工人名單檔案 log.Debug("File Count=" + Request.Files.Count); if (Request.Files[i].ContentLength > 0) { //存檔路徑 var fileName = Path.GetFileName(Request.Files[i].FileName); string reportFolder = ContextService.strUploadPath + "\\" + projectid + "\\DailyReport\\"; //check 資料夾是否存在 string folder = reportFolder + RptHeader.REPORT_ID; ZipFileCreator.CreateDirectory(folder); var path = Path.Combine(folder, fileName); Request.Files[i].SaveAs(path); item.DOC = "DailyReport\\" + RptHeader.REPORT_ID + "\\" + fileName; log.Debug("Upload Sign List File:" + Request.Files[i].FileName); } else { item.DOC = aryDoc[i]; log.Error("Not Upload Sign List File!Exist File=" + item.DOC); } log.Debug("Supplier Info=" + item.SUPPLIER_ID); if ("" != aryTempWorkerQty[i].Trim()) { item.WORKER_QTY = decimal.Parse(aryTempWorkerQty[i]); newDailyRpt.lstTempWoker4Show.Add(item); } item.REMARK = aryTempWarkRemark[i]; } } //處理機具資料 newDailyRpt.lstRptWorkerAndMachine = new List<PLAN_DR_WORKER>(); string[] aryMachineType = f["MachineKeyid"].Split(','); string[] aryMachineQty = f["planMachineQty"].Split(','); for (int i = 0; i < aryMachineType.Length; i++) { PLAN_DR_WORKER item = new PLAN_DR_WORKER(); item.REPORT_ID = RptHeader.REPORT_ID; item.WORKER_TYPE = "MACHINE"; item.PARA_KEY_ID = aryMachineType[i]; if ("" != aryMachineQty[i]) { item.WORKER_QTY = decimal.Parse(aryMachineQty[i]); newDailyRpt.lstRptWorkerAndMachine.Add(item); } } log.Debug("count MachineD=" + f["MachineKeyid"] + ",WorkerQty=" + f["planMachineQty"]); //處理重要事項資料 newDailyRpt.lstRptNote = new List<PLAN_DR_NOTE>(); string[] aryNote = f["planNote"].Split(','); for (int i = 0; i < aryNote.Length; i++) { PLAN_DR_NOTE item = new PLAN_DR_NOTE(); item.REPORT_ID = RptHeader.REPORT_ID; if ("" != aryNote[i].Trim()) { item.SORT = i + 1; item.REMARK = aryNote[i].Trim(); newDailyRpt.lstRptNote.Add(item); } } //註記任務是否完成 if (null == Request["taskDone"]) { newDailyRpt.isDoneFlag = false; } else { newDailyRpt.isDoneFlag = true; } log.Debug("count Note=" + f["planNote"]); string msg = planService.createDailyReport(newDailyRpt); Response.Redirect("~/ProjectPlan/dailyReport/" + projectid); //ProjectPlan/dailyReport/P00061 }
public ActionResult AlterarSenha(FormCollection _form) { Usuario usuario = new Usuario(); var usuarioLogado = Session["usuario"] as Usuario; string txtSenhaAtual = _form["txtSenhaAtual"]; string txtSenhaNova = _form["txtSenha"]; string txtSenhaConfirmar = _form["txtSenhaConfirmar"]; if (txtSenhaAtual == "" || txtSenhaNova == "" || txtSenhaConfirmar == "") { ViewBag.MensagemAlterarSenhaFail = "Preencha todos os campos"; usuario = usuarioLogado; return(View(usuario)); } else if (txtSenhaConfirmar != txtSenhaNova) { ViewBag.MensagemAlterarSenhaFail = "Senha nova não é igual ao confirmar senha"; usuario = usuarioLogado; return(View(usuario)); } else { if (Bcredi.Utils.Utils.Decryption(usuarioLogado.Password).Equals(txtSenhaAtual)) { if (txtSenhaAtual == txtSenhaNova) { ViewBag.MensagemAlterarSenhaFail = "A senha nova não pode ser igual a senha antiga"; usuario = usuarioLogado; return(View(usuario)); } usuario.Password = Bcredi.Utils.Utils.Encryption(_form["txtSenha"]); usuario.Email = usuarioLogado.Email; bool response = usuarioService.AlterarSenhaUpdate(usuario); if (response == true) { ViewBag.MensagemAlterarSenhaOK = "Sua senha foi alterada com sucesso!"; } else { ViewBag.MensagemAlterarSenhaFail = "Não foi possível alterar sua senha!"; } } else { usuario.Email = usuarioLogado.Email; ViewBag.MensagemAlterarSenhaFail = "Senha atual incorreta!"; } } usuario = usuarioLogado; return(View(usuario)); }
public void GetValue_KeyDoesNotExist_ReturnsNull() { // Arrange FormCollection formCollection = new FormCollection(); // Act ValueProviderResult vpResult = formCollection.GetValue(""); // Assert Assert.Null(vpResult); }
public ActionResult SelecionarDepto(FormCollection formcollection) { var departamento = formcollection["Departamento"]; string[] recorte = departamento.Split(','); if (formcollection.Count >= 9) { Paciente paciente = new Paciente() { Nombre = formcollection["Nombre"], Apellido = formcollection["Apellido"], CUI = long.Parse(formcollection["CUI"]), Edad = int.Parse(formcollection["Edad"]), Munucipio = formcollection["Munucipio"], Departamento = recorte[0], DescripcionDePosibleContagio = formcollection["Descripcion"] }; paciente.Sintomas = new List <string>(); #region sintomas if (formcollection["Fiebre"] != null) { paciente.Sintomas.Add(formcollection["Fiebre"]); } if (formcollection["Cansancio"] != null) { paciente.Sintomas.Add(formcollection["Cansancio"]); } if (formcollection["Tos seca"] != null) { paciente.Sintomas.Add(formcollection["Tos seca"]); } if (formcollection["Dolor corporal"] != null) { paciente.Sintomas.Add(formcollection["Dolor corporal"]); } if (formcollection["Congestion nasal"] != null) { paciente.Sintomas.Add(formcollection["Congestion nasal"]); } if (formcollection["Secrecion nasal"] != null) { paciente.Sintomas.Add(formcollection["Secrecion nasal"]); } if (formcollection["Dolor de garganta"] != null) { paciente.Sintomas.Add(formcollection["Dolor de garganta"]); } #endregion if (paciente.Guardar()) { paciente = new Paciente(); ViewBag.Confirmacion = "Paciente registrado con exito"; return(View("Registrar", paciente)); } else { paciente = new Paciente(); ViewBag.Error = "No se ha podido registrar al paciente"; return(View("Registrar", paciente)); } } else { Paciente paciente = new Paciente() { Nombre = formcollection["Nombre"], Apellido = formcollection["Apellido"], CUI = long.Parse(formcollection["CUI"]), Edad = int.Parse(formcollection["Edad"]) }; paciente.Departamento = recorte[0]; paciente.ObtenerMunicipios(paciente.Departamento); return(View("Registrar", paciente)); } }
public ActionResult login(FormCollection collection) { return(RedirectToAction("Index", "Home")); }
public ActionResult SaveEditTemplate(Guid idTemplate, TEMPLATEViewModel model, FormCollection collection) { var hash = idTemplate; TEMPLATE template = db.TEMPLATEs.Find(hash); template.MODELE.site_url = model.MODELE.site_url; template.url = model.url; template.ftpUser = model.ftpUser; template.ftpPassword = model.ftpPassword; template.ip = model.ip; int result = db.SaveChanges(); if (result > 0) { return(View("EditTemplateConfirmation")); } else { return(View("ErrorException")); } }
public ActionResult UserRoles(string id, FormCollection roleItems) { try { if (roleItems != null) { Dictionary <string, object> roleItemValues = new Dictionary <string, object>(); List <string> userRoles = null; foreach (string key in roleItems.Keys) { if (key.ToLower() != "id") { roleItemValues.Add(key, roleItems.GetValues(key)); } } if (roleItemValues != null) { userRoles = new List <string>(); foreach (var key in roleItemValues.Keys) { if ((roleItemValues[key] != null) && (roleItemValues[key] as string[]).Length >= 1) { if ((roleItemValues[key] as string[])[0].ToLower() == "true") { userRoles.Add(key); } } } } var userManager = new UserManager <IdentityUser>(new UserStore <IdentityUser>(new IdentityDbContext(Platform.DAAS.OData.Security.ModuleConfiguration.DefaultIdentityStoreConnectionName))); IList <string> currentUserRoles = userManager.GetRoles(id); var securityManager = Provider.SecurityManager(); List <object> setRoleResults = new List <object>(); if ((currentUserRoles != null) && (currentUserRoles.Count > 0)) { IdentityResult identityResult = userManager.RemoveFromRoles(id, currentUserRoles.ToArray()); setRoleResults.Add(identityResult); } if (userRoles != null) { IdentityRole identityRole = null; var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new IdentityDbContext(Platform.DAAS.OData.Security.ModuleConfiguration.DefaultIdentityStoreConnectionName))); foreach (var role in userRoles) { identityRole = roleManager.FindById(role); if (identityRole != null) { setRoleResults.Add(securityManager.AddActorToRole(id, identityRole.Name)); //Add the user to each of the roles selected. } } } } return(RedirectToAction("Details", new { id = id }));//return RedirectToAction("Index"); } catch (Exception ex) { Provider.ExceptionHandler().HandleException(ex); return(View()); } }
public ActionResult Create(FormCollection collection) { try { int i = 1; string yangxuzhi = ""; for (i = 1; i <= 7; i++) { yangxuzhi = yangxuzhi + collection[i.ToString()] + ","; } string yinxuzhi = ""; for (i = 8; i <= 15; i++) { yinxuzhi = yinxuzhi + collection[i.ToString()] + ","; } string qixuzhi = ""; for (i = 16; i <= 23; i++) { qixuzhi = qixuzhi + collection[i.ToString()] + ","; } string tanshizhi = ""; for (i = 24; i <= 31; i++) { tanshizhi = tanshizhi + collection[i.ToString()] + ","; } string shirezhi = ""; for (i = 32; i <= 38; i++) { shirezhi = shirezhi + collection[i.ToString()] + ","; } string xueyuzhi = ""; for (i = 39; i <= 45; i++) { xueyuzhi = xueyuzhi + collection[i.ToString()] + ","; } string qiyuzhi = ""; for (i = 46; i <= 52; i++) { qiyuzhi = qiyuzhi + collection[i.ToString()] + ","; } string tebingzhi = ""; for (i = 53; i <= 59; i++) { tebingzhi = tebingzhi + collection[i.ToString()] + ","; } string pinghezhi = ""; for (i = 60; i <= 67; i++) { pinghezhi = pinghezhi + collection[i.ToString()] + ","; } string reslut = ""; for (i = 1; i <= 67; i++) { reslut = reslut + collection[i.ToString()] + ","; } string CustomerId = collection["CustomerId"]; return(RedirectToAction("Index", "Tizhi", new { id = reslut, cid = CustomerId })); } catch { return(View()); } }
public async Task <ActionResult> Edit(string id, FormCollection collection, HttpPostedFileBase headImageFile) { try { // TODO: Add update logic here var userManager = new UserManager <IdentityUser>(new UserStore <IdentityUser>(new IdentityDbContext(Platform.DAAS.OData.Security.ModuleConfiguration.DefaultIdentityStoreConnectionName))); var user = userManager.FindById(id); IdentityResult result = null; if (user != null) { //userManager.SetEmail(user.Id, collection["Email"]); user.Email = collection["Email"]; //user.Description = collection["Description"]; result = userManager.Update(user); } //if (result.Succeeded) //{ // var accountManager = Facade.Facade.GetAccountManager(); // var account = accountManager.GetAccount(id); // if (account == null) // { // account = new Core.DomainModel.Account() // { // ID = id, // Name = user.UserName, // FirstName = collection["FirstName"], // LastName = collection["LastName"], // NickName = collection["NickName"], // Organization = collection["Organization"], // Position = collection["Position"], // Gender = int.Parse(collection["Gender"]), // SID = collection["SID"], // Headline = collection["Headline"], // Email = collection["Email"], // Description = collection["Description"] // }; // if (headImageFile != null) // { // var ms = imageSize(headImageFile); // account.HeadImage = new Attachment() // { // Name = String.Format("HdImg-{0}-{1}-{2}", ControllerContext.HttpContext.User.Identity.Name, DateTime.Now.ToString("yyyy-MM-ddTHH-mm-ss"), headImageFile.FileName.Substring((headImageFile.FileName.LastIndexOf("\\") + 1))), //String.Format("HeadImg-{0}-{1}-{2}", ControllerContext.HttpContext.User.Identity.Name, ControllerContext.HttpContext.User.Identity.GetUserId(), Guid.NewGuid().ToString("N")), //Request.Files[0].FileName, // Bytes = new byte[ms.Length], // Size = ms.Length, // CreationTime = DateTime.Now // }; // using (headImageFile.InputStream) // { // account.HeadImage.Bytes = ms.ToArray(); // } // if (Facade.Global.Should("DoRemoteFileUpload")) // { // this.DoRemoteFileUpload(account.HeadImage); // } // else // { // accountManager.SetImage(account.HeadImage, account.HeadImage.Bytes); // } // } // accountManager.AddAccount(account); // } // else // { // account.Name = user.UserName; // account.FirstName = collection["FirstName"]; // account.LastName = collection["LastName"]; // account.NickName = collection["NickName"]; // account.Organization = collection["Organization"]; // account.Position = collection["Position"]; // account.Gender = int.Parse(collection["Gender"]); // account.SID = collection["SID"]; // account.Headline = collection["Headline"]; // account.Email = collection["Email"]; // account.Description = collection["Description"]; // if (headImageFile != null) // { // var ms = imageSize(headImageFile); // account.HeadImage = new Attachment() // { // Name = String.Format("HdImg-{0}-{1}-{2}", ControllerContext.HttpContext.User.Identity.Name, DateTime.Now.ToString("yyyy-MM-ddTHH-mm-ss"), headImageFile.FileName.Substring((headImageFile.FileName.LastIndexOf("\\") + 1))), //String.Format("HeadImg-{0}-{1}-{2}", ControllerContext.HttpContext.User.Identity.Name, ControllerContext.HttpContext.User.Identity.GetUserId(), Guid.NewGuid().ToString("N")), //Request.Files[0].FileName, // Bytes = new byte[ms.Length], // Size = ms.Length, // CreationTime = DateTime.Now // }; // using (headImageFile.InputStream) // { // account.HeadImage.Bytes = ms.ToArray(); // } // if (Facade.Global.Should("DoRemoteFileUpload")) // { // this.DoRemoteFileUpload(account.HeadImage); // } // else // { // accountManager.SetImage(account.HeadImage, account.HeadImage.Bytes); // } // } // accountManager.SetAccount(id, account); // } //return RedirectToAction("Index"); // return RedirectToAction("Details", new { id = id }); //} //return RedirectToAction("Index"); return(RedirectToAction("Details", new { id = id })); } catch (Exception ex) { Provider.ExceptionHandler().HandleException(ex); return(View()); } }
public void StopInk() { FormCollection.Close(); FormDisplay.Close(); FormButtonHitter.Close(); //FormCollection.Dispose(); //FormDisplay.Dispose(); GC.Collect(); FormCollection = null; FormDisplay = null; }
/// <summary> /// Returns the full unique url for a Tree based on it's type /// </summary> /// <param name="url"></param> /// <param name="action"></param> /// <param name="treeType"></param> /// <param name="id"></param> /// <param name="queryStrings"></param> /// <returns></returns> public static string GetTreeUrl(this UrlHelper url, string action, Type treeType, HiveId id, FormCollection queryStrings) { if (!treeType.GetCustomAttributes(typeof(TreeAttribute), false).Any()) { throw new InvalidCastException("The controller type specified is not of type TreeController"); } return(url.GetTreeUrl(action, id, UmbracoController.GetControllerId <TreeAttribute>(treeType), queryStrings)); }
/// <summary> /// Returns the full unique url for a Tree /// </summary> /// <param name="url"></param> /// <param name="action"></param> /// <param name="id"></param> /// <param name="treeId"></param> /// <param name="queryStrings"></param> /// <returns></returns> public static string GetTreeUrl(this UrlHelper url, string action, HiveId id, Guid treeId, FormCollection queryStrings) { var treeMetaData = DependencyResolver.Current.GetService <ComponentRegistrations>() .TreeControllers .Where(x => x.Metadata.Id == treeId) .SingleOrDefault(); if (treeMetaData == null) { throw new InvalidOperationException("Could not find the tree controller with id " + treeId); } var area = url.GetBackOfficeArea(); //now, need to figure out what area this tree belongs too... var pluginDefition = treeMetaData.Metadata.PluginDefinition; if (pluginDefition.HasRoutablePackageArea()) { area = pluginDefition.PackageName; } return(url.Action(action, treeMetaData.Metadata.ControllerName, new { area, id = GetIdVal(id), treeId = treeId.ToString("N") }) + "?" + queryStrings.ToQueryString()); }
public static AppraisalViewFormModel UpdateAppraisalBeforeSaving(FormCollection form, AppraisalViewFormModel appraisal, DealershipViewModel dealer, string userName) { string additionalPackages = form["txtFactoryPackageOption"]; string additionalOptions = form["txtNonInstalledOption"]; if (!String.IsNullOrEmpty(additionalPackages)) { string[] filterOptions = CommonHelper.GetArrayFromStringWithoutMoney(additionalPackages); additionalPackages = ""; if (filterOptions.Any()) { foreach (string tmp in filterOptions) { int number; bool flag = int.TryParse(tmp, out number); if (!flag) { additionalPackages += tmp.Trim() + ","; } } } if (!String.IsNullOrEmpty(additionalPackages)) { if (additionalPackages.Substring(additionalPackages.Length - 1).Equals(",")) { additionalPackages = additionalPackages.Substring(0, additionalPackages.Length - 1).Trim(); } } } if (!String.IsNullOrEmpty(additionalOptions)) { string[] filterOptions = CommonHelper.GetArrayFromStringWithoutMoney(additionalOptions); additionalOptions = ""; if (filterOptions.Any()) { foreach (string tmp in filterOptions) { int number; bool flag = int.TryParse(tmp, out number); if (!flag) { additionalOptions += tmp.Trim() + ","; } } } if (!String.IsNullOrEmpty(additionalOptions)) { if (additionalOptions.Substring(additionalOptions.Length - 1).Equals(",")) { additionalOptions = additionalOptions.Substring(0, additionalOptions.Length - 1).Trim(); } } } if (!String.IsNullOrEmpty(appraisal.SelectedTrim) && appraisal.SelectedTrim.Contains("|")) { var result = appraisal.SelectedTrim.Split('|'); if (result.Count() > 1) { appraisal.ChromeStyleId = result[0]; //appraisal.SelectedTrim = result[1]; var trim = result[1]; appraisal.SelectedTrim = trim.Equals("Base/Other Trims") ? (appraisal.CusTrim ?? String.Empty) : trim; } } else if (!String.IsNullOrEmpty(appraisal.CusTrim)) { appraisal.SelectedTrim = appraisal.CusTrim; appraisal.ChromeStyleId = null; } appraisal.SelectedPackageOptions = additionalPackages; appraisal.SelectedFactoryOptions = additionalOptions; appraisal.Title = appraisal.ModelYear + " " + appraisal.Make + " " + appraisal.AppraisalModel + (!String.IsNullOrEmpty(appraisal.SelectedTrim) ? " " + appraisal.SelectedTrim : ""); appraisal.SalePrice = CommonHelper.RemoveSpecialCharactersForMsrp(appraisal.MSRP); appraisal.MSRP = CommonHelper.RemoveSpecialCharactersForMsrp(appraisal.MSRP); appraisal.AppraisalBy = userName; appraisal.Mileage = appraisal.Mileage ?? "0"; appraisal.CarFaxDealerId = dealer.CarFax; try { appraisal.CarFax = CarFaxHelper.ConvertXmlToCarFaxModelAndSave(appraisal.VinNumber, dealer.CarFax, dealer.CarFaxPassword); } catch (Exception) { appraisal.CarFax = new CarFaxViewModel() { Success = false }; } appraisal.BB = BlackBookService.GetFullReport(appraisal.VinNumber, appraisal.Mileage, dealer.State); if (!String.IsNullOrEmpty(appraisal.SelectedExteriorColorValue) && appraisal.SelectedExteriorColorValue.Trim().Equals("Other Colors") && !String.IsNullOrEmpty(appraisal.CusExteriorColor)) { appraisal.SelectedExteriorColorValue = appraisal.CusExteriorColor; } if (!String.IsNullOrEmpty(appraisal.SelectedInteriorColor) && appraisal.SelectedInteriorColor.Equals("Other Colors") && !String.IsNullOrEmpty(appraisal.CusInteriorColor)) { appraisal.SelectedInteriorColor = appraisal.CusInteriorColor; } return(appraisal); }
public ActionResult SaveTheme(MODELEViewModel model, HttpPostedFileBase logoUrl, HttpPostedFileBase menu1_paragraphe1_photoUrl, HttpPostedFileBase menu1_paragraphe2_photoUrl, HttpPostedFileBase menu2_paragraphe1_photoUrl, HttpPostedFileBase menu2_paragraphe2_photoUrl, HttpPostedFileBase menu3_paragraphe1_photoUrl, HttpPostedFileBase menu3_paragraphe2_photoUrl, HttpPostedFileBase menu4_paragraphe1_photoUrl, HttpPostedFileBase menu4_paragraphe2_photoUrl, HttpPostedFileBase photoALaUneUrl, HttpPostedFileBase favicone, FormCollection collection) { var templateName = Session["TemplateName"].ToString(); if (!string.IsNullOrEmpty(collection["nbmenu"])) { string nbmenu = collection["nbmenu"]; Session["nbmenu"] = nbmenu; } string path = Server.MapPath("~/Themes/" + templateName); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } else { DeleteFiles(path); } string pathimg = Server.MapPath("~/Themes/" + templateName + "/img/"); DeleteFiles(pathimg); MODELE newmodel = new MODELE(); newmodel.logoUrl = SavePhoto(logoUrl, templateName); newmodel.favicone = SaveFavicon(favicone, templateName); /*Menu 1 */ newmodel.menu1_titre = model.menu1_titre; newmodel.menu1_paragraphe1_titre = model.menu1_paragraphe1_titre; newmodel.menu1_paragraphe1_photoUrl = SavePhoto(menu1_paragraphe1_photoUrl, templateName); newmodel.menu1_p1_alt = AltPhoto(menu1_paragraphe1_photoUrl, templateName); newmodel.menu1_contenu1 = model.menu1_contenu1; newmodel.menu1_paragraphe2_titre = model.menu1_paragraphe2_titre; newmodel.menu1_paragraphe2_photoUrl = SavePhoto(menu1_paragraphe2_photoUrl, templateName); newmodel.menu1_p2_alt = AltPhoto(menu1_paragraphe2_photoUrl, templateName); newmodel.menu1_contenu2 = model.menu1_contenu2; newmodel.menu1_meta_description = model.menu1_meta_description; /*Menu 2 */ newmodel.menu2_titre = model.menu2_titre; newmodel.menu2_paragraphe1_titre = model.menu2_paragraphe1_titre; newmodel.menu2_paragraphe2_titre = model.menu2_paragraphe2_titre; newmodel.menu2_paragraphe1_photoUrl = SavePhoto(menu2_paragraphe1_photoUrl, templateName); newmodel.menu2_p1_alt = AltPhoto(menu2_paragraphe1_photoUrl, templateName); newmodel.menu2_paragraphe2_photoUrl = SavePhoto(menu2_paragraphe2_photoUrl, templateName); newmodel.menu2_p2_alt = AltPhoto(menu2_paragraphe2_photoUrl, templateName); newmodel.menu2_contenu1 = model.menu2_contenu1; newmodel.menu2_contenu2 = model.menu2_contenu2; newmodel.menu2_meta_description = model.menu2_meta_description; /*Menu 3 */ newmodel.menu3_titre = model.menu3_titre; newmodel.menu3_paragraphe1_titre = model.menu3_paragraphe1_titre; newmodel.menu3_paragraphe2_titre = model.menu3_paragraphe2_titre; newmodel.menu3_paragraphe1_photoUrl = SavePhoto(menu3_paragraphe1_photoUrl, templateName); newmodel.menu3_p1_alt = AltPhoto(menu3_paragraphe1_photoUrl, templateName); newmodel.menu3_paragraphe2_photoUrl = SavePhoto(menu3_paragraphe2_photoUrl, templateName); newmodel.menu3_p2_alt = AltPhoto(menu3_paragraphe2_photoUrl, templateName); newmodel.menu3_contenu1 = model.menu3_contenu1; newmodel.menu3_contenu2 = model.menu3_contenu2; newmodel.menu3_meta_description = model.menu3_meta_description; /*Menu 4 */ newmodel.menu4_titre = model.menu4_titre; newmodel.menu4_paragraphe1_titre = model.menu4_paragraphe1_titre; newmodel.menu4_paragraphe2_titre = model.menu4_paragraphe2_titre; newmodel.menu4_paragraphe1_photoUrl = SavePhoto(menu4_paragraphe1_photoUrl, templateName); newmodel.menu4_p1_alt = AltPhoto(menu4_paragraphe1_photoUrl, templateName); newmodel.menu4_paragraphe2_photoUrl = SavePhoto(menu4_paragraphe2_photoUrl, templateName); newmodel.menu4_p2_alt = AltPhoto(menu4_paragraphe2_photoUrl, templateName); newmodel.menu4_contenu1 = model.menu4_contenu1; newmodel.menu4_contenu2 = model.menu4_contenu2; newmodel.menu4_meta_description = model.menu4_meta_description; /*A la une*/ newmodel.photoALaUneUrl = SavePhoto(photoALaUneUrl, templateName); newmodel.site_url = model.site_url; newmodel.modeleId = Guid.NewGuid(); Session["modeleId"] = newmodel.modeleId; db.MODELEs.Add(newmodel); try { int res = db.SaveChanges(); if (res > 0) { Templates val = new Templates(); TEMPLATEViewModel templateVm = new TEMPLATEViewModel(); templateVm.ListProjet = val.GetListProjetItem(); templateVm.ListTheme = val.GetListThemeItem(); return(View("CreateTemplate", templateVm)); } else { return(View("ErrorException")); } } catch (Exception ex) { return(View("Theme1")); } }
public ActionResult EditPost(int id, string category, string type, [DefaultValue(-1)] int filterId, FormCollection formCollection) { var profile = _profileService.GetImageProfile(id); var filter = _processingManager.DescribeFilters().SelectMany(x => x.Descriptors).FirstOrDefault(x => x.Category == category && x.Type == type); var model = new FilterEditViewModel(); TryUpdateModel(model); // validating form values _formManager.Validate(new ValidatingContext { FormName = filter.Form, ModelState = ModelState, ValueProvider = ValueProvider }); if (ModelState.IsValid) { var filterRecord = profile.Filters.FirstOrDefault(f => f.Id == filterId); // add new filter record if it's a newly created filter if (filterRecord == null) { filterRecord = new FilterRecord { Category = category, Type = type, Position = profile.Filters.Count }; profile.Filters.Add(filterRecord); } var dictionary = formCollection.AllKeys.ToDictionary(key => key, formCollection.Get); // save form parameters filterRecord.State = FormParametersHelper.ToString(dictionary); filterRecord.Description = model.Description; // set profile as updated profile.ModifiedUtc = DateTime.UtcNow; profile.FileNames.Clear(); _signals.Trigger("MediaProcessing_Saved_" + profile.Name); return(RedirectToAction("Edit", "Admin", new { id })); } // model is invalid, display it again var form = _formManager.Build(filter.Form); _formManager.Bind(form, formCollection); var viewModel = new FilterEditViewModel { Id = id, Description = model.Description, Filter = filter, Form = form }; return(View(viewModel)); }
public ActionResult GenerarLlavesRSA(FormCollection collection) { try { var p = int.Parse(collection["P"]); var q = int.Parse(collection["Q"]); if (p > 16 && q > 16) { Data.Instancia.ExisteError = false; if (!Data.Instancia.RSA_Cif.GeneradorLlaves.EsPrimo(p) || !Data.Instancia.RSA_Cif.GeneradorLlaves.EsPrimo(q)) { Data.Instancia.ExisteError = true; Data.Instancia.Error = 1; } else if (Data.Instancia.RSA_Cif.GeneradorLlaves.MCD(p, q) != 1 ) //Se está validando de P y Q sean coprimos { Data.Instancia.ExisteError = true; Data.Instancia.Error = 2; } if (Data.Instancia.ExisteError != true) { var path = Data.Instancia.RutaAbsolutaServer; Data.Instancia.RSA_Cif.GeneradorLlaves.AsignarRutaRaiz(path); if (Data.Instancia.RSA_Cif.GeneradorLlaves.GenerarClaves(p, q)) { Data.Instancia.GenerarLlaves = false; Data.Instancia.DescargarLlaves = true; Data.Instancia.ExisteError = false; Data.Instancia.SeCargoArchivoLlave = true; } else { Data.Instancia.GenerarLlaves = true; Data.Instancia.DescargarLlaves = false; Data.Instancia.ExisteError = true; } } } else { Data.Instancia.ExisteError = true; Data.Instancia.Error = 0; } return(RedirectToAction("IndexRSA")); } catch (Exception exception) { Data.Instancia.ExisteError = true; if (exception.Message == "Inverso modular") { Data.Instancia.Error = 4; } return(View("IndexRSA")); } }
public int CurrentPen = 1; // defaut pen public Root() { SetDefaultPens(); SetDefaultConfig(); ReadOptions("pens.ini"); ReadOptions("config.ini"); trayMenu = new ContextMenu(); trayMenu.MenuItems.Add("About", OnAbout); trayMenu.MenuItems.Add("Pen Configurations", OnPenSetting); trayMenu.MenuItems.Add("Options", OnOptions); trayMenu.MenuItems.Add("-"); trayMenu.MenuItems.Add("Exit", OnExit); Size size = SystemInformation.SmallIconSize; trayIcon = new NotifyIcon(); trayIcon.Text = "gInk"; if (WhiteTrayIcon) trayIcon.Icon = new Icon(gInk.Properties.Resources.icon_white, size); else trayIcon.Icon = new Icon(gInk.Properties.Resources.icon_red, size); trayIcon.ContextMenu = trayMenu; trayIcon.Visible = true; trayIcon.MouseClick += TrayIcon_Click; int modifier = 0; if (Hotkey_Control) modifier |= 0x2; if (Hotkey_Alt) modifier |= 0x1; if (Hotkey_Shift) modifier |= 0x4; if (Hotkey_Win) modifier |= 0x8; if (modifier != 0) RegisterHotKey(IntPtr.Zero, 0, modifier, Hotkey); TestMessageFilter mf = new TestMessageFilter(this); Application.AddMessageFilter(mf); FormCollection = null; FormDisplay = null; }
public async Task <ActionResult> PayeezyResponse(FormCollection formFields) { ActionResult actionResult; int? impersonatorTenantId; long? impersonatorUserId; int value; long num; bool item = formFields["isRecordPayment"] != null; int num1 = 0; int num2 = 0; int num3 = 0; long num4 = (long)0; if (!item) { string str = formFields["x_cust_id"].ToString(); string[] strArrays = str.Split(new char[] { '|' }); num1 = int.Parse(strArrays[0].ToString()); num2 = int.Parse(strArrays[1].ToString()); num3 = int.Parse(strArrays[2].ToString()); num4 = long.Parse(strArrays[3].ToString()); } else { num1 = int.Parse(formFields["invoiceId"].ToString()); num2 = int.Parse(formFields["x_cust_id"].ToString()); if (this.AbpSession.ImpersonatorTenantId.HasValue) { impersonatorTenantId = this.AbpSession.ImpersonatorTenantId; value = impersonatorTenantId.Value; } else { impersonatorTenantId = this.AbpSession.TenantId; value = impersonatorTenantId.Value; } num3 = value; if (this.AbpSession.ImpersonatorUserId.HasValue) { impersonatorUserId = this.AbpSession.ImpersonatorUserId; num = impersonatorUserId.Value; } else { impersonatorUserId = this.AbpSession.UserId; num = impersonatorUserId.Value; } num4 = num; } Dictionary <string, string> strs = new Dictionary <string, string>(); foreach (object key in formFields.Keys) { strs.Add(key.ToString(), formFields[key.ToString()]); } InvoicePayment invoicePayment = new InvoicePayment() { Id = (long)0, TenantId = num3, InvoiceId = (long)num1, CustomerId = (long)num2, X_Response_Code = strs["x_response_code"].ToString(), X_Response_Reason_Code = strs["x_response_reason_code"].ToString(), X_Response_Reason_Text = strs["x_response_reason_text"].ToString(), X_Auth_Code = strs["x_auth_code"].ToString(), X_Trans_Id = strs["x_trans_id"].ToString(), X_Description = strs["x_description"].ToString(), DollarAmount = decimal.Parse(strs["x_amount"].ToString()), TransactionDateTime = DateTime.Now, P_Authorization_Num = strs["Authorization_Num"].ToString(), P_Bank_Resp_Code = strs["Bank_Resp_Code"].ToString(), P_Bank_Message = strs["Bank_Message"].ToString(), P_Customer_Ref = strs["Customer_Ref"].ToString(), P_Exact_Ctr = strs["exact_ctr"].ToString(), P_EXact_Message = strs["EXact_Message"].ToString(), P_ResponseObject = JsonConvert.SerializeObject(strs, Formatting.Indented) }; InvoicePayment invoicePayment1 = invoicePayment; ((dynamic)this.ViewBag).NewId = 0; decimal num5 = new decimal(0); using (CustomDbContext customDbContext = new CustomDbContext()) { try { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("INSERT INTO [dbo].[FuelWerxInvoicePayments]"); stringBuilder.AppendLine(" ([TenantId]"); stringBuilder.AppendLine(" ,[InvoiceId]"); stringBuilder.AppendLine(" ,[CustomerId]"); stringBuilder.AppendLine(" ,[X_Response_Code]"); stringBuilder.AppendLine(" ,[X_Response_Reason_Code]"); stringBuilder.AppendLine(" ,[X_Response_Reason_Text]"); stringBuilder.AppendLine(" ,[X_Auth_Code]"); stringBuilder.AppendLine(" ,[X_Trans_Id]"); stringBuilder.AppendLine(" ,[X_Description]"); stringBuilder.AppendLine(" ,[P_Exact_Ctr]"); stringBuilder.AppendLine(" ,[P_Authorization_Num]"); stringBuilder.AppendLine(" ,[P_Customer_Ref]"); stringBuilder.AppendLine(" ,[P_Bank_Resp_Code]"); stringBuilder.AppendLine(" ,[P_Bank_Message]"); stringBuilder.AppendLine(" ,[P_EXact_Message]"); stringBuilder.AppendLine(" ,[P_ResponseObject]"); stringBuilder.AppendLine(" ,[TransactionDateTime]"); stringBuilder.AppendLine(" ,[DollarAmount]"); stringBuilder.AppendLine(" ,[ExportedToReporting]"); stringBuilder.AppendLine(" ,[IsDeleted]"); stringBuilder.AppendLine(" ,[DeleterUserId]"); stringBuilder.AppendLine(" ,[DeletionTime]"); stringBuilder.AppendLine(" ,[LastModificationTime]"); stringBuilder.AppendLine(" ,[LastModifierUserId]"); stringBuilder.AppendLine(" ,[CreationTime]"); stringBuilder.AppendLine(" ,[CreatorUserId])"); stringBuilder.AppendLine(" VALUES"); stringBuilder.AppendLine(" (@p0"); stringBuilder.AppendLine(" ,@p1"); stringBuilder.AppendLine(" ,@p2"); stringBuilder.AppendLine(" ,@p3"); stringBuilder.AppendLine(" ,@p4"); stringBuilder.AppendLine(" ,@p5"); stringBuilder.AppendLine(" ,@p6"); stringBuilder.AppendLine(" ,@p7"); stringBuilder.AppendLine(" ,@p8"); stringBuilder.AppendLine(" ,@p9"); stringBuilder.AppendLine(" ,@p10"); stringBuilder.AppendLine(" ,@p11"); stringBuilder.AppendLine(" ,@p12"); stringBuilder.AppendLine(" ,@p13"); stringBuilder.AppendLine(" ,@p14"); stringBuilder.AppendLine(" ,@p15"); stringBuilder.AppendLine(" ,@p16"); stringBuilder.AppendLine(" ,@p17"); stringBuilder.AppendLine(" ,0"); stringBuilder.AppendLine(" ,0"); stringBuilder.AppendLine(" ,null"); stringBuilder.AppendLine(" ,null"); stringBuilder.AppendLine(" ,null"); stringBuilder.AppendLine(" ,null"); stringBuilder.AppendLine(" ,GETDATE()"); stringBuilder.AppendLine(" ,@p18);"); stringBuilder.AppendLine("SELECT CAST(SCOPE_IDENTITY() AS BIGINT)[NewId];"); Database database = customDbContext.Database; string str1 = stringBuilder.ToString(); object[] tenantId = new object[] { invoicePayment1.TenantId, invoicePayment1.InvoiceId, invoicePayment1.CustomerId, invoicePayment1.X_Response_Code, invoicePayment1.X_Response_Reason_Code, invoicePayment1.X_Response_Reason_Text, invoicePayment1.X_Auth_Code, invoicePayment1.X_Trans_Id, invoicePayment1.X_Description, invoicePayment1.P_Exact_Ctr, invoicePayment1.P_Authorization_Num, invoicePayment1.P_Customer_Ref, invoicePayment1.P_Bank_Resp_Code, invoicePayment1.P_Bank_Message, invoicePayment1.P_EXact_Message, invoicePayment1.P_ResponseObject, invoicePayment1.TransactionDateTime, null, null }; decimal dollarAmount = invoicePayment1.DollarAmount; tenantId[17] = decimal.Parse(dollarAmount.ToString()); tenantId[18] = num4; long num6 = await database.SqlQuery <long>(str1, tenantId).SingleAsync(); long num7 = num6; await customDbContext.SaveChangesAsync(); ((dynamic)this.ViewBag).NewId = num7; string str2 = "SELECT LineTotal FROM FuelWerxInvoices WHERE Id = @p0"; Database database1 = customDbContext.Database; string str3 = str2.ToString(); object[] invoiceId = new object[] { invoicePayment1.InvoiceId }; dollarAmount = await database1.SqlQuery <decimal>(str3, invoiceId).SingleAsync(); decimal num8 = dollarAmount; string str4 = "UPDATE FuelWerxInvoices SET PaidTotal = (SELECT SUM(DollarAmount) FROM FuelWerxInvoicePayments WHERE InvoiceId = @p0) WHERE Id = @p0; SELECT PaidTotal FROM FuelWerxInvoices WHERE Id = @p0;"; Database database2 = customDbContext.Database; string str5 = str4.ToString(); object[] objArray = new object[] { invoicePayment1.InvoiceId }; dollarAmount = await database2.SqlQuery <decimal>(str5, objArray).SingleAsync(); decimal num9 = dollarAmount; if (num8 < num9) { num5 = num9 - num8; this.Logger.Debug(string.Concat("CreateInvoiceForOverageAmount[] invoiceId:overage = ", num1.ToString(), ":", num5.ToString())); StringBuilder stringBuilder1 = new StringBuilder(); stringBuilder1.AppendLine("DECLARE @newId As BIGINT = 0;"); stringBuilder1.AppendLine("INSERT INTO [dbo].[FuelWerxInvoices]"); stringBuilder1.AppendLine(" ([TenantId]"); stringBuilder1.AppendLine(" ,[CustomerId]"); stringBuilder1.AppendLine(" ,[Number]"); stringBuilder1.AppendLine(" ,[Date]"); stringBuilder1.AppendLine(" ,[PONumber]"); stringBuilder1.AppendLine(" ,[Discount]"); stringBuilder1.AppendLine(" ,[Rate]"); stringBuilder1.AppendLine(" ,[Hours]"); stringBuilder1.AppendLine(" ,[Tax]"); stringBuilder1.AppendLine(" ,[LineTotal]"); stringBuilder1.AppendLine(" ,[Terms]"); stringBuilder1.AppendLine(" ,[CurrentStatus]"); stringBuilder1.AppendLine(" ,[TimeEntryLog]"); stringBuilder1.AppendLine(" ,[Description]"); stringBuilder1.AppendLine(" ,[IsActive]"); stringBuilder1.AppendLine(" ,[ProjectId]"); stringBuilder1.AppendLine(" ,[CreationTime]"); stringBuilder1.AppendLine(" ,[CreatorUserId]"); stringBuilder1.AppendLine(" ,[CustomerAddressId]"); stringBuilder1.AppendLine(" ,[Label]"); stringBuilder1.AppendLine(" ,[BillingType]"); stringBuilder1.AppendLine(" ,[DueDateDiscountExpirationDate]"); stringBuilder1.AppendLine(" ,[DueDateDiscountTotal]"); stringBuilder1.AppendLine(" ,[DueDate]"); stringBuilder1.AppendLine(" ,[Upcharge]"); stringBuilder1.AppendLine(" ,[GroupDiscount]"); stringBuilder1.AppendLine(" ,[HoursActual]"); stringBuilder1.AppendLine(" ,[TermType]"); stringBuilder1.AppendLine(" ,[LogDataAndTasksVisibleToCustomer]"); stringBuilder1.AppendLine(" ,[EmergencyDeliveryFee]"); stringBuilder1.AppendLine(" ,[IsDeleted]"); stringBuilder1.AppendLine(" ,[IncludeEmergencyDeliveryFee])"); stringBuilder1.AppendLine(" SELECT [TenantId]"); stringBuilder1.AppendLine(" ,[CustomerId]"); stringBuilder1.AppendLine(" ,[Number]"); stringBuilder1.AppendLine(" ,CONVERT(date, GETDATE())"); stringBuilder1.AppendLine(" ,[PONumber]"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(" ,[Rate]"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(string.Concat(" ,-", num5.ToString())); stringBuilder1.AppendLine(" ,[Terms]"); stringBuilder1.AppendLine(string.Concat(" ,'", this.L("InvoiceOverageNewInvoiceDefaultStatus").Replace("'", "''"), "'")); stringBuilder1.AppendLine(" ,''"); stringBuilder1.AppendLine(" ,[Description]"); stringBuilder1.AppendLine(" ,1"); stringBuilder1.AppendLine(" ,null"); stringBuilder1.AppendLine(" ,GETDATE()"); stringBuilder1.AppendLine(" ,[CreatorUserId]"); stringBuilder1.AppendLine(" ,[CustomerAddressId]"); stringBuilder1.AppendLine(" ,[Label]"); stringBuilder1.AppendLine(" ,[BillingType]"); stringBuilder1.AppendLine(" ,null"); stringBuilder1.AppendLine(" ,null"); stringBuilder1.AppendLine(" ,CONVERT(date, DATEADD(m, 1, GETDATE()))"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(" ,[TermType]"); stringBuilder1.AppendLine(" ,[LogDataAndTasksVisibleToCustomer]"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(" ,[IncludeEmergencyDeliveryFee]"); stringBuilder1.AppendLine(" FROM [dbo].[FuelWerxInvoices]"); stringBuilder1.AppendLine(" WHERE ([Id] = @p0);"); stringBuilder1.AppendLine("SET @newId = (SELECT CAST(SCOPE_IDENTITY() AS BIGINT)[NewId]);"); stringBuilder1.AppendLine("IF @newId > 0"); stringBuilder1.AppendLine("BEGIN"); stringBuilder1.AppendLine(" INSERT INTO [dbo].[FuelWerxInvoiceAdjustments]"); stringBuilder1.AppendLine(" ("); stringBuilder1.AppendLine(" [InvoiceId]"); stringBuilder1.AppendLine(" ,[Name]"); stringBuilder1.AppendLine(" ,[Cost]"); stringBuilder1.AppendLine(" ,[RetailCost]"); stringBuilder1.AppendLine(" ,[Description]"); stringBuilder1.AppendLine(" ,[IsTaxable]"); stringBuilder1.AppendLine(" ,[IsActive]"); stringBuilder1.AppendLine(" ,[CreationTime]"); stringBuilder1.AppendLine(" ,[CreatorUserId]"); stringBuilder1.AppendLine(" ,[IsDeleted]"); stringBuilder1.AppendLine(" )"); stringBuilder1.AppendLine(" VALUES"); stringBuilder1.AppendLine(" ("); stringBuilder1.AppendLine(" @newId"); stringBuilder1.AppendLine(string.Concat(" ,'", this.L("InvoiceOverageNewInvoiceDefaultAdjustmentName").Replace("'", "''"), "'")); stringBuilder1.AppendLine(string.Concat(" ,-", num5.ToString())); stringBuilder1.AppendLine(string.Concat(" ,-", num5.ToString())); stringBuilder1.AppendLine(string.Concat(" ,'", this.L("InvoiceOverageNewInvoiceDefaultAdjustmentDescription").Replace("'", "''"), "'")); stringBuilder1.AppendLine(" ,1"); stringBuilder1.AppendLine(" ,1"); stringBuilder1.AppendLine(" ,GETDATE()"); stringBuilder1.AppendLine(" ,(SELECT TOP 1 [CreatorUserId] FROM [dbo].[FuelWerxInvoices] WHERE [Id] = @newId)"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(" );"); stringBuilder1.AppendLine("END"); stringBuilder1.AppendLine("SELECT @newId;"); Database database3 = customDbContext.Database; string str6 = stringBuilder1.ToString(); object[] invoiceId1 = new object[] { invoicePayment1.InvoiceId }; num6 = await database3.SqlQuery <long>(str6, invoiceId1).SingleAsync(); long num10 = num6; this.Logger.Debug(string.Concat("CreateInvoiceForOverageAmount[] newInvoiceId = ", num10.ToString())); } } catch (Exception exception1) { Exception exception = exception1; ((dynamic)this.ViewBag).NewId = 0; throw new UserFriendlyException(string.Concat(this.L("ManualPaymentCreationFailed"), exception.Message.ToString())); } } if (!item) { actionResult = this.View(); } else { actionResult = this.Json(new MvcAjaxResponse()); } return(actionResult); }
public string Index(FormCollection fc, string searchString) { return "From [HttpPost]Index: filter on " + searchString; }
public async Task <ActionResult> Payeezy(FormCollection formFields) { int value; string str; Guid guid; string str1; bool flag; PayNowDto payNowDto = new PayNowDto(); try { int?impersonatorTenantId = this.AbpSession.ImpersonatorTenantId; if (impersonatorTenantId.HasValue) { impersonatorTenantId = this.AbpSession.ImpersonatorTenantId; value = impersonatorTenantId.Value; } else { value = this.AbpSession.GetTenantId(); } int num = value; TenantSettingsEditDto allSettingsByTenantId = await this._tenantSettingsAppService.GetAllSettingsByTenantId(num); long num1 = long.Parse(formFields["invoiceId"]); decimal.Parse(formFields["invoiceAmount"]); decimal num2 = decimal.Parse(formFields["paymentAmount"]); Invoice invoice = await this._invoiceAppService.GetInvoice(num1); if (invoice == null || invoice.TenantId != num) { if (invoice != null) { throw new Exception("SecurityViolation"); } throw new Exception("InvoiceIsNull"); } payNowDto.x_invoice_num = invoice.Number; payNowDto.x_po_num = invoice.PONumber; payNowDto.x_reference_3 = invoice.Number; ICustomerAppService customerAppService = this._customerAppService; NullableIdInput <long> nullableIdInput = new NullableIdInput <long>() { Id = new long?(invoice.CustomerId) }; GetCustomerForEditOutput customerForEdit = await customerAppService.GetCustomerForEdit(nullableIdInput); PayNowDto payNowDto1 = payNowDto; string[] strArrays = new string[7]; long id = invoice.Id; strArrays[0] = id.ToString(); strArrays[1] = "|"; long?impersonatorUserId = customerForEdit.Customer.Id; id = impersonatorUserId.Value; strArrays[2] = id.ToString(); strArrays[3] = "|"; strArrays[4] = num.ToString(); strArrays[5] = "|"; impersonatorUserId = this.AbpSession.ImpersonatorUserId; if (impersonatorUserId.HasValue) { impersonatorUserId = this.AbpSession.ImpersonatorUserId; id = impersonatorUserId.Value; str = id.ToString(); } else { impersonatorUserId = this.AbpSession.UserId; if (impersonatorUserId.HasValue) { impersonatorUserId = this.AbpSession.UserId; id = impersonatorUserId.Value; str = id.ToString(); } else { impersonatorUserId = this.AbpSession.UserId; str = impersonatorUserId.ToString(); } } strArrays[6] = str; payNowDto1.x_cust_id = string.Concat(strArrays); payNowDto.x_email = customerForEdit.Customer.Email; if (customerForEdit.Customer.BusinessName != null && customerForEdit.Customer.BusinessName.ToString().Length > 0) { payNowDto.x_company = customerForEdit.Customer.BusinessName; } if (customerForEdit.Customer.FirstName != null && customerForEdit.Customer.FirstName.ToString().Length > 0) { payNowDto.x_first_name = customerForEdit.Customer.FirstName.ToString(); } if (customerForEdit.Customer.LastName != null && customerForEdit.Customer.LastName.ToString().Length > 0) { payNowDto.x_last_name = customerForEdit.Customer.LastName.ToString(); } PayNowDto str2 = payNowDto; impersonatorUserId = customerForEdit.Customer.Id; id = impersonatorUserId.Value; str2.x_customer_tax_id = id.ToString(); impersonatorUserId = invoice.CustomerAddressId; if (impersonatorUserId.HasValue) { impersonatorUserId = invoice.CustomerAddressId; if (impersonatorUserId.Value > (long)0) { IGenericAppService genericAppService = this._genericAppService; GetAddressesInput getAddressesInput = new GetAddressesInput(); impersonatorUserId = customerForEdit.Customer.Id; getAddressesInput.OwnerId = new long?(impersonatorUserId.Value); getAddressesInput.OwnerType = "Customer"; PagedResultOutput <AddressListDto> addresses = await genericAppService.GetAddresses(getAddressesInput); int num3 = 0; while (num3 < addresses.Items.Count) { long id1 = (long)addresses.Items[num3].Id; impersonatorUserId = invoice.CustomerAddressId; flag = (id1 == impersonatorUserId.GetValueOrDefault() ? impersonatorUserId.HasValue : false); if (!flag) { num3++; } else { payNowDto.x_address = addresses.Items[num3].PrimaryAddress; payNowDto.x_city = addresses.Items[num3].City; payNowDto.x_zip = addresses.Items[num3].PostalCode; impersonatorTenantId = addresses.Items[num3].CountryRegionId; if (!impersonatorTenantId.HasValue) { break; } IGenericAppService genericAppService1 = this._genericAppService; impersonatorTenantId = addresses.Items[num3].CountryRegionId; int?nullable = new int?(impersonatorTenantId.Value); impersonatorTenantId = null; ListResultOutput <CountryRegionInCountryListDto> countryRegions = genericAppService1.GetCountryRegions(nullable, impersonatorTenantId); if (countryRegions.Items.Count != 1) { break; } payNowDto.x_state = countryRegions.Items[0].Code; break; } } } } Tenant byIdAsync = await this._tenantManager.GetByIdAsync(num); string tenancyName = byIdAsync.TenancyName; string str3 = tenancyName; string str4 = tenancyName; str4 = str3; byIdAsync = await this._tenantManager.FindByTenancyNameAsync(str4); string siteRootAddress = this._webUrlService.GetSiteRootAddress(str4); PayNowDto payNowDto2 = payNowDto; object[] objArray = new object[] { siteRootAddress, "Mpa/Settings/GetLogoById?logoId=", null, null, null }; guid = (allSettingsByTenantId.Logo.InvoiceImageId.HasValue ? allSettingsByTenantId.Logo.InvoiceImageId.Value : Guid.Empty); objArray[2] = guid; objArray[3] = "&logoType=header&viewContrast=light&t="; id = Clock.Now.Ticks; objArray[4] = id.ToString(); payNowDto2.x_logo_url = string.Concat(objArray); payNowDto.x_receipt_link_url = string.Concat(siteRootAddress, "Pay/PayeezyResponse"); payNowDto.x_receipt_link_method = "AUTO-POST"; payNowDto.x_receipt_link_text = this.L("CompleteTransaction"); if (allSettingsByTenantId.PaymentGatewaySettings.GatewaySettings.Length <= 3) { throw new Exception("PaymentGatewayError_PayEezySettingsMissing"); } PayEezyJsonObject payEezyJsonObject = JsonConvert.DeserializeObject <PayEezyJsonObject>(allSettingsByTenantId.PaymentGatewaySettings.GatewaySettings); payNowDto.x_login = payEezyJsonObject.PayEezy_x_login; payNowDto.x_transaction_key = payEezyJsonObject.PayEezy_x_transaction_key; PayNowDto payNowDto3 = payNowDto; bool? payEezyXTestRequest = payEezyJsonObject.PayEezy_x_test_request; payNowDto3.x_test_request = bool.Parse(payEezyXTestRequest.ToString()); PayNowDto payNowDto4 = payNowDto; payEezyXTestRequest = payEezyJsonObject.PayEezy_x_email_customer; payNowDto4.x_email_customer = bool.Parse(payEezyXTestRequest.ToString()); payNowDto.x_gateway_id = payEezyJsonObject.PayEezy_x_gateway_id; PayNowDto payNowDto5 = payNowDto; string payEezyXDescription = payEezyJsonObject.PayEezy_x_description; str1 = (formFields["Description"] == null || formFields["Description"] != null && formFields["Description"].ToString().Length > 0 ? string.Concat(" ", formFields["Description"].ToString()) : ""); payNowDto5.x_description = string.Concat(payEezyXDescription, str1); payNowDto.x_amount = num2; payNowDto.x_customer_ip = PayController.GetIPAddress(this.Request); Random random = new Random(); PayNowDto str5 = payNowDto; int num4 = random.Next(0, 1000); str5.x_fp_sequence = num4.ToString(); TimeSpan utcNow = DateTime.UtcNow - new DateTime(1970, 1, 1); payNowDto.x_fp_timestamp = ((int)utcNow.TotalSeconds).ToString(); payNowDto.x_fp_hash = PayController.GeneratePayeezyHash(payNowDto.x_transaction_key, payNowDto.x_login, payNowDto.x_amount, payNowDto.x_fp_sequence, payNowDto.x_fp_timestamp, "USD"); if (!payNowDto.x_test_request) { payNowDto.PostToUrl = "https://checkout.globalgatewaye4.firstdata.com/payment"; } else { payNowDto.PostToUrl = "https://demo.globalgatewaye4.firstdata.com/payment"; } allSettingsByTenantId = null; invoice = null; str4 = null; } catch (Exception) { payNowDto = new PayNowDto(); ((dynamic)this.ViewBag).Error_InvalidParameters = true; } return(this.View(payNowDto)); }
public ActionResult Delete(int id, FormCollection form) { Db.Delete(id); return RedirectToAction("Index"); }
public ActionResult HoaDon(FormCollection f) { luuDonHang(f); return(View("ThanhCong")); }
private void UpdateRequest(HttpRequest request, string data, string name) { const string fileName = "text.txt"; var fileCollection = new FormFileCollection(); var formCollection = new FormCollection(new Dictionary<string, StringValues>(), fileCollection); request.Form = formCollection; request.ContentType = "multipart/form-data; boundary=----WebKitFormBoundarymx2fSWqWSd0OxQqq"; if (string.IsNullOrEmpty(data) || string.IsNullOrEmpty(name)) { // Leave the submission empty. return; } request.Headers["Content-Disposition"] = $"form-data; name={name}; filename={fileName}"; var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(data)); fileCollection.Add(new FormFile(memoryStream, 0, data.Length, name, fileName) { Headers = request.Headers }); }
//[ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "ID,IsManual,AccessCardID,DeletedFlag,ShipmentStatusID,OrderID,BayID,BayName,CustomerName,VehicleCode,DriverName,DriverCNIC,CarrierName,ShipmentDate,ProductID")] Shipment shipment, FormCollection formCollection) { #region update bays queue #endregion #region access card update if (shipment.AccessCardID != null && shipment.ShipmentStatusID == 1) { ///////////////////////////////////////////////////update order status/////////////////////////////////////////////////// Order odr = db.Orders.Where(x => x.OrderID == shipment.OrderID).FirstOrDefault <Order>(); odr.OrderStatusID = 3; odr.ModifiedDate = DateTime.Now; odr.ModifiedBy = User.Identity.Name; db.Orders.Attach(odr); db.Entry(odr).Property(x => x.ModifiedDate).IsModified = true; db.Entry(odr).Property(x => x.ModifiedBy).IsModified = true; db.Entry(odr).Property(x => x.OrderStatusID).IsModified = true; db.SaveChanges(); /////////////////////////////////////////////////assign access card/////////////////////////////////////////////// AccessCard accessCard = db.AccessCards.Where(x => x.CardID == shipment.AccessCardID).FirstOrDefault <AccessCard>(); accessCard.IsAssigned = true; accessCard.ModifiedDate = DateTime.Now; accessCard.ModifiedBy = User.Identity.Name; db.AccessCards.Attach(accessCard); db.Entry(accessCard).Property(x => x.ModifiedDate).IsModified = true; db.Entry(accessCard).Property(x => x.ModifiedBy).IsModified = true; db.Entry(accessCard).Property(x => x.IsAssigned).IsModified = true; db.Entry(accessCard).State = EntityState.Modified; db.SaveChanges(); //db.Entry(accessCard).State = EntityState.Detached; } else if (shipment.AccessCardID != null && shipment.ShipmentStatusID != 1 && shipment.ShipmentStatusID != 5) { ////////////////////////////////////unassign card if any//////////////////////// int?expectedID = db.Shipments.AsNoTracking().Where(x => x.ID == shipment.ID).FirstOrDefault().AccessCardID; if (expectedID != null && expectedID != shipment.AccessCardID) { /////////////////////////////////////////access card old/////////////////////// AccessCard accessCardOld = db.AccessCards.Where(x => x.CardID == expectedID).FirstOrDefault <AccessCard>(); accessCardOld.IsAssigned = false; accessCardOld.ModifiedDate = DateTime.Now; accessCardOld.ModifiedBy = User.Identity.Name; db.AccessCards.Attach(accessCardOld); db.Entry(accessCardOld).Property(x => x.ModifiedDate).IsModified = true; db.Entry(accessCardOld).Property(x => x.ModifiedBy).IsModified = true; db.Entry(accessCardOld).Property(x => x.IsAssigned).IsModified = true; //////////////////////////access card New/////////////////////////////////////// AccessCard accessCardNew = db.AccessCards.Where(x => x.CardID == shipment.AccessCardID).FirstOrDefault <AccessCard>(); accessCardNew.CardID = (int)shipment.AccessCardID; accessCardNew.IsAssigned = true; accessCardNew.ModifiedDate = DateTime.Now; accessCardNew.ModifiedBy = User.Identity.Name; db.AccessCards.Attach(accessCardNew); db.Entry(accessCardNew).Property(x => x.ModifiedDate).IsModified = true; db.Entry(accessCardNew).Property(x => x.ModifiedBy).IsModified = true; db.Entry(accessCardNew).Property(x => x.IsAssigned).IsModified = true; ///////////////////////////finally save data///////////////////////////////////// db.Entry(accessCardOld).State = EntityState.Modified; db.Entry(accessCardNew).State = EntityState.Modified; db.SaveChanges(); } else { ///////////////////////////////////////////////////update order status/////////////////////////////////////////////////// Order odr = db.Orders.Where(x => x.OrderID == shipment.OrderID).FirstOrDefault <Order>(); odr.OrderStatusID = 3; odr.ModifiedDate = DateTime.Now; odr.ModifiedBy = User.Identity.Name; db.Orders.Attach(odr); db.Entry(odr).Property(x => x.ModifiedDate).IsModified = true; db.Entry(odr).Property(x => x.ModifiedBy).IsModified = true; db.Entry(odr).Property(x => x.OrderStatusID).IsModified = true; db.SaveChanges(); ////////////////////////////////////////////////assign Access card/////////////////////////////////////////////////////// AccessCard accessCard = db.AccessCards.Where(x => x.CardID == shipment.AccessCardID).FirstOrDefault <AccessCard>(); accessCard.CardID = (int)shipment.AccessCardID; accessCard.IsAssigned = true; accessCard.ModifiedDate = DateTime.Now; accessCard.ModifiedBy = User.Identity.Name; db.AccessCards.Attach(accessCard); db.Entry(accessCard).Property(x => x.ModifiedDate).IsModified = true; db.Entry(accessCard).Property(x => x.ModifiedBy).IsModified = true; db.Entry(accessCard).Property(x => x.IsAssigned).IsModified = true; db.Entry(accessCard).State = EntityState.Modified; //commneted by ahad for performance db.SaveChanges(); } } else if (shipment.ShipmentStatusID == 5) { Order odr = db.Orders.Where(x => x.OrderID == shipment.OrderID).FirstOrDefault <Order>(); odr.OrderStatusID = 3; odr.OrderDeliveryDT = DateTime.Now; odr.ModifiedDate = DateTime.Now; odr.ModifiedBy = User.Identity.Name; db.Orders.Attach(odr); db.Entry(odr).Property(x => x.ModifiedDate).IsModified = true; db.Entry(odr).Property(x => x.ModifiedBy).IsModified = true; db.Entry(odr).Property(x => x.OrderStatusID).IsModified = true; db.Entry(odr).Property(x => x.OrderDeliveryDT).IsModified = true; db.SaveChanges(); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AccessCard accessCard = db.AccessCards.Where(x => x.CardID == shipment.AccessCardID).FirstOrDefault <AccessCard>(); accessCard.CardID = (int)shipment.AccessCardID; accessCard.IsAssigned = false; accessCard.ModifiedDate = DateTime.Now; accessCard.ModifiedBy = User.Identity.Name; db.AccessCards.Attach(accessCard); db.Entry(accessCard).Property(x => x.ModifiedDate).IsModified = true; db.Entry(accessCard).Property(x => x.ModifiedBy).IsModified = true; db.Entry(accessCard).Property(x => x.IsAssigned).IsModified = true; db.Entry(accessCard).State = EntityState.Modified; //commneted by ahad for performance db.SaveChanges(); //db.Entry(accessCard).State = EntityState.Detached; } #endregion #region shipment compartment int compCountTempDataUpdate = Convert.ToInt32(TempData["CompCountUpdate"].ToString()); if (compCountTempDataUpdate != 0) { for (int i = 0; i < compCountTempDataUpdate; i++) { int compIDConverted = Convert.ToInt32(formCollection["compId" + i]); ShipmentCompartment shipmentComp = db.ShipmentCompartments.Where(x => x.ID == compIDConverted).FirstOrDefault <ShipmentCompartment>(); //shipmentComp.ID = Convert.ToInt32(formCollection["compId" + i]); shipmentComp.OrderedQuantity = Convert.ToInt32(formCollection["Order.OrderQty"]); int compPlannedQty; if (Int32.TryParse(formCollection["compPlannedQty" + i], out compPlannedQty)) { shipmentComp.PlannedQuantity = compPlannedQty; } else { shipmentComp.PlannedQuantity = null; } shipmentComp.AccessCardKey = shipment.AccessCardID.ToString(); shipmentComp.BayID = Convert.ToInt32(shipment.BayID); shipmentComp.Product = shipment.ProductID.ToString(); shipmentComp.ShipmentID = shipment.ID; //shipmentComp.CreatedDate = DateTime.Now; shipmentComp.ModifiedDate = DateTime.Now; shipmentComp.ModifiedBy = User.Identity.Name; shipmentComp.CompartmentCode = Convert.ToInt32(formCollection["compCode" + i]); shipmentComp.Capacity = Convert.ToInt32(formCollection["compCapacity" + i]); db.ShipmentCompartments.Attach(shipmentComp); db.Entry(shipmentComp).State = EntityState.Modified; db.SaveChanges(); //db.Entry(shipmentComp).State = EntityState.Detached; } } else { int compCountTempDataNew = Convert.ToInt32(TempData["CompCountNew"].ToString()); for (int i = 0; i < compCountTempDataNew; i++) { try { if (shipment.ShipmentStatusID != 4) { shipment.ShipmentStatusID = 2; // shipment status id is set to queued. } ShipmentCompartment shipmentComp = new ShipmentCompartment(); shipmentComp.OrderedQuantity = Convert.ToInt32(formCollection["Order.OrderQty"]); int compPlannedQty; if (Int32.TryParse(formCollection["compPlannedQty" + i], out compPlannedQty)) { shipmentComp.PlannedQuantity = compPlannedQty; } else { shipmentComp.PlannedQuantity = null; } shipmentComp.AccessCardKey = shipment.AccessCardID.ToString(); shipmentComp.BayID = Convert.ToInt32(shipment.BayID); shipmentComp.Product = shipment.ProductID.ToString(); shipmentComp.ShipmentID = shipment.ID; shipmentComp.CreatedDate = DateTime.Now; shipmentComp.CreatedBy = User.Identity.Name; shipmentComp.ModifiedDate = DateTime.Now; shipmentComp.ModifiedBy = User.Identity.Name; shipmentComp.CompartmentCode = Convert.ToInt32(formCollection["compCode" + i]); shipmentComp.Capacity = Convert.ToInt32(formCollection["compCapacity" + i]); db.ShipmentCompartments.Add(shipmentComp); db.SaveChanges(); } catch (Exception e) { e.ToString(); } } } #endregion if (ModelState.IsValid) { //db.Entry(shipment).Property(x => x.ModifiedDate).IsModified = true; db.Entry(shipment).State = EntityState.Modified; db.Entry(shipment).Property(x => x.CreatedDate).IsModified = false; db.Entry(shipment).Property(x => x.CreatedBy).IsModified = false; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.AccessCardID = new SelectList(db.AccessCards, "CardID", "Remarks", shipment.AccessCardID); ViewBag.BayID = new SelectList(db.Bays, "BayID", "Remarks", shipment.BayID); ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderCode", shipment.OrderID); ViewBag.ShipmentStatusID = new SelectList(db.ShipmentStatus, "ID", "Status", shipment.ShipmentStatusID); ViewBag.ID = new SelectList(db.WeighBridges, "ShipmentID", "Status", shipment.ID); return(View(shipment)); }
public void GetValue_ThrowsIfNameIsNull() { // Arrange FormCollection formCollection = new FormCollection(); // Act & assert Assert.ThrowsArgumentNull( delegate { formCollection.GetValue(null); }, "name"); }
public ActionResult CreateCard(ElementModels model, HttpPostedFileBase image1, FormCollection fm) { if (ModelState.IsValid) { if (image1 != null) { model.ImagePath = new byte[image1.ContentLength]; image1.InputStream.Read(model.ImagePath, 0, image1.ContentLength); } string ET = fm["ET".ToString()]; string IF = fm["IF".ToString()]; string II = fm["II".ToString()]; model.ElementType = ET; model.IsForce = IF; model.IsInter = II; int cardCreate = CreateElementCard(model.ElementType, model.ElementName, model.InSan, model.DeSan, model.IsForce, model.IsInter, model.ElementDes, model.ImagePath ); return(RedirectToAction("CreateCard")); } return(View()); }
public void GetValue_KeyExists_ReturnsResult() { // Arrange FormCollection formCollection = new FormCollection() { { "foo", "1" }, { "foo", "2" } }; // Act ValueProviderResult vpResult = formCollection.GetValue("foo"); // Assert Assert.NotNull(vpResult); Assert.Equal(new[] { "1", "2" }, (string[])vpResult.RawValue); Assert.Equal("1,2", vpResult.AttemptedValue); Assert.Equal(CultureInfo.CurrentCulture, vpResult.Culture); }
/// <summary> /// 批量导入excel数据 /// </summary> public ActionResult Upexcel(FormCollection from) { // var fl = Request.Files; // Stream file = Request.Files[0].InputStream; //if (files != null && files.Count > 0) //{ // Stream fileStream = Request.Files[0].InputStream; // byte[] fileDataStream = new byte[Request.Files[0].ContentLength]; // fileStream.Read(fileDataStream, 0, Request.Files[0].ContentLength); //} HttpPostedFileBase file = Request.Files["upload"]; string result = string.Empty; if (file == null || file.ContentLength <= 0) { } else { try { Workbook workbook = new Workbook(file.InputStream); Cells cells = workbook.Worksheets[0].Cells; DataTable tab = cells.ExportDataTable(0, 0, cells.Rows.Count, cells.MaxDisplayRange.ColumnCount); int rowsnum = tab.Rows.Count; if (rowsnum == 0) { result = "Excel表为空!请重新导入!"; //当Excel表为空时,对用户进行提示 } //数据表一共多少行! DataRow[] dr = tab.Select(); //按行进行数据存储操作! for (int i = 1; i < dr.Length; i++) { //RPer,B_Guid,BA_Guid数据需要比对! string rper = (new BusinessPartnerSvc().GetPartnersDts(Session["CurrentCompanyGuid"].ToString(), dr[i][0].ToString())).ToString(); string bguid = (new BankAccountSvc().GetBankDts(Session["CurrentCompanyGuid"].ToString(), dr[i][4].ToString())).ToString(); string baguid = (new BankAccountSvc().GetBankAccountDts(Session["CurrentCompanyGuid"].ToString(), bguid, dr[i][5].ToString())).ToString(); string cguid = Session["CurrentCompanyGuid"].ToString(); string creator = base.userData.LoginFullName; DateTime createdate = DateTime.Now; DBHelper dh = new DBHelper(); dh.strCmd = "SP_UpdRecPayRecord"; dh.AddPare("@ID", SqlDbType.NVarChar, 40, Guid.NewGuid().ToString()); dh.AddPare("@Flag", SqlDbType.NVarChar, 1, "R"); dh.AddPare("@R_Per", SqlDbType.NVarChar, 40, rper); dh.AddPare("@Date", SqlDbType.Date, 0, dr[i][1].ToString()); dh.AddPare("@Amount", SqlDbType.Decimal, 0, dr[i][2].ToString()); dh.AddPare("@Currency", SqlDbType.NVarChar, 40, dr[i][3].ToString()); dh.AddPare("@B_Guid", SqlDbType.NVarChar, 40, bguid); dh.AddPare("@BA_Guid", SqlDbType.NVarChar, 40, baguid); dh.AddPare("@Remark", SqlDbType.NVarChar, 40, dr[i][6].ToString()); dh.AddPare("@Creator", SqlDbType.NVarChar, 40, creator); dh.AddPare("@CreateDate", SqlDbType.DateTime, 0, createdate); dh.AddPare("@C_GUID", SqlDbType.NVarChar, 50, cguid); dh.AddPare("@InvType", SqlDbType.NVarChar, 50, "未归账"); try { dh.NonQuery(); result = "导入成功!"; } catch { result = "导入数据部分错误!"; } } } catch (Exception) { result = "导入失败,请检查EXCEL格式是否错误!"; } } JsonResult json = new JsonResult(); json.Data = result; return(json); }
public ActionResult Index(FormCollection form) { int i = 0; return View(); }
public ActionResult getActionItem4Task(FormCollection f) { log.Debug("projectId=" + f["projectid"] + ",prjuid=" + f["checkNodeId"]); //planService return PartialView("_getProjecttem4Task", planService.getItemInTask(f["projectid"], f["checkNodeId"])); }