private static void Execute(string words) { SearchTokens st = new SearchTokens(); Sanitizer sa = new Sanitizer(); Console.WriteLine(""); Console.WriteLine("Simple Tokenizer"); List<string> tokens = st.ForSearch(words); foreach (string token in tokens) { Console.Write("[" + token + "] "); } Console.WriteLine(""); Console.WriteLine("-------------------------------------------"); Console.WriteLine(""); Console.WriteLine("Descriminated Tokenizer with escape"); TokenLists tokenList = st.ForSearchDescriminated(words); Console.WriteLine(" Singular"); Console.Write(" "); foreach (string token in tokenList.SingularWords) { Console.Write("[" + token + "] "); } Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine(" Agregated and Escaped words"); Console.Write(" "); foreach (string token in tokenList.AgregatedWords) { Console.Write("[" + sa.EscapeNonAlphanumeric(token) + "] "); } }
public static string GetSafeHtml(string input) { return(Sanitizer.GetSafeHtmlFragment(input)); }
/// <summary> /// Takes in HTML and returns santized Html/string /// </summary> /// <param name="html"></param> /// <param name="useXssSantiser"></param> /// <returns></returns> public static string ScrubHtml(string html, bool useXssSantiser = false) { if (string.IsNullOrEmpty(html)) { return(html); } // clear the flags on P so unclosed elements in P will be auto closed. HtmlNode.ElementsFlags.Remove("p"); var doc = new HtmlDocument(); doc.LoadHtml(html); var finishedHtml = html; // Embed Urls if (doc.DocumentNode != null) { // Get all the links we are going to var tags = doc.DocumentNode.SelectNodes("//a[contains(@href, 'youtube.com')]|//a[contains(@href, 'youtu.be')]|//a[contains(@href, 'vimeo.com')]|//a[contains(@href, 'screenr.com')]|//a[contains(@href, 'instagram.com')]"); if (tags != null) { // find formatting tags foreach (var item in tags) { if (item.PreviousSibling == null) { // Prepend children to parent node in reverse order foreach (var node in item.ChildNodes.Reverse()) { item.ParentNode.PrependChild(node); } } else { // Insert children after previous sibling foreach (var node in item.ChildNodes) { item.ParentNode.InsertAfter(node, item.PreviousSibling); } } // remove from tree item.Remove(); } } //Remove potentially harmful elements var nc = doc.DocumentNode.SelectNodes("//script|//link|//iframe|//frameset|//frame|//applet|//object|//embed"); if (nc != null) { foreach (var node in nc) { node.ParentNode.RemoveChild(node, false); } } //remove hrefs to java/j/vbscript URLs nc = doc.DocumentNode.SelectNodes("//a[starts-with(translate(@href, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'javascript')]|//a[starts-with(translate(@href, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'jscript')]|//a[starts-with(translate(@href, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'vbscript')]"); if (nc != null) { foreach (var node in nc) { node.SetAttributeValue("href", "#"); } } //remove img with refs to java/j/vbscript URLs nc = doc.DocumentNode.SelectNodes("//img[starts-with(translate(@src, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'javascript')]|//img[starts-with(translate(@src, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'jscript')]|//img[starts-with(translate(@src, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'vbscript')]"); if (nc != null) { foreach (var node in nc) { node.SetAttributeValue("src", "#"); } } //remove on<Event> handlers from all tags nc = doc.DocumentNode.SelectNodes("//*[@onclick or @onmouseover or @onfocus or @onblur or @onmouseout or @ondblclick or @onload or @onunload or @onerror]"); if (nc != null) { foreach (var node in nc) { node.Attributes.Remove("onFocus"); node.Attributes.Remove("onBlur"); node.Attributes.Remove("onClick"); node.Attributes.Remove("onMouseOver"); node.Attributes.Remove("onMouseOut"); node.Attributes.Remove("onDblClick"); node.Attributes.Remove("onLoad"); node.Attributes.Remove("onUnload"); node.Attributes.Remove("onError"); } } // remove any style attributes that contain the word expression (IE evaluates this as script) nc = doc.DocumentNode.SelectNodes("//*[contains(translate(@style, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'expression')]"); if (nc != null) { foreach (var node in nc) { node.Attributes.Remove("stYle"); } } // build a list of nodes ordered by stream position var pos = new NodePositions(doc); // browse all tags detected as not opened foreach (var error in doc.ParseErrors.Where(e => e.Code == HtmlParseErrorCode.TagNotOpened)) { // find the text node just before this error var last = pos.Nodes.OfType <HtmlTextNode>().LastOrDefault(n => n.StreamPosition < error.StreamPosition); if (last != null) { // fix the text; reintroduce the broken tag last.Text = error.SourceText.Replace("/", "") + last.Text + error.SourceText; } } finishedHtml = doc.DocumentNode.WriteTo(); } // The reason we have this option, is using the santiser with the MarkDown editor // causes problems with line breaks. if (useXssSantiser) { return(SanitizerCompatibleWithForiegnCharacters(Sanitizer.GetSafeHtmlFragment(finishedHtml))); } return(finishedHtml); }
public string AddReturnInsertedKey(string primaryKeyName) { return($"RETURNING {Sanitizer.SanitizeIdentifierName(primaryKeyName)}"); }
public void Setup() { sanitizer = new Sanitizer(); }
public ResourceSlugAttribute() { Evaluator = v => Sanitizer.IsSlug((string)v); }
public ActionResult ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return(JsonValidationError()); } if (!string.IsNullOrEmpty(model.NewPassword)) { if (!Regex.IsMatch(model.NewPassword, SiteUtils.GetPasswordRegex())) { ModelState.AddModelError("Password", "Password does not meet policy!"); return(JsonValidationError()); } } if (model.OldPassword == model.NewPassword) { ModelState.AddModelError("Error", "Old Password and New Password cannot be same"); return(JsonValidationError()); } var response = new BoolResponse(); var result = _authenticationService.Login(_sessionContext.CurrentUser.Username, Sanitizer.GetSafeHtmlFragment(model.OldPassword), true); if (result != null) { response.IsValid = _customerRepository.ChangePassword(Sanitizer.GetSafeHtmlFragment(model.OldPassword), Sanitizer.GetSafeHtmlFragment(model.NewPassword), _sessionContext.CurrentUser.UserId.ToString()).Result; return(JsonSuccess(response, JsonRequestBehavior.AllowGet)); } else { ModelState.AddModelError("Error", "Old Password didn't match."); return(JsonValidationError()); } }
public ActionResult SignIn(LoginViewModel login) { if (!ModelState.IsValid) { return(JsonValidationError()); } var result = _authenticationService.Login(Sanitizer.GetSafeHtmlFragment(login.Username), Sanitizer.GetSafeHtmlFragment(login.Password), true); if (result == null) { ModelState.AddModelError("", "Invalid Password!"); return(JsonValidationError()); } else { //returnURL needs to be decoded string decodedUrl = string.Empty; string returnUrl = TempData["ReturnUrl"] != null ? TempData["ReturnUrl"].ToString() : ""; if (!string.IsNullOrEmpty(returnUrl)) { if (returnUrl.ToLower().Contains("passwordrecovery")) { returnUrl = ""; } } decodedUrl = Server.UrlDecode(returnUrl); var resp = new BoolResponse { IsValid = true, MessageCode = result.SessionId, Message = result.FirstName, ReturnUrl = decodedUrl }; SiteUtils.SetBasketAction(resetAction: true); return(JsonSuccess(resp, JsonRequestBehavior.AllowGet)); } }
[ValidateInput(false)]//若為屬性可用[AllowHtml] public ActionResult HtmlEditor(string UserEditor) { ViewBag.UserEditor = Sanitizer.GetSafeHtmlFragment(UserEditor); return(View()); }
/// <summary> /// Write an input stream to an output folder /// </summary> /// <param name="inputStream">Input stream to be moved</param> /// <param name="outDir">Output directory to build to</param> /// <param name="rom">DatItem representing the new information</param> /// <returns>True if the write was a success, false otherwise</returns> /// <remarks>This works for now, but it can be sped up by using Ionic.Zip or another zlib wrapper that allows for header values built-in. See edc's code.</remarks> public virtual bool Write(Stream inputStream, string outDir, Rom rom) { bool success = false; // If either input is null or empty, return if (inputStream == null || rom == null || rom.Name == null) { return(success); } // If the stream is not readable, return if (!inputStream.CanRead) { return(success); } // Set internal variables FileStream outputStream = null; // Get the output folder name from the first rebuild rom string fileName; if (writeToParent) { fileName = Path.Combine(outDir, Sanitizer.RemovePathUnsafeCharacters(rom.Name)); } else { fileName = Path.Combine(outDir, Sanitizer.RemovePathUnsafeCharacters(rom.Machine.Name), Sanitizer.RemovePathUnsafeCharacters(rom.Name)); } try { // If the full output path doesn't exist, create it if (!Directory.Exists(Path.GetDirectoryName(fileName))) { Directory.CreateDirectory(Path.GetDirectoryName(fileName)); } // Overwrite output files by default outputStream = FileExtensions.TryCreate(fileName); // If the output stream isn't null if (outputStream != null) { // Copy the input stream to the output inputStream.Seek(0, SeekOrigin.Begin); int bufferSize = 4096 * 128; byte[] ibuffer = new byte[bufferSize]; int ilen; while ((ilen = inputStream.Read(ibuffer, 0, bufferSize)) > 0) { outputStream.Write(ibuffer, 0, ilen); outputStream.Flush(); } outputStream.Dispose(); if (rom.ItemType == ItemType.Rom) { if (!string.IsNullOrWhiteSpace(rom.Date)) { File.SetCreationTime(fileName, DateTime.Parse(rom.Date)); } } success = true; } } catch (Exception ex) { logger.Error(ex); success = false; } finally { outputStream?.Dispose(); } return(success); }
/// <summary> /// Read set information /// </summary> /// <param name="cmpr">ClrMameProReader to use to parse the header</param> /// <param name="resource">True if the item is a resource (bios), false otherwise</param> /// <param name="filename">Name of the file to be parsed</param> /// <param name="indexId">Index ID for the DAT</param> private void ReadSet( ClrMameProReader cmpr, bool resource, // Standard Dat parsing string filename, int indexId) { // Prepare all internal variables bool containsItems = false; Machine machine = new Machine() { MachineType = (resource ? MachineType.Bios : MachineType.NULL), }; // If there's no subtree to the header, skip it if (cmpr == null || cmpr.EndOfStream) { return; } // While we don't hit an end element or end of stream while (!cmpr.EndOfStream) { cmpr.ReadNextLine(); // Ignore comments and nothingness if (cmpr.RowType == CmpRowType.None || cmpr.RowType == CmpRowType.Comment) { continue; } // If we reached the end of a section, break if (cmpr.RowType == CmpRowType.EndTopLevel) { break; } // Handle any standalone items if (cmpr.RowType == CmpRowType.Standalone && cmpr.Standalone != null) { string itemKey = cmpr.Standalone?.Key.ToLowerInvariant(); string itemVal = cmpr.Standalone?.Value; switch (itemKey) { case "name": machine.Name = itemVal; break; case "description": machine.Description = itemVal; break; case "year": machine.Year = itemVal; break; case "manufacturer": machine.Manufacturer = itemVal; break; case "category": machine.Category = itemVal; break; case "cloneof": machine.CloneOf = itemVal; break; case "romof": machine.RomOf = itemVal; break; case "sampleof": machine.SampleOf = itemVal; break; } } // Handle any internal items else if (cmpr.RowType == CmpRowType.Internal && !string.IsNullOrWhiteSpace(cmpr.InternalName) && cmpr.Internal != null) { containsItems = true; string itemKey = cmpr.InternalName; // Create the proper DatItem based on the type ItemType itemType = itemKey.AsItemType() ?? ItemType.Rom; DatItem item = DatItem.Create(itemType); // Then populate it with information item.CopyMachineInformation(machine); item.Source.Index = indexId; item.Source.Name = filename; // Loop through all of the attributes foreach (var kvp in cmpr.Internal) { string attrKey = kvp.Key; string attrVal = kvp.Value; switch (attrKey) { //If the item is empty, we automatically skip it because it's a fluke case "": continue; // Regular attributes case "name": item.SetFields(new Dictionary <Field, string> { [Field.DatItem_Name] = attrVal }); break; case "size": if (item.ItemType == ItemType.Rom) { (item as Rom).Size = Sanitizer.CleanLong(attrVal); } break; case "crc": if (item.ItemType == ItemType.Rom) { (item as Rom).CRC = attrVal; } break; case "md5": if (item.ItemType == ItemType.Disk) { (item as Disk).MD5 = attrVal; } else if (item.ItemType == ItemType.Media) { (item as Media).MD5 = attrVal; } else if (item.ItemType == ItemType.Rom) { (item as Rom).MD5 = attrVal; } break; #if NET_FRAMEWORK case "ripemd160": if (item.ItemType == ItemType.Rom) { (item as Rom).RIPEMD160 = attrVal; } break; #endif case "sha1": if (item.ItemType == ItemType.Disk) { (item as Disk).SHA1 = attrVal; } else if (item.ItemType == ItemType.Media) { (item as Media).SHA1 = attrVal; } else if (item.ItemType == ItemType.Rom) { (item as Rom).SHA1 = attrVal; } break; case "sha256": if (item.ItemType == ItemType.Media) { (item as Media).SHA256 = attrVal; } else if (item.ItemType == ItemType.Rom) { (item as Rom).SHA256 = attrVal; } break; case "sha384": if (item.ItemType == ItemType.Rom) { (item as Rom).SHA384 = attrVal; } break; case "sha512": if (item.ItemType == ItemType.Rom) { (item as Rom).SHA512 = attrVal; } break; case "spamsum": if (item.ItemType == ItemType.Media) { (item as Media).SpamSum = attrVal; } else if (item.ItemType == ItemType.Rom) { (item as Rom).SpamSum = attrVal; } break; case "status": ItemStatus tempFlagStatus = attrVal.AsItemStatus(); if (item.ItemType == ItemType.Disk) { (item as Disk).ItemStatus = tempFlagStatus; } else if (item.ItemType == ItemType.Rom) { (item as Rom).ItemStatus = tempFlagStatus; } break; case "date": if (item.ItemType == ItemType.Release) { (item as Release).Date = attrVal; } else if (item.ItemType == ItemType.Rom) { (item as Rom).Date = attrVal; } break; case "default": if (item.ItemType == ItemType.BiosSet) { (item as BiosSet).Default = attrVal.AsYesNo(); } else if (item.ItemType == ItemType.Release) { (item as Release).Default = attrVal.AsYesNo(); } break; case "description": if (item.ItemType == ItemType.BiosSet) { (item as BiosSet).Description = attrVal; } break; case "region": if (item.ItemType == ItemType.Release) { (item as Release).Region = attrVal; } break; case "language": if (item.ItemType == ItemType.Release) { (item as Release).Language = attrVal; } break; } } // Now process and add the rom ParseAddHelper(item); } } // If no items were found for this machine, add a Blank placeholder if (!containsItems) { Blank blank = new Blank() { Source = new Source { Index = indexId, Name = filename, }, }; blank.CopyMachineInformation(machine); // Now process and add the rom ParseAddHelper(blank); } }
/// <summary> /// Constructio /// </summary> /// <returns></returns> public BaseTemplate_Create <T, V> Create() { try { // first of all, we check if user has the right to perform this operation! if (HasUserToBeAuthenticated()) { if (!IsUserAuthenticated() || !HasUserPrivilege()) { return(this); } } //Run the parameters through the cleanse process dynamic cleansedParams = Cleanser.Cleanse(Request.parameters); try { DTO = GetDTO(cleansedParams); } catch { throw new InputFormatException(); } DTO = Sanitizer.Sanitize(DTO); DTOValidationResult = Validator.Validate(DTO); if (!DTOValidationResult.IsValid) { OnDTOValidationError(); return(this); } Ado.StartTransaction(IsolationLevel.Snapshot); // The Actual Creation should happen here by the specific class! if (!Execute()) { Ado.RollbackTransaction(); OnExecutionError(); return(this); } Ado.CommitTransaction(); OnExecutionSuccess(); return(this); } catch (FormatException formatException) { //A FormatException error has been caught, rollback the transaction, log the error and return a message to the caller Ado.RollbackTransaction(); Log.Instance.Error(formatException); Response.error = Label.Get("error.schema"); return(this); } catch (InputFormatException inputError) { //An error has been caught, rollback the transaction, log the error and return a message to the caller Ado.RollbackTransaction(); Log.Instance.Error(inputError); Response.error = Label.Get("error.schema"); return(this); } catch (Exception ex) { //An error has been caught, rollback the transaction, log the error and return a message to the caller Ado.RollbackTransaction(); Log.Instance.Error(ex); Response.error = Label.Get("error.exception"); return(this); } finally { Dispose(); } }
/// <summary> /// Saves the specified site activity rule id. /// </summary> /// <param name="siteActivityRuleId">The site activity rule id.</param> public void Save(Guid siteActivityRuleId) { var dataManager = new DataManager(); var txtFormTitle = ((TextBox)rmpWizard.FindPageViewByID("InstructionAndText").Controls[0].FindControl("txtFormTitle")); var txtTextButton = ((TextBox)rmpWizard.FindPageViewByID("InstructionAndText").Controls[0].FindControl("txtTextButton")); var txtFormWidth = ((RadNumericTextBox)rmpWizard.FindPageViewByID("Design").Controls[0].FindControl("txtFormWidth")); var ucCssEditorInstruction = ((CssEditor)rmpWizard.FindPageViewByID("Design").Controls[0].FindControl("ucCssEditorInstruction")); var ucCssEditorColumns = ((CssEditor)rmpWizard.FindPageViewByID("Design").Controls[0].FindControl("ucCssEditorColumns")); var ucCssEditorButton = ((CssEditor)rmpWizard.FindPageViewByID("Design").Controls[0].FindControl("ucCssEditorButton")); var rcpBackgroundColor = ((RadColorPicker)rmpWizard.FindPageViewByID("Design").Controls[0].FindControl("rcpBackgroundColor")); var txtUrl = ((TextBox)rmpWizard.FindPageViewByID("ActionAfterProcessing").Controls[0].FindControl("txtUrl")); var plInviteFriendSettings = ((Panel)rmpWizard.FindPageViewByID("ActionAfterProcessing").Controls[0].FindControl("plInviteFriendSettings")); var dcbWorkflowTemplate = ((DictionaryOnDemandComboBox)rmpWizard.FindPageViewByID("ActionAfterProcessing").Controls[0].FindControl("dcbWorkflowTemplate")); var ucPopupSiteActionTemplate = ((PopupSiteActionTemplate)rmpWizard.FindPageViewByID("ActionAfterProcessing").Controls[0].FindControl("ucPopupSiteActionTemplate")); tbl_SiteActivityRules siteActivityRule = null; if (!IsEditMode) { siteActivityRule = dataManager.SiteActivityRules.CopyByID(siteActivityRuleId); siteActivityRule.TemplateID = siteActivityRuleId; siteActivityRule.SiteID = CurrentUser.Instance.SiteID; siteActivityRule.Code = string.Concat("form_", DateTime.Now.ToString("[ddMMyyyy]_[mmss]")); var currentSiteColumnCategories = dataManager.ColumnCategories.SelectAll(CurrentUser.Instance.SiteID); foreach (tbl_SiteActivityRuleLayout ruleLayout in siteActivityRule.tbl_SiteActivityRuleLayout) { ruleLayout.SiteID = CurrentUser.Instance.SiteID; } foreach (tbl_SiteColumns siteColumns in dataManager.SiteColumns.SelectByActivityRuleId(siteActivityRule.ID)) { siteColumns.SiteID = CurrentUser.Instance.SiteID; var columnCategory = currentSiteColumnCategories.SingleOrDefault(o => o.Title == siteColumns.tbl_ColumnCategories.Title) ?? currentSiteColumnCategories.FirstOrDefault(); siteColumns.CategoryID = columnCategory.ID; } } else { siteActivityRule = dataManager.SiteActivityRules.SelectById(siteActivityRuleId); } siteActivityRule.Name = txtFormTitle.Text; siteActivityRule.TextButton = txtTextButton.Text; siteActivityRule.RepostURL = txtUrl.Text; siteActivityRule.FormWidth = (int?)txtFormWidth.Value; siteActivityRule.CSSButton = ucCssEditorButton.GetCss(); siteActivityRule.CSSForm = EncodeBackgroundCss(rcpBackgroundColor); var order = 0; var existsiteActivityRule = dataManager.SiteActivityRules.SelectById(siteActivityRuleId); foreach (var activityRuleLayout in existsiteActivityRule.tbl_SiteActivityRuleLayout) { if (string.IsNullOrEmpty(activityRuleLayout.LayoutParams)) { continue; } var toUpdate = siteActivityRule.tbl_SiteActivityRuleLayout.FirstOrDefault(o => o.Name == activityRuleLayout.Name); if (toUpdate == null) { continue; } var lp = LayoutParams.Deserialize(activityRuleLayout.LayoutParams); if (!string.IsNullOrEmpty(lp.GetValue("ShowInMaster"))) { switch ((ShowTextBlockInMaster)int.Parse(lp.GetValue("ShowInMaster"))) { case ShowTextBlockInMaster.Text: var text = ((TextBox)FindControlRecursive(rmpWizard.FindPageViewByID("InstructionAndText").Controls[0], activityRuleLayout.ID.ToString())).Text; text = text.Replace("\n", "#@#"); text = Sanitizer.GetSafeHtmlFragment(text); text = text.Replace("#@#", "\n"); toUpdate.Description = text; break; case ShowTextBlockInMaster.HTML: toUpdate.Description = ((RadEditor)FindControlRecursive(rmpWizard.FindPageViewByID("InstructionAndText").Controls[0], activityRuleLayout.ID.ToString())).Content; break; } toUpdate.CSSStyle = ucCssEditorInstruction.GetCss(); } } foreach (tbl_SiteActivityRuleLayout ruleLayout in siteActivityRule.tbl_SiteActivityRuleLayout) { if (string.IsNullOrEmpty(ruleLayout.LayoutParams) && ruleLayout.LayoutType != (int)LayoutType.Feedback && ruleLayout.LayoutType != (int)LayoutType.GroupFields && ruleLayout.LayoutType != (int)LayoutType.InviteFriend && ruleLayout.LayoutType != (int)LayoutType.Root && ruleLayout.LayoutType != (int)LayoutType.TextBlock) { ruleLayout.CSSStyle = ucCssEditorColumns.GetCss(); } } if (rmpWizard.FindPageViewByID("LogicProcessing") != null) { var ddlOutputFormatFields = ((DropDownList)rmpWizard.FindPageViewByID("LogicProcessing").Controls[0].FindControl("ddlOutputFormatFields")); var rlbDestination = ((RadListBox)rmpWizard.FindPageViewByID("LogicProcessing").Controls[0].FindControl("rlbDestination")); var plFeedBack = ((Panel)rmpWizard.FindPageViewByID("LogicProcessing").Controls[0].FindControl("plFeedBack")); var rblStep = ((RadioButtonList)rmpWizard.FindPageViewByID("LogicProcessing").Controls[0].FindControl("rblStep")); var rblKnowledgeBase = ((RadioButtonList)rmpWizard.FindPageViewByID("LogicProcessing").Controls[0].FindControl("rblKnowledgeBase")); var chxPublicationType = ((CheckBoxList)rmpWizard.FindPageViewByID("LogicProcessing").Controls[0].FindControl("chxPublicationType")); tbl_SiteActivityRuleLayout parentSiteActivityRuleLayout = (from ruleLayout in siteActivityRule.tbl_SiteActivityRuleLayout where !string.IsNullOrEmpty(ruleLayout.LayoutParams) let layoutParams = LayoutParams.Deserialize(ruleLayout.LayoutParams) where !string.IsNullOrEmpty(layoutParams.GetValue("IsUsedForAdditionalDetails")) && bool.Parse(layoutParams.GetValue("IsUsedForAdditionalDetails")) select ruleLayout).FirstOrDefault(); if (parentSiteActivityRuleLayout != null) { var idsToDelete = siteActivityRule.tbl_SiteActivityRuleLayout.Where( o => o.ParentID == parentSiteActivityRuleLayout.ID).Select(o => o.ID).ToList(); foreach (Guid id in idsToDelete) { dataManager.SiteActivityRuleLayout.Delete(id); } foreach (RadListBoxItem item in rlbDestination.Items) { var siteActivityRuleLayout = new tbl_SiteActivityRuleLayout { ID = Guid.NewGuid(), SiteID = CurrentUser.Instance.SiteID, SiteActivityRuleID = siteActivityRule.ID, Order = order, Name = item.Text, ParentID = parentSiteActivityRuleLayout.ID, LayoutType = (int)LayoutType.ProfileField }; Guid outSiteColumnId; if (Guid.TryParse(item.Value, out outSiteColumnId)) { siteActivityRuleLayout.SiteColumnID = outSiteColumnId; siteActivityRuleLayout.SysField = null; } else { siteActivityRuleLayout.SiteColumnID = null; siteActivityRuleLayout.SysField = item.Value; } /*switch (item.Value) * { * case "sys_fullname": * siteActivityRuleLayout.LayoutType = (int) LayoutType.FullName; * break; * case "sys_email": * siteActivityRuleLayout.LayoutType = (int) LayoutType.Email; * break; * case "sys_phone": * siteActivityRuleLayout.LayoutType = (int) LayoutType.Phone; * break; * case "sys_surname": * siteActivityRuleLayout.LayoutType = (int) LayoutType.Surname; * break; * case "sys_name": * siteActivityRuleLayout.LayoutType = (int) LayoutType.Name; * break; * case "sys_patronymic": * siteActivityRuleLayout.LayoutType = (int) LayoutType.Patronymic; * break; * default: * siteActivityRuleLayout.SiteColumnID = Guid.Parse(item.Value); * siteActivityRuleLayout.LayoutType = (int) LayoutType.ProfileField; * break; * }*/ order++; siteActivityRule.tbl_SiteActivityRuleLayout.Add(siteActivityRuleLayout); } parentSiteActivityRuleLayout.OutputFormatFields = int.Parse(ddlOutputFormatFields.SelectedValue); dataManager.SiteActivityRuleLayout.Update(parentSiteActivityRuleLayout); } if (plFeedBack.Visible) { var feedBackComponent = siteActivityRule.tbl_SiteActivityRuleLayout.FirstOrDefault(o => o.LayoutType == (int)LayoutType.Feedback); if (feedBackComponent != null) { var layoutParams = new List <LayoutParams>(); layoutParams.Add(new LayoutParams() { Name = "step", Value = rblStep.SelectedValue }); layoutParams.Add(new LayoutParams() { Name = "kb", Value = rblKnowledgeBase.SelectedValue }); var publicationTypeValues = (from ListItem item in chxPublicationType.Items where item.Selected select item.Value).ToList(); layoutParams.Add(new LayoutParams() { Name = "pt", Value = string.Join(",", publicationTypeValues) }); feedBackComponent.LayoutParams = LayoutParams.Serialize(layoutParams); } } } if (plInviteFriendSettings.Visible) { var inviteFriendComponent = siteActivityRule.tbl_SiteActivityRuleLayout.FirstOrDefault(o => o.LayoutType == (int)LayoutType.InviteFriend); if (inviteFriendComponent != null) { var lp = new List <LayoutParams>(); var item = new LayoutParams { Name = "WorkflowTemplateID", Value = dcbWorkflowTemplate.SelectedIdNullable.HasValue ? dcbWorkflowTemplate.SelectedId.ToString() : string.Empty }; lp.Add(item); item = new LayoutParams { Name = "SiteActionTemplateID", Value = ucPopupSiteActionTemplate.SiteActionTemplateId != Guid.Empty ? ucPopupSiteActionTemplate.SiteActionTemplateId.ToString() : string.Empty }; lp.Add(item); inviteFriendComponent.LayoutParams = LayoutParams.Serialize(lp); } } dataManager.SiteActivityRules.Update(siteActivityRule); Response.Redirect(UrlsData.AP_SiteActivityRules((int)RuleType.ExternalForm)); }
public static string Sanitize(string userInput) { return(Sanitizer.Sanitize(userInput)); }
public tbl_Testimonials SaveTestimonial(int testimonialID, string testimonialDate, string client, string company, string content) { if (String.IsNullOrEmpty(client) || String.IsNullOrEmpty(company) || String.IsNullOrEmpty(testimonialDate)) { return(null); } DateTime date = testimonialDate.ParseDateTime(); return(TestimonialsRepository.SaveTestimonial(testimonialID, date, Sanitizer.GetSafeHtmlFragment(client), Sanitizer.GetSafeHtmlFragment(company), content ?? String.Empty)); }
private void LogError(string msg) { BuildAndLogConsoleLog(msg, LogLevel.Error); _processStdErrDataQueue = WorkerProcessUtilities.AddStdErrMessage(_processStdErrDataQueue, Sanitizer.Sanitize(msg)); }
public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { if (!IsEnabled(logLevel)) { return; } // Make sure we have something to log string formattedMessage = formatter?.Invoke(state, exception); if (string.IsNullOrEmpty(formattedMessage) && exception == null) { return; } (string exceptionType, string exceptionMessage, string exceptionDetails) = exception.GetExceptionDetails(); if (exception != null) { formattedMessage = Sanitizer.Sanitize(formattedMessage); } // enumerate all the state values once, capturing the values we'll use below // last one wins string stateFunctionName = null; if (state is IEnumerable <KeyValuePair <string, object> > stateProps) { foreach (var kvp in stateProps) { if (Utility.IsFunctionName(kvp)) { stateFunctionName = kvp.Value?.ToString(); } } } var scopeProps = _scopeProvider.GetScopeDictionary(); string functionName = stateFunctionName; if (string.IsNullOrEmpty(functionName)) { if (Utility.TryGetFunctionName(scopeProps, out string scopeFunctionName)) { functionName = scopeFunctionName; } } // Build up a JSON string for the Azure Monitor 'properties' bag StringWriter sw = new StringWriter(); using (JsonTextWriter writer = new JsonTextWriter(sw) { Formatting = Formatting.None }) { writer.WriteStartObject(); WritePropertyIfNotNull(writer, "message", formattedMessage); WritePropertyIfNotNull(writer, "category", _category); WritePropertyIfNotNull(writer, "hostVersion", _hostVersion); WritePropertyIfNotNull(writer, "functionInvocationId", Utility.GetValueFromScope(scopeProps, ScopeKeys.FunctionInvocationId)); WritePropertyIfNotNull(writer, "functionName", functionName); WritePropertyIfNotNull(writer, "hostInstanceId", _hostInstanceId); WritePropertyIfNotNull(writer, "activityId", Utility.GetValueFromScope(scopeProps, ScriptConstants.LogPropertyActivityIdKey)); WritePropertyIfNotNull(writer, "level", logLevel.ToString()); WritePropertyIfNotNull(writer, nameof(exceptionDetails), exceptionDetails); WritePropertyIfNotNull(writer, nameof(exceptionMessage), exceptionMessage); WritePropertyIfNotNull(writer, nameof(exceptionType), exceptionType); writer.WriteEndObject(); } _eventGenerator.LogAzureMonitorDiagnosticLogEvent(logLevel, _hostNameProvider.Value, AzureMonitorOperationName, AzureMonitorCategoryName, _regionName, sw.ToString()); }
// [ValidateInput(false)] public ActionResult Registration(RegisterViewModel register) { if (!ModelState.IsValid) { return(JsonValidationError()); } if (!string.IsNullOrEmpty(register.Password)) { if (!Regex.IsMatch(register.Password, SiteUtils.GetPasswordRegex())) { ModelState.AddModelError("Password", "Password does not meet policy!"); return(JsonValidationError()); } } var response = new BoolResponse(); //-- to check if user's Email Address already registered var existingUser = _customerRepository.GetExistingUser(Sanitizer.GetSafeHtmlFragment(register.Email)); if (existingUser.Result != null) { if (existingUser.Result.Count > 0 && existingUser.Result[0].UserSourceType != UserSourceTypes.Newsletter.GetHashCode().ToString()) { ModelState.AddModelError("Error", "Your email address is already registered with us."); return(JsonValidationError()); } var user = new CustomerModel { Email = Sanitizer.GetSafeHtmlFragment(register.Email), Password = Sanitizer.GetSafeHtmlFragment(register.Password), NotifyByEmail = register.NotifyByEmail, NotifyByPost = register.NotifyByPost, NotifyBySMS = register.NotifyBySMS, NewsLetterSubscribed = !register.NewsLetterSubscribed, SourceProcess = register.SourceProcess, IsRegistered = true }; var result = _customerRepository.Register(user); if (result.Result.IsValid) { var loginResult = _authenticationService.Login(Sanitizer.GetSafeHtmlFragment(register.Email), Sanitizer.GetSafeHtmlFragment(register.Password), true); response.IsValid = true; SiteUtils.SetBasketAction(resetAction: true); return(JsonSuccess(response, JsonRequestBehavior.AllowGet)); } else { ModelState.AddModelError("Error", "Registration failed!"); return(JsonValidationError()); } } else { ModelState.AddModelError("Error", " '+' Symbol is not allowed in Email!"); return(JsonValidationError()); } }
/// <summary> /// Read game information /// </summary> /// <param name="reader">XmlReader to use to parse the header</param> /// <param name="filename">Name of the file to be parsed</param> /// <param name="indexId">Index ID for the DAT</param> private void ReadGame(XmlReader reader, string filename, int indexId) { // Prepare all internal variables string releaseNumber = string.Empty, duplicateid; long? size = null; List <Rom> datItems = new List <Rom>(); Machine machine = new Machine(); // If there's no subtree to the configuration, skip it if (reader == null) { return; } // Otherwise, add what is possible reader.MoveToContent(); // Otherwise, read what we can from the header while (!reader.EOF) { // We only want elements if (reader.NodeType != XmlNodeType.Element) { reader.Read(); continue; } // Get all games items switch (reader.Name.ToLowerInvariant()) { case "imagenumber": // TODO: Read this into a field reader.ReadElementContentAsString(); break; case "releasenumber": // TODO: Read this into a field releaseNumber = reader.ReadElementContentAsString(); break; case "title": machine.Name = reader.ReadElementContentAsString(); break; case "savetype": // TODO: Read this into a field reader.ReadElementContentAsString(); break; case "romsize": size = Sanitizer.CleanLong(reader.ReadElementContentAsString()); break; case "publisher": machine.Publisher = reader.ReadElementContentAsString(); break; case "location": // TODO: Read this into a field reader.ReadElementContentAsString(); break; case "sourcerom": // TODO: Read this into a field reader.ReadElementContentAsString(); break; case "language": // TODO: Read this into a field reader.ReadElementContentAsString(); break; case "files": datItems = ReadFiles(reader.ReadSubtree(), releaseNumber, machine.Name, filename, indexId); // Skip the files node now that we've processed it reader.Skip(); break; case "im1crc": // TODO: Read this into a field reader.ReadElementContentAsString(); break; case "im2crc": // TODO: Read this into a field reader.ReadElementContentAsString(); break; case "comment": machine.Comment = reader.ReadElementContentAsString(); break; case "duplicateid": duplicateid = reader.ReadElementContentAsString(); if (duplicateid != "0") { machine.CloneOf = duplicateid; } break; default: reader.Read(); break; } } // Add information accordingly for each rom for (int i = 0; i < datItems.Count; i++) { datItems[i].Size = size; datItems[i].CopyMachineInformation(machine); // Now process and add the rom ParseAddHelper(datItems[i]); } }
public ActionResult changeDefaultAddress(AddressModel customeraddress) { var result = _customerRepository.changeDefaultAddress(Sanitizer.GetSafeHtmlFragment(customeraddress.CustomerId), Sanitizer.GetSafeHtmlFragment(customeraddress.Id)); return(JsonSuccess(result.Result, JsonRequestBehavior.AllowGet)); }
protected string HtmlEncode(String value) { return(Sanitizer.Encode(value)); }
private void OnErrorDataReceived(object sender, DataReceivedEventArgs e) { // TODO: per language stdout/err parser? if (e.Data != null) { string msg = e.Data; if (msg.IndexOf("warn", StringComparison.OrdinalIgnoreCase) > -1) { if (LanguageWorkerChannelUtilities.IsLanguageWorkerConsoleLog(msg)) { msg = LanguageWorkerChannelUtilities.RemoveLogPrefix(msg); _workerChannelLogger?.LogWarning(msg); } else { _consoleLogSource?.Log(msg); } } else if ((msg.IndexOf("error", StringComparison.OrdinalIgnoreCase) > -1) || (msg.IndexOf("fail", StringComparison.OrdinalIgnoreCase) > -1) || (msg.IndexOf("severe", StringComparison.OrdinalIgnoreCase) > -1)) { if (LanguageWorkerChannelUtilities.IsLanguageWorkerConsoleLog(msg)) { msg = LanguageWorkerChannelUtilities.RemoveLogPrefix(msg); _workerChannelLogger?.LogError(msg); } else { _consoleLogSource?.Log(msg); } _processStdErrDataQueue = LanguageWorkerChannelUtilities.AddStdErrMessage(_processStdErrDataQueue, Sanitizer.Sanitize(msg)); } else { if (LanguageWorkerChannelUtilities.IsLanguageWorkerConsoleLog(msg)) { msg = LanguageWorkerChannelUtilities.RemoveLogPrefix(msg); _workerChannelLogger?.LogInformation(msg); } else { _consoleLogSource?.Log(msg); } } } }
public static string SanitizeFragment(string htmlText) { return(Sanitizer.GetSafeHtmlFragment(htmlText)); }
public static string SanitizeHtml(string htmlText) { return(Sanitizer.GetSafeHtml(htmlText)); }
/// <summary> /// Read game/machine information /// </summary> /// <param name="reader">XmlReader to use to parse the machine</param> /// <param name="dirs">List of dirs to prepend to the game name</param> /// <param name="filename">Name of the file to be parsed</param> /// <param name="indexId">Index ID for the DAT</param> /// <param name="keep">True if full pathnames are to be kept, false otherwise (default)</param> private void ReadMachine( XmlReader reader, List <string> dirs, // Standard Dat parsing string filename, int indexId, // Miscellaneous bool keep) { // If we have an empty machine, skip it if (reader == null) { return; } // Otherwise, add what is possible reader.MoveToContent(); string key = string.Empty; string temptype = reader.Name; bool containsItems = false; // Create a new machine MachineType machineType = 0x0; if (reader.GetAttribute("isbios").AsYesNo() == true) { machineType |= MachineType.Bios; } if (reader.GetAttribute("isdevice").AsYesNo() == true) // Listxml-specific, used by older DATs { machineType |= MachineType.Device; } if (reader.GetAttribute("ismechanical").AsYesNo() == true) // Listxml-specific, used by older DATs { machineType |= MachineType.Mechanical; } string dirsString = (dirs != null && dirs.Count() > 0 ? string.Join("/", dirs) + "/" : string.Empty); Machine machine = new Machine { Name = dirsString + reader.GetAttribute("name"), Description = dirsString + reader.GetAttribute("name"), SourceFile = reader.GetAttribute("sourcefile"), Board = reader.GetAttribute("board"), RebuildTo = reader.GetAttribute("rebuildto"), Runnable = reader.GetAttribute("runnable").AsRunnable(), // Used by older DATs CloneOf = reader.GetAttribute("cloneof"), RomOf = reader.GetAttribute("romof"), SampleOf = reader.GetAttribute("sampleof"), MachineType = (machineType == 0x0 ? MachineType.NULL : machineType), }; if (Header.Type == "SuperDAT" && !keep) { string tempout = Regex.Match(machine.Name, @".*?\\(.*)").Groups[1].Value; if (!string.IsNullOrWhiteSpace(tempout)) { machine.Name = tempout; } } while (!reader.EOF) { // We only want elements if (reader.NodeType != XmlNodeType.Element) { reader.Read(); continue; } // Get the roms from the machine switch (reader.Name) { case "comment": // There can be multiple comments by spec machine.Comment += reader.ReadElementContentAsString(); break; case "description": machine.Description = reader.ReadElementContentAsString(); break; case "year": machine.Year = reader.ReadElementContentAsString(); break; case "manufacturer": machine.Manufacturer = reader.ReadElementContentAsString(); break; case "publisher": // Not technically supported but used by some legacy DATs machine.Publisher = reader.ReadElementContentAsString(); break; case "category": // Not technically supported but used by some legacy DATs machine.Category = reader.ReadElementContentAsString(); break; case "trurip": // This is special metadata unique to EmuArc ReadTruRip(reader.ReadSubtree(), machine); // Skip the trurip node now that we've processed it reader.Skip(); break; case "archive": containsItems = true; DatItem archive = new Archive { Name = reader.GetAttribute("name"), Source = new Source { Index = indexId, Name = filename, }, }; archive.CopyMachineInformation(machine); // Now process and add the archive key = ParseAddHelper(archive); reader.Read(); break; case "biosset": containsItems = true; DatItem biosSet = new BiosSet { Name = reader.GetAttribute("name"), Description = reader.GetAttribute("description"), Default = reader.GetAttribute("default").AsYesNo(), Source = new Source { Index = indexId, Name = filename, }, }; biosSet.CopyMachineInformation(machine); // Now process and add the biosSet key = ParseAddHelper(biosSet); reader.Read(); break; case "disk": containsItems = true; DatItem disk = new Disk { Name = reader.GetAttribute("name"), MD5 = reader.GetAttribute("md5"), SHA1 = reader.GetAttribute("sha1"), MergeTag = reader.GetAttribute("merge"), ItemStatus = reader.GetAttribute("status").AsItemStatus(), Source = new Source { Index = indexId, Name = filename, }, }; disk.CopyMachineInformation(machine); // Now process and add the disk key = ParseAddHelper(disk); reader.Read(); break; case "media": containsItems = true; DatItem media = new Media { Name = reader.GetAttribute("name"), MD5 = reader.GetAttribute("md5"), SHA1 = reader.GetAttribute("sha1"), SHA256 = reader.GetAttribute("sha256"), SpamSum = reader.GetAttribute("spamsum"), Source = new Source { Index = indexId, Name = filename, }, }; media.CopyMachineInformation(machine); // Now process and add the media key = ParseAddHelper(media); reader.Read(); break; case "release": containsItems = true; DatItem release = new Release { Name = reader.GetAttribute("name"), Region = reader.GetAttribute("region"), Language = reader.GetAttribute("language"), Date = reader.GetAttribute("date"), Default = reader.GetAttribute("default").AsYesNo(), }; release.CopyMachineInformation(machine); // Now process and add the release key = ParseAddHelper(release); reader.Read(); break; case "rom": containsItems = true; DatItem rom = new Rom { Name = reader.GetAttribute("name"), Size = Sanitizer.CleanLong(reader.GetAttribute("size")), CRC = reader.GetAttribute("crc"), MD5 = reader.GetAttribute("md5"), #if NET_FRAMEWORK RIPEMD160 = reader.GetAttribute("ripemd160"), #endif SHA1 = reader.GetAttribute("sha1"), SHA256 = reader.GetAttribute("sha256"), SHA384 = reader.GetAttribute("sha384"), SHA512 = reader.GetAttribute("sha512"), SpamSum = reader.GetAttribute("spamsum"), MergeTag = reader.GetAttribute("merge"), ItemStatus = reader.GetAttribute("status").AsItemStatus(), Date = Sanitizer.CleanDate(reader.GetAttribute("date")), Inverted = reader.GetAttribute("inverted").AsYesNo(), Source = new Source { Index = indexId, Name = filename, }, }; rom.CopyMachineInformation(machine); // Now process and add the rom key = ParseAddHelper(rom); reader.Read(); break; case "sample": containsItems = true; DatItem sample = new Sample { Name = reader.GetAttribute("name"), Source = new Source { Index = indexId, Name = filename, }, }; sample.CopyMachineInformation(machine); // Now process and add the sample key = ParseAddHelper(sample); reader.Read(); break; default: reader.Read(); break; } } // If no items were found for this machine, add a Blank placeholder if (!containsItems) { Blank blank = new Blank() { Source = new Source { Index = indexId, Name = filename, }, }; blank.CopyMachineInformation(machine); // Now process and add the rom ParseAddHelper(blank); } }