protected void Page_Load(object sender, EventArgs e) { // Create a ClaimsPrincipal object from the current user to work with claims ClaimsPrincipal claimsPrincipal = Page.User as ClaimsPrincipal; /* * We can use the FindFirst method to get the first occurance of a specific claim. * This is very useful when you only expect a single instance of a particular claim type. * Note the ClaimTypes class contains many common claims defined as properties for your use. */ // Here we are setting our label to the name claim value. Claim claimName = claimsPrincipal.FindFirst(ClaimTypes.Name); if (claimName != null) { this.nameLabel.Text = AntiXssEncoder.HtmlEncode(claimName.Value, false); } else { this.nameLabel.Text = "Name claim not found"; } // ClaimsPrincipal.Claims returns a collection of claims that we can query, iterate over // or in this case set as a datasource of a GridView control. Lots of flexibility. this.ClaimsGridView.DataSource = claimsPrincipal.Claims; this.ClaimsGridView.DataBind(); }
public JsonResult AddMetaPage(string pageName, string widgetName) { var success = "OK"; var message = ""; try { if (String.IsNullOrWhiteSpace(pageName)) { pageName = "** New Page For Widget **"; } var encodedName = AntiXssEncoder.HtmlEncode(pageName, false); var metaPage = new MetaPage { Breadcrumb = string.Empty, IsSystem = false, MetaDefinition = "", PageDefinition = widgetName, PageName = encodedName, metapage_guid = Guid.NewGuid(), IsVisible = false }; _unitOfWork.Repository <MetaPage>().Save(metaPage); } catch (Exception ex) { success = "FAILED"; message = ex.Message; } var result = new { Success = success, Message = message }; return(Json(result, JsonRequestBehavior.AllowGet)); }
public static string HtmlEncodeJTokenStrings(string jsonString) { var reconstruct = JToken.Parse(jsonString); var stack = new Stack <JToken>(); stack.Push(reconstruct); while (stack.Count > 0) { var item = stack.Pop(); if (item.Type == JTokenType.String) { var valueItem = item as JValue; if (valueItem == null) { continue; } var value = valueItem.Value <string>(); valueItem.Value = AntiXssEncoder.HtmlEncode(value, true); } foreach (var child in item.Children()) { stack.Push(child); } } return(reconstruct.ToString()); }
/// <summary> /// Método de carga de página en el cual carga una tabla con los datos básicos de las compañías. /// </summary> /// <param name="typeHab, idComp">parametro que indica si la compañía está habilitada y su id</param> /// <returns></returns> protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { try { if (Presentador.BotonHabilitarInhabilitar(int.Parse(AntiXssEncoder.HtmlEncode(Request.QueryString["typeHab"], false)), int.Parse(AntiXssEncoder.HtmlEncode(Request.QueryString["idComp"], false)))) { ScriptManager.RegisterStartupScript(this, this.GetType(), "alerts", "javascript:alert('" + msjError + "')", true); } } catch (Exception ex) { if (!ex.Message.Equals("Value cannot be null.\r\nParameter name: String")) { Response.Redirect("../M1/PaginaError.aspx", false); } } try { if (Presentador.ImprimirCompania(HttpContext.Current.Session["Rol"].ToString())) { ScriptManager.RegisterStartupScript(this, this.GetType(), "alerts", "javascript:alert('" + msjError + "')", true); } } catch { } } }
// GET: SubmitAssignment public ActionResult SubmitAssignment(int id) { //List<Assignment> pass = new List<Assignment>(); SubmitAssignmentViewModel svm = new SubmitAssignmentViewModel(); Assignment assignment = db.Assignments.ToList().Find(a => a.AssignmentID == id); svm.RetryRemaining = assignment.MaxAttempt - db.Submissions.ToList().FindAll(s => s.AssignmentID == id).Count(); Module module = db.Modules.ToList().Find(m => m.ModuleCode == assignment.ModuleCode); svm.Module = module.ModuleCode + " " + module.ModuleName; svm.IssuedBy = db.Lecturers.ToList().Find(lc => lc.StaffID == assignment.CreateBy).Name.ToString(); //start a session to check which assignment student is viewing Session["assignmentId"] = id; if (Session["UploadError"] != null) { ModelState.AddModelError("UploadError", Session["UploadError"].ToString()); Session.Remove("UploadError"); } svm.assignment = assignment; //encode the richtext from the DB svm.assignment.Describe = AntiXssEncoder.HtmlEncode(svm.assignment.Describe, false); return(View(svm)); }//end of get SubmitAssignment
private string GetHtmlLink(string unsubscribeUrl) { string link = string.Format("<a id='{0}' href=\"{1}\">{2}</a>", "BD5134C6-8D33-4ABA-A0C4-08581FDF89DB", unsubscribeUrl, ClientStrings.GroupSubscriptionUnsubscribeLinkWord.ToString(this.cultureInfo)); string groupName = AntiXssEncoder.HtmlEncode(this.groupDisplayName, false); return("<br /><div style=\"display:inline-block\" ><table border=\"0\" cellspacing=\"0\" style=\"background-color:#F4F4F4;\" ><tr><td style=\"padding:20px; font-size:12px; color:#666666\" >" + ClientStrings.GroupSubscriptionUnsubscribeInfoHtml(groupName, link).ToString(this.cultureInfo) + "</tr></td></table></div>"); }
private static void HandleDeserializationError(object sender, ErrorEventArgs errorArgs, ICollection <KeyValuePair <string, string> > errors) { var errorArgsErrorContext = errorArgs.ErrorContext; errors.Add(new KeyValuePair <string, string>(errorArgsErrorContext.Path, AntiXssEncoder.HtmlEncode(errorArgsErrorContext.Error.Message, true))); errorArgsErrorContext.Handled = true; }
public ActionResult Create(AnnouncementViewModel viewModel) { if (!ModelState.IsValid) { return(View(viewModel)); } try { SendEmailAndSMS(viewModel); // sanitize the html from user viewModel.AnnouncementHtml = AntiXssEncoder.HtmlEncode(viewModel.AnnouncementHtml, false); // add announcement to Azure table storage AnnouncementHelper.AddAnnouncent(viewModel); AnnouncementHelper.CreatedNewAnnouncement = true; return(RedirectToAction("Index")); } catch (Exception ex) { // log caught exception with Elmah ErrorSignal.FromCurrentContext().Raise(ex); return(View(viewModel)); } }
// SetValue gets called by Json.Net during deserialization. // The value parameter has the original value read from the JSON; // target is the object on which to set the value. public void SetValue(object target, object value) { string valueString = (string)value; var encodedValue = AntiXssEncoder.HtmlEncode(valueString, true); _targetProperty.SetValue(target, encodedValue); }
protected void Page_Load(object sender, EventArgs e) { if (User.Identity.IsAuthenticated) { // Create a ClaimsPrincipal object from the current user to work with claims ClaimsPrincipal claimsPrincipal = User as ClaimsPrincipal; // We can use the FindFirst method to get the first occurance of a specific claim. // This is very useful when you only expect a single instance of a particular claim type. // Note the ClaimTypes class contains many common claims defined as properties for your use. // Elsewhere we use the Name property from the User.Identity, here we show // that it is also a claim just as the others below that are not mapped to // properties within IPrincipal based identities Claim claimName = claimsPrincipal.FindFirst(ClaimTypes.Name); if (claimName != null) { this.nameLabel.Text = AntiXssEncoder.HtmlEncode(claimName.Value, false); } else { this.nameLabel.Text = "Name claim not found"; } // ClaimsPrincipal.Claims returns a collection of claims that we can query, iterate over // or in this case set as a datasource of a GridView control. Lots of flexibility. this.ClaimsGridView.DataSource = claimsPrincipal.Claims; this.ClaimsGridView.DataBind(); } }
private void CheckAllStrings(object data, Type dataType) { if (dataType == typeof(string)) { var tempData = AntiXssEncoder.HtmlEncode(data.ToString(), false); if (string.Equals(tempData, data.ToString(), StringComparison.OrdinalIgnoreCase) == false) { throw new SampleSiteException("You attempted to pass in some XSS, no soup for you!"); } } else if (dataType.IsClass) { var properties = dataType.GetProperties(); foreach (var property in properties) { var dataToConvert = property.GetValue(data, null); CheckAllStrings(dataToConvert, property.PropertyType); property.SetValue(data, dataToConvert, null); } } }
public ViewResult List(string category, int page = 1, String SearchTerm = null) { var str = AntiXssEncoder.HtmlEncode(SearchTerm, true); ViewBag.search = SearchTerm; ProductsListViewModel viewModel = new ProductsListViewModel { Products = repository.Products .Where(p => SearchTerm == null || p.Name.StartsWith(str)) .Where(p => category == null || p.Category == category) .OrderBy(p => p.ProductID) .Skip((page - 1) * PageSize) .Take(PageSize) , PagingInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = category == null? repository.Products.Count() : repository.Products.Where(e => e.Category == category).Count() }, CurrentCategory = category }; //if (Request.IsAjaxRequest()) //{ // return PartialView("_MovieResult", model); //} return(View(viewModel)); }
protected void btn_html_Click(object sender, EventArgs e) { String s = this.txt_1.Text; this.txt_2.Text = AntiXssEncoder.HtmlEncode(s, true); //this.txt_2.Text = AntiXssEncoder.HtmlEncode(s, false); }
public ActionResult TlogSendState(ViewModels.TlogViewModels FormCols) { /*初始化宣告*/ ViewModels.TlogViewModels vmTlogSendStat = null; try { /*OWASP檢查*/ OWASP_Verify(FormCols.TxDateST); OWASP_Verify(FormCols.TxDateED); OWASP_Verify(FormCols.CardNo); /*參數透過AntiXss編碼*/ FormCols.TxDateST = AntiXssEncoder.HtmlEncode(FormCols.TxDateST, true); FormCols.TxDateED = AntiXssEncoder.HtmlEncode(FormCols.TxDateED, true); FormCols.CardNo = AntiXssEncoder.HtmlEncode(FormCols.CardNo, true); /*取得TLOG*/ vmTlogSendStat = new ViewModels.TlogViewModels(); vmTlogSendStat.TxDateST = FormCols.TxDateST; vmTlogSendStat.TxDateED = FormCols.TxDateED; vmTlogSendStat.CardNo = string.IsNullOrEmpty(FormCols.CardNo) ? "" : FormCols.CardNo.Trim(); vmTlogSendStat.TlogSendState = getTlogSendState(FormCols.TxDateST, FormCols.TxDateED, FormCols.CardNo).ToPagedList(1, 5); return(View(vmTlogSendStat)); } catch (Exception ex) { return(RedirectToAction("Exception", "TGW", new { @MsgCont = ex.Message })); } finally { vmTlogSendStat = null; } }
public ActionResult Search(String name) { string XSSName = AntiXssEncoder.HtmlEncode(name, true); var connectionString = ConfigurationManager.ConnectionStrings["SQLiteConnection"].ConnectionString; List <Pet> pets = new List <Pet>(); Pet pet; using (var m_dbConnection = new SQLiteConnection(connectionString)) { m_dbConnection.Open(); SQLiteCommand command = new SQLiteCommand("SELECT * FROM tblpets WHERE petName LIKE @petName", m_dbConnection); command.Parameters.AddWithValue("@petName", "%" + XSSName + "%"); using (SQLiteDataReader reader = command.ExecuteReader()) { while (reader.Read()) { pet = new Pet(); // adding messages to the list pet.PetID = int.Parse(AntiXssEncoder.HtmlEncode(reader.GetInt32(0).ToString(), true)); pet.PetName = AntiXssEncoder.HtmlEncode(reader.GetString(1).Trim(), true); pet.Price = Decimal.Parse(AntiXssEncoder.HtmlEncode(reader.GetDecimal(2).ToString(), true)); pet.PetType = AntiXssEncoder.HtmlEncode(reader.GetString(3).Trim(), true); pets.Add(pet); } } JavaScriptSerializer jss = new JavaScriptSerializer(); string output = jss.Serialize(pets); return(Content(output)); } }
private static void AntiXssEncode(DbChangeTracker tracker) { var addedModifiedEntries = tracker.Entries().Where(e => e.State == EntityState.Added | e.State == EntityState.Modified); foreach (var entry in addedModifiedEntries) { var entity = entry.Entity; var type = entity.GetType(); var properties = type.GetProperties(); foreach (var property in properties) { if (property.PropertyType != typeof(string)) { continue; } var value = property.GetValue(entity, null); if (value == null) { continue; } value = AntiXssEncoder.HtmlEncode(value.ToString(), true); property.SetValue(entity, value, null); } } }
private void SavePage() { var encodedName = AntiXssEncoder.HtmlEncode(txtName.Value, false); var encodedDefinition = AntiXssEncoder.HtmlEncode(txtDefinition.Value, false); var encodedBreadcrumb = AntiXssEncoder.HtmlEncode(txtBreadcrumb.Value, false); if (_metaPage == null) { // Prepare new page _metaPage = new MetaPage { Breadcrumb = encodedBreadcrumb, IsSystem = false, MetaDefinition = "", PageDefinition = encodedDefinition, PageName = encodedName, metapage_guid = Guid.NewGuid(), IsVisible = (ddlVisible.Value == "Yes") }; UnitOfWork.Repository <MetaPage>().Save(_metaPage); } else { // Prepare updated page _metaPage.PageName = encodedName; _metaPage.PageDefinition = encodedDefinition; _metaPage.Breadcrumb = encodedBreadcrumb; _metaPage.IsVisible = (ddlVisible.Value == "Yes"); UnitOfWork.Repository <MetaPage>().Update(_metaPage); } UnitOfWork.Complete(); HttpCookie cookie = new HttpCookie("PopUpMessage"); cookie.Value = String.Format("Page {0} successfully", _formMode == FormMode.AddMode ? "added" : "updated"); Response.Cookies.Add(cookie); Response.Redirect("PageViewer.aspx?guid=" + _metaPage.metapage_guid.ToString()); }
/// <summary> /// 发送一封回复邮件 /// </summary> /// <param name="toEmailAddress">收件人</param> /// <param name="emailTitle">邮件标题</param> /// <param name="emailBody">邮件正文(已经做过XSS攻击防御)</param> /// <param name="nickName">收件人昵称(已经做过XSS攻击防御)</param> /// <param name="titleLink">邮件模板中的标题链接</param> /// <param name="title">邮件模板中的文章标题</param> /// <param name="moreLink">邮件模板中的查看更多</param> /// <returns></returns> public static void SendReplyEmailAsync(string toEmailAddress, string emailTitle, string emailBody, string nickName, string titleLink, string title, string moreLink) { string emailHTML = FileCommon.ReadToString(HttpContext.Current.Server.MapPath(emailFromReplyTemplatePath)); string emailContent = emailHTML.Replace("{nickName}", AntiXssEncoder.HtmlEncode(nickName, false)).Replace("{titleLink}", titleLink).Replace("{title}", title).Replace("{body}", AntiXssEncoder.HtmlEncode(emailBody, false)).Replace("{moreLink}", moreLink); Task.Run(() => { lock (@lock) { try { Mailer.SendEmail(emailSmtpServerHost, emailSmtpServerPort, emailFromAddress, emailFromAddress, emailFromPwd, toEmailAddress, emailTitle, emailContent, 100); } catch (Exception e) { logManager.Error(string.Format("发送邮件异常(catch){2}【收件人】{0}{2}【邮件正文】{2}{1}", toEmailAddress, emailContent, Environment.NewLine), e); } } }); //Mailer.SendEmailAsync(emailSmtpServerHost, emailSmtpServerPort, emailFromAddress, emailFromAddress, emailFromPwd, toEmailAddress, emailTitle, emailContent, 100, (sender, e) => //{ // if (e.Error != null) // { // logManager.Error(string.Format("发送邮件异常(async){2}【收件人】{0}{2}【邮件正文】{2}{1}", toEmailAddress, emailContent, Environment.NewLine), e.Error); // } //}); }
public ActionResult Create(ForumMessage msg) { if (Session["LoggedUserName"] == null) { Logging.Log("POST : Forum create message page", Logging.AccessType.Anonymous); return(RedirectToAction("Index", "Login")); } if (ModelState.IsValid) { var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["SQLiteConnection"].ConnectionString; using (var m_dbConnection = new SQLiteConnection(connectionString)) { m_dbConnection.Open(); SQLiteCommand command = new SQLiteCommand("INSERT INTO tblforum (userId, subject, body) VALUES (@userId,@subject,@body)", m_dbConnection); command.Parameters.AddWithValue("@userId", int.Parse(Session["LoggedUserId"].ToString())); command.Parameters.AddWithValue("@body", AntiXssEncoder.HtmlEncode(msg.Body, true)); command.Parameters.AddWithValue("@subject", AntiXssEncoder.HtmlEncode(msg.Subject, true)); try { command.ExecuteNonQuery(); Logging.Log("POST : Successful creation of a forum post", Logging.AccessType.Valid); } catch (Exception ex) { throw new Exception(ex.Message); } } } return(RedirectToAction("Index")); }
private object SanitizeObject(object obj, Type modelType) { if (obj != null) { List <PropertyInfo> propertiesFlaggedForSanitization = modelType.GetProperties().Where(e => e.GetCustomAttribute <SanitizePropertyAttribute>() != null).ToList(); if (propertiesFlaggedForSanitization.Any()) { foreach (var propertyInfo in propertiesFlaggedForSanitization) { var raw = (string)propertyInfo.GetValue(obj); if (!string.IsNullOrEmpty(raw)) { propertyInfo.SetValue(obj, AntiXssEncoder.HtmlEncode(raw, true)); } } } } modelType.GetProperties().ToList().Where(_ => _.PropertyType.IsClass == true).ToList().ForEach(property => { var nObj = property.GetValue(obj); if (nObj != null) { var sObj = SanitizeObject(nObj, property.PropertyType); property.SetValue(obj, sObj); } }); return(obj); }
public static void HtmlEncode(string s, TextWriter writer, bool encodeSpaces) { if (s == null || s.Length == 0) { return; } if (writer == null) { throw new ArgumentNullException("writer"); } if (encodeSpaces) { for (int i = 0; i < s.Length; i++) { if (s[i] == ' ') { writer.Write(" "); } else { writer.Write(AntiXssEncoder.HtmlEncode(s.Substring(i, 1), false)); } } return; } writer.Write(AntiXssEncoder.HtmlEncode(s, false)); }
private void BuildGroupHeaderDiv(IExchangePrincipal groupExchangePrincipal) { this.encodedGroupDisplayName = AntiXssEncoder.HtmlEncode(groupExchangePrincipal.MailboxInfo.DisplayName, false); string arg = string.Format("<div style=\"font-size:21px;margin-left:19px;position:absolute;top:0px;left:0px;text-overflow: ellipsis;overflow:hidden;white-space:nowrap;max-width:95%\">{0}</div><div style=\"font-size:12px;color:#666666;margin-top:24px;margin-left:20px\">{1}</div>", this.encodedGroupDisplayName, this.GetGroupTypeMessage(groupExchangePrincipal.ModernGroupType)); this.groupHeaderDiv = string.Format("<table cellspacing=\"0\"cellpadding=\"0\"border=\"0\" style=\"width:100%; max-width:600px\"><tbody><tr><td style=\"width:50px;height:50px;position:relative\"><div><img style=\"top: 0px; display: inline; width:50px\" src=\"{0}\"></div><div style=\"position:absolute;top:0px\"><img style=\"top: 0px; display: inline; width:50px\"src=\"service.svc/s/GetUserPhoto?email={1}&UA=0&size=HR64x64\"onerror=\"this.style.display='none'\"></div></td><td style=\"color:#333333;position:relative\">{2}</td></tr></tbody></table>", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAYAAADimHc4AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAUpSURBVHhe7Zu9ctswEIT5/o+TmbyG0zlFZpQihYoUKlKoSMFwEUGGoQWIw99BInZmC8si8fMd7w6Ms3z98nWd1vMEoOwJQNkTgLInAGVPAMqeAJQ9ASh7AlD2BKDsCUDZE4CyJwBlTwDKngCUPQEoewJQ9gSg7AlA2ROAsicAZU8Ayp4AlD0BKHsCUPYEoOynAXD6eVovl8t6vV5XX/gMv8N32LUje3gA51/ndf172+lEXX5f6L1G9LAA3r+/izfe1zM8EUMCMFFfSdc/VzrGKB4OQM3NtxoZwlAATj9Oty2rr1EhDAWgNOfv6Xw+03E1PQwAdC499PbtjY6v5SQAmDSiJ9aDo2th16a6lzBfNr7UqFVIaw9P7fYzPsfv2XW+owCwqWzTg9oGRx5n94q5V/Rb5czRWjrXvTNJEEDJpkgLXuvc7yunICMLZM9zuy6UISgA82iVahuU3du3OXApiM0l5FpzZGnpAUCVzb8pJdJQWzSUmqPhmvJP558AtMjFe61fTeASpaYhUQ1MlNuJ3QGYHNdIdgzm3vn/roQU2eJUDrmd2B1AC9JWsU5AU2w+rlsGh02BBkCPQuguzLWm2Hysm+/J7Qk0AHrk4dCrYU3FzgM4XLYWIBsAPYQF+YvsNXZIMQA9ahP2ZOnVh4deAagV4U1RAD20rX1BaugltlCtNhQKAcDnvbS06P1DYovVOohBbD7woQC0PH9EdetCmLsC6JkC2GLhlmeQkGIn4ZcEECrCcKsTZ0x774J6qVsKCrWh1r27ITYH173ms/SKPrS7bKHWPR/72KsR6x4HMWjpUgQjBc91r3TIxvbd43yEtPz/JNz4cdvLt66bz0XwlxGtmwPMxQBomoYSo9+6ZeTFOh/m1mkR2ccAgFtFHhbhLirFTU7nwkCwbpUWbVNyB9CC9l7nE3PNJ0Ea+b6rywmGOwC4akuaGXG+SyNQkvNDrp0W3Y7wEwC4yiNXafOt8XRKC2LJ08dcC4K7+fADALikKNdeuGsULUS0CRK/Zm0/43NJxyW1geCPm6rtOn/zYQoAxmIlTwMiVFJwcX98H2kP1vjPFBhfMmdraaqOHfyCAKzvUUdSAD7DzRlZZtzLnDADUYT74Tvs2lrGXGlgbXPC3CTjI2hKn8YFi65RqPYseZpyojLFWGeKpE9zjm0wLrcxgzmq1FhIjmKPbY4lAWCFa9i9Su2msA8AN9UsYsUn7C0oSiPRBICfIoSqGZh+IDwAgGpEX/HmO8pJCfg+rqulUghIOSwQKACjgujDZJtomxPyJoqfvyFYIOYbK/KlcseT2E05vsIArLbFoHj5MGLdQs3IG0mpNcEEwxYkJhh2tA8gIjZ4zdQzokJZIVfZABDlbCKvGv1WoXXnpr1sAKxQm0JzALH0m5JumLIBsFcHqQedZxc7uOam3mwALApyDjvPKFaMURtylA3AnwB8GG35vtb6swCwQnSU/G/lrx/OKcRZAFgBRk04klg7mtMBZgFg74tip71XVK09yAJQi/4zi2WBnC4wC4A/MNzq/cuoqtUJ1QNwMLFGJOclpBwAacFye+Bnl78PsFRiAIz80TogK38fYKnkAEjuO1oHZFWjGREDYNX/sADI+7DmANiLqKO8A/JVIxjFAOYZ4EPDADjaGcCKNSTS19JiAP6A8FFFO0JhSz4BFMrfC+lhTAaAHMKa/QnKk8jfD1giEYAaj9yrif3LoEQTQKFKmxIRgBpt16uJAZC05RNAodie9AWQ+fcwr6KyoFzXf8jAL38D/RRdAAAAAElFTkSuQmCC", groupExchangePrincipal.MailboxInfo.PrimarySmtpAddress.ToString(), arg); }
public ActionResult GetStage1PetPrice(string petName) { if (Session["LoggedUserID"] == null) { Logging.Log("Get stage1 price page", Logging.AccessType.Anonymous); return(RedirectToAction("Index", "Login")); } string petNameXSS = AntiXssEncoder.HtmlEncode(petName, true); string price = string.Empty; var connectionString = ConfigurationManager.ConnectionStrings["SQLiteConnection"].ConnectionString; using (var m_dbConnection = new SQLiteConnection(connectionString)) { m_dbConnection.Open(); SQLiteCommand command = new SQLiteCommand("select price from tblpets where petName = @petName", m_dbConnection); command.Parameters.AddWithValue("@petName", petNameXSS); using (SQLiteDataReader reader = command.ExecuteReader()) { while (reader.Read()) { price = reader.GetDecimal(0).ToString(); } } return(Json(price, JsonRequestBehavior.AllowGet)); } }
public ActionResult GetStage1PetNames(string petType) { if (Session["LoggedUserID"] == null) { Logging.Log("Get stage1 pet names", Logging.AccessType.Anonymous); return(RedirectToAction("Index", "Login")); } string petTypeXSS = AntiXssEncoder.HtmlEncode(petType, true); List <SelectListItem> petNameList = new List <SelectListItem>(); var connectionString = ConfigurationManager.ConnectionStrings["SQLiteConnection"].ConnectionString; using (var m_dbConnection = new SQLiteConnection(connectionString)) { m_dbConnection.Open(); SQLiteCommand command = new SQLiteCommand("select petName from tblpets where petType = @petType", m_dbConnection); command.Parameters.AddWithValue("@petType", petTypeXSS); using (SQLiteDataReader reader = command.ExecuteReader()) { while (reader.Read()) { petNameList.Add(new SelectListItem() { Text = reader.GetString(0).Trim(), Value = reader.GetString(0).Trim() }); } } return(Json(petNameList, JsonRequestBehavior.AllowGet)); } }
public ActionResult Subscribe(SubscribeFormViewModel viewModel) { if (!this.IsLicensed) { return(this.Content(this.LicensingMessage)); } if (ModelState.IsValid) { string error; bool isSucceeded = this.Model.AddSubscriber(viewModel, out error); this.ViewBag.Error = error; this.ViewBag.IsSucceeded = isSucceeded; this.ViewBag.Email = AntiXssEncoder.HtmlEncode(viewModel.Email, false); if (isSucceeded) { var validator = ObjectFactory.Resolve <IRedirectUriValidator>(); var redirectUrl = viewModel.RedirectPageUrl; if (this.Model.SuccessfullySubmittedForm == SuccessfullySubmittedForm.OpenSpecificPage && !string.IsNullOrEmpty(viewModel.RedirectPageUrl) && validator.IsValid(redirectUrl)) { return(this.Redirect(viewModel.RedirectPageUrl)); } this.ModelState.Clear(); } } var fullTemplateName = this.templateNamePrefix + this.TemplateName; viewModel = this.Model.CreateViewModel(); return(this.View(fullTemplateName, viewModel)); }
public ActionResult SysList(ViewModels.SysInfoViewModels FormCols) { /*初始化宣告*/ ViewModels.SysInfoViewModels vmSysInfo = null; try { /*OWASP檢查*/ OWASP_Verify(FormCols.SysName); OWASP_Verify(FormCols.GrpName); /*參數透過AntiXss編碼*/ FormCols.SysName = AntiXssEncoder.HtmlEncode(FormCols.SysName, true); FormCols.GrpName = AntiXssEncoder.HtmlEncode(FormCols.GrpName, true); /*取得系統清單*/ vmSysInfo = new ViewModels.SysInfoViewModels(); vmSysInfo.SysName = Server.HtmlDecode(FormCols.SysName); vmSysInfo.GrpName = Server.HtmlDecode(FormCols.GrpName); vmSysInfo.SysInfoList = getSysInfo(Server.HtmlDecode(FormCols.SysName), Server.HtmlDecode(FormCols.GrpName)).ToPagedList(1, 3); return(View(vmSysInfo)); } catch (Exception ex) { return(RedirectToAction("Exception", "TGW", new { @MsgCont = ex.Message })); } finally { vmSysInfo = null; } }
public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) { if (actionContext.ActionArguments != null && actionContext.ActionArguments.Any()) { var arguments = actionContext.ActionArguments; foreach (var argument in arguments) { var properties = argument.Value.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public) .Where(prop => prop.CanRead && prop.CanWrite && prop.PropertyType == typeof(string) && prop.GetGetMethod(true).IsPublic&& prop.GetSetMethod(true).IsPublic); foreach (var propertyInfo in properties) { if (propertyInfo.GetValue(argument.Value) is string stringValue) { var encodedString = AntiXssEncoder.HtmlEncode(stringValue, true); if (encodedString != stringValue) { actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Forbidden input. The following characters are not allowed: &, <, >, \", '"); return(Task.CompletedTask); } } } } } return(base.OnActionExecutingAsync(actionContext, cancellationToken)); }
public ActionResult DelSysInfo(int SCodeByDel = 0) { /*參數透過AntiXss編碼*/ SCodeByDel = Convert.ToInt16(AntiXssEncoder.HtmlEncode(SCodeByDel.ToString(), true)); /*初始化宣告*/ App_Code.clsUtility objUtil = null; string SqlCmd = ""; try { objUtil = new App_Code.clsUtility(); using (var SqlConn = new SqlConnection(objUtil.ConnStrDecrypt(ConfigurationManager.ConnectionStrings["TGWLogs"].ConnectionString))) { SqlCmd = "DELETE SYSTEM_LIST WHERE intSYS_CODE = @SysCode"; var SqlParams = new { @SysCode = SCodeByDel }; SqlConn.Execute(SqlCmd, SqlParams); return(RedirectToAction("SysList", "TGW", new { PageIdx = 1 })); } } catch (Exception ex) { return(RedirectToAction("Exception", "TGW", new { @MsgCont = ex.Message })); } }
public ContactRecordViewModel SanitizeContactRecordViewModel(ContactRecordViewModel viewModel) { viewModel.Comments = AntiXssEncoder.HtmlEncode(viewModel.Comments, false); viewModel.PassAlongComments = AntiXssEncoder.HtmlEncode(viewModel.PassAlongComments, false); viewModel.Subject = AntiXssEncoder.HtmlEncode(viewModel.Subject, false); viewModel.PassAlongFollowUpComments = AntiXssEncoder.HtmlEncode(viewModel.PassAlongFollowUpComments, false); return(viewModel); }
public PrayerRequestViewModel SanitizePrayerRequestViewModel(PrayerRequestViewModel viewModel) { viewModel.Comments = AntiXssEncoder.HtmlEncode(viewModel.Comments, false); viewModel.PassAlongComments = AntiXssEncoder.HtmlEncode(viewModel.PassAlongComments, false); viewModel.Subject = AntiXssEncoder.HtmlEncode(viewModel.Subject, false); viewModel.PassAlongComments = AntiXssEncoder.HtmlEncode(viewModel.PassAlongFollowUpComments, false); return(viewModel); }