public async Task CreateCategoryAsync(Category category) { category.Name = category.Name.Trim(); category.NameNormalized = Normalizer.Normalize(category.Name); category.Title = category.Title; ValidateCategory(category); category.SubTitle = category.SubTitle?.SetNullIfEmptyTrim(); category.Icon = category.Icon?.SetNullIfEmptyTrim(); category.SettingsJson = category.SettingsJson?.MakeJsonText(); category.LayoutName = category.LayoutName?.SetNullIfEmptyTrim(); category.MaterialTypeTitle = category.MaterialTypeTitle?.SetNullIfEmptyTrim(); category.Header = sanitizer.Sanitize(category.Header?.SetNullIfEmptyTrim()); var parent = await db.Categories.FirstOrDefaultAsync(x => x.Id == category.ParentId); if (parent == null) { throw new SunParentEntityNotFoundException(nameof(Category), category.ParentId); } using (db.BeginTransaction()) { int id = await db.InsertWithInt32IdentityAsync(category); await db.Categories.Where(x => x.Id == id).Set(x => x.SortNumber, id).UpdateAsync(); category.SortNumber = category.Id = id; db.CommitTransaction(); } }
public virtual async Task CreateAsync( Material material, string tags, bool isDescriptionEditable = false) { material.Text = sanitizer.Sanitize(material.Text); var(preview, description) = MaterialExtensions.MakePreviewAndDescription(material.Text, materialsOptions.DescriptionLength, materialsOptions.PreviewLength); material.Preview = preview; if (isDescriptionEditable) { material.Description = SimpleHtmlToText.ClearTags(sanitizer.Sanitize(material.Description)); } else { material.Description = description; } using (db.BeginTransaction()) { material.Id = await db.InsertWithInt32IdentityAsync(material); await db.Materials.Where(x => x.Id == material.Id).Set(x => x.SortNumber, x => material.Id) .UpdateAsync(); await tagsManager.MaterialCreateAndSetTagsAsync(material, tags); db.CommitTransaction(); } }
public virtual async Task CreateAsync(Material material, string tags, bool isDescriptionEditable = false) { material.Text = sanitizer.Sanitize(material.Text); var(preview, description) = MaterialExtensions.MakePreviewAndDescription(material.Text, materialsOptions.DescriptionLength, materialsOptions.PreviewLength); material.Preview = preview; if (isDescriptionEditable) { material.Description = SimpleHtmlToText.ClearTags(sanitizer.Sanitize(material.Description)); } else { material.Description = description; } /*material.MakePreviewAndDescription(materialsOptions.DescriptionLength, * materialsOptions.PreviewLength);*/ material.Id = await db.InsertWithInt32IdentityAsync(material); await tagsManager.MaterialCreateAndSetTagsAsync(material, tags); }
public virtual Task SetMyProfileInformationAsync(int userId, string html) { var htmlSanitized = sanitizer.Sanitize(html); return(db.Users.Where(x => x.Id == userId) .Set(x => x.Information, htmlSanitized).UpdateAsync()); }
public void InferredEvaluatorAddedOnlyOnce() { WorkDefine.Workflow testWF = new WorkDefine.Workflow("test") { Activities = new List <WorkDefine.Activity>() { new WorkDefine.Activity() { //Action = "action.test", Id = "activity.test", Reactions = new List <WorkDefine.Reaction>() { new WorkDefine.Reaction() { Logic = "evaluator.test", Work = "action.reaction" }, new WorkDefine.Reaction() { Logic = "evaluator.test", Work = "action.reaction" } } } } }; StepTracer <LintTrace> tracer = new StepTracer <LintTrace>(); tracer.TraceFirst(new LintTrace(LintStatusOptions.Sanitizing, "Testing Sanitizer")); Sanitizer toTest = new Sanitizer(tracer, this.defaultConfig); WorkDefine.Workflow sanitized = toTest.Sanitize(testWF); Assert.Equal(1, sanitized.Evaluators.Count(g => g.Id == "evaluator.test")); }
public static string GetValueByOutputMethod(object contentItem, string fieldName) { var content = contentItem as Content; if (content == null || string.IsNullOrEmpty(fieldName) || !content.Fields.ContainsKey(fieldName)) { return(string.Empty); } var fieldValue = content[fieldName] as string; if (string.IsNullOrEmpty(fieldValue)) { return(string.Empty); } switch (content.Fields[fieldName].FieldSetting.OutputMethod) { case OutputMethod.Default: case OutputMethod.Text: return(UITools.GetSafeText(fieldValue)); case OutputMethod.Html: return(Sanitizer.Sanitize(fieldValue)); default: return(fieldValue); } }
public string GetOutputData(OutputMethod method) { var data = GetData(); if (data == null) { return(null); } switch (method) { case OutputMethod.Raw: return(data.ToString()); case OutputMethod.Text: return(HttpUtility.HtmlEncode(data)); case OutputMethod.Html: return(Sanitizer.Sanitize(data.ToString())); case OutputMethod.Default: return(GetOutputData(this.OutputMethod)); default: throw new SnNotSupportedException("Unknown OutputMethod: " + this.Field.FieldSetting.OutputMethod); } }
public void LogEvent(string eventName, string functionName = null, string data = null) { ArgumentNullException.ThrowIfNull(eventName); eventName = Sanitizer.Sanitize(eventName); string key = GetAggregateKey(eventName, functionName); QueuedEvents.AddOrUpdate(key, (name) => { // create the default event that will be added // if an event isn't already queued for this key return(new SystemMetricEvent { FunctionName = functionName, EventName = eventName.ToLowerInvariant(), Count = 1, Data = data }); }, (name, evtToUpdate) => { // update the existing event evtToUpdate.Count++; return(evtToUpdate); }); }
public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { // propagate special exceptions through the EventManager var stateProps = state as IEnumerable <KeyValuePair <string, object> > ?? new Dictionary <string, object>(); string source = _categoryName ?? Utility.GetStateValueOrDefault <string>(stateProps, ScriptConstants.LogPropertySourceKey); if (exception is FunctionIndexingException && _eventManager != null) { _eventManager.Publish(new FunctionIndexingEvent("FunctionIndexingException", source, exception)); } // User logs are not logged to system logs. if (!IsEnabled(logLevel) || IsUserLog(state)) { return; } string formattedMessage = formatter?.Invoke(state, exception); // If we don't have a message, there's nothing to log. if (string.IsNullOrEmpty(formattedMessage)) { return; } IDictionary <string, object> scopeProps = _scopeProvider.GetScopeDictionary(); // Apply standard event properties // Note: we must be sure to default any null values to empty string // otherwise the ETW event will fail to be persisted (silently) string subscriptionId = _environment.GetSubscriptionId() ?? string.Empty; string appName = _environment.GetAzureWebsiteUniqueSlotName() ?? string.Empty; string summary = Sanitizer.Sanitize(formattedMessage) ?? string.Empty; string innerExceptionType = string.Empty; string innerExceptionMessage = string.Empty; string functionName = _functionName ?? Utility.ResolveFunctionName(stateProps, scopeProps) ?? string.Empty; string eventName = !string.IsNullOrEmpty(eventId.Name) ? eventId.Name : Utility.GetStateValueOrDefault <string>(stateProps, ScriptConstants.LogPropertyEventNameKey) ?? string.Empty; string functionInvocationId = Utility.GetValueFromScope(scopeProps, ScriptConstants.LogPropertyFunctionInvocationIdKey) ?? string.Empty; string hostInstanceId = _hostInstanceId; string activityId = Utility.GetStateValueOrDefault <string>(stateProps, ScriptConstants.LogPropertyActivityIdKey) ?? string.Empty; string runtimeSiteName = _environment.GetRuntimeSiteName() ?? string.Empty; string slotName = _environment.GetSlotName() ?? string.Empty; // Populate details from the exception. string details = string.Empty; if (exception != null) { if (string.IsNullOrEmpty(functionName) && exception is FunctionInvocationException fex) { functionName = string.IsNullOrEmpty(fex.MethodName) ? string.Empty : fex.MethodName.Replace("Host.Functions.", string.Empty); } (innerExceptionType, innerExceptionMessage, details) = exception.GetExceptionDetails(); innerExceptionMessage = innerExceptionMessage ?? string.Empty; } _eventGenerator.LogFunctionTraceEvent(logLevel, subscriptionId, appName, functionName, eventName, source, details, summary, innerExceptionType, innerExceptionMessage, functionInvocationId, hostInstanceId, activityId, runtimeSiteName, slotName); }
private void GetExceptionDetails(Exception exception, out string exceptionType, out string exceptionMessage) { if (exception == null) { throw new ArgumentNullException(nameof(exception)); } exceptionType = exception.GetType().ToString(); exceptionMessage = Sanitizer.Sanitize(exception.Message) ?? string.Empty; }
public virtual Task SendPrivateMessageAsync(User from, User to, string text) { var header = $"<div>Вам написал: <a href='{globalOptions.SiteUrl.AppendPathSegment("user/" + from.Link)}'>{from.UserName}</a></div><br/>"; text = sanitizer.Sanitize(header + text); string subject = $"Сообщение от {to.UserName} с сайта {globalOptions.SiteName}"; return(EmailSenderService.SendEmailAsync(to.Email, subject, text)); }
private void SetDatePickerTitleAndDescription() { // do not do this twice if (_titleIsAlreadySet) { return; } _titleIsAlreadySet = true; var title = GetLabelForTitleControl() as Label; var desc = GetLabelForDescription() as Label; if (title != null) { title.Text = HttpUtility.HtmlEncode(Field.DisplayName); } if (desc != null) { desc.Text = Sanitizer.Sanitize(Field.Description); var dateTimeFormat = System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat; var shortDatePattern = dateTimeFormat.ShortDatePattern; var timePattern = dateTimeFormat.ShortTimePattern; var pattern = string.Empty; switch (Mode) { case DateTimeMode.None: case DateTimeMode.DateAndTime: var patternWithTime = HttpContext.GetGlobalResourceObject("Portal", "DateFieldDateTimeFormatDescription") as string ?? "{0} - {1}"; pattern = String.Format(patternWithTime, shortDatePattern, timePattern); break; case DateTimeMode.Date: var patternWithoutTime = HttpContext.GetGlobalResourceObject("Portal", "DateFieldDateFormatDescription") as string ?? "{0}"; pattern = String.Format(patternWithoutTime, shortDatePattern); break; default: break; } var text = desc.Text.TrimEnd(); if (!string.IsNullOrEmpty(text)) { text = string.Concat(text, "<br />"); } desc.Text = string.Concat(text, pattern); } }
public IEvaluator Parse(string choice) { try { return(Lexer.Lex(Sanitizer.Sanitize(choice))); } catch (Exception e) { var log = new LogEvaluator("log", Messages); new EvaluatorParameterizer().SetParameters(log, "error", e.Message); return(log); } }
public virtual Task SendPrivateMessageAsync(User from, User to, string text) { return(emailSenderService.SendEmailByTemplateAsync( to.Email, "private-message.html", new Dictionary <string, string> { { "[siteName]", globalOptions.SiteName }, { "[url]", globalOptions.SiteUrl.AppendPathSegment("user/" + from.Link) }, { "[userName]", from.UserName }, { "[message]", sanitizer.Sanitize(text) } } )); }
public async Task CreateCategoryAsync(Category category) { if (category == null) { throw new ArgumentNullException("Category can not be null"); } category.Header = sanitizer.Sanitize(category.Header); category.NameNormalized = Normalizer.Normalize(category.Name); var parent = await db.Categories.FirstOrDefaultAsync(x => x.Id == category.ParentId); if (parent == null) { throw new ParentCategoryNotFoundByIdException(category.ParentId); } using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { int id = await db.InsertWithInt32IdentityAsync(category); await db.Categories.Where(x => x.Id == id).Set(x => x.SortNumber, id).UpdateAsync(); } }
public virtual async Task CreateAsync(Material material, string tags, CategoryCached category) { IHtmlDocument doc = new HtmlParser().Parse(material.Text); material.Text = sanitizer.Sanitize(doc); var generator = categoriesCache.GetMaterialsPreviewGenerator(category.MaterialsPreviewGeneratorName); material.Preview = generator(doc, materialsOptions.PreviewLength); switch (category.MaterialsSubTitleInputType) { case MaterialsSubTitleInputType.Manual: material.SubTitle = SimpleHtmlToText.ClearTags(sanitizer.Sanitize(material.SubTitle)); break; case MaterialsSubTitleInputType.Auto: material.SubTitle = MakeSubTitle.Do(doc, materialsOptions.SubTitleLength); break; } using (db.BeginTransaction()) { material.Id = await db.InsertWithInt32IdentityAsync(material); await db.Materials.Where(x => x.Id == material.Id).Set(x => x.SortNumber, x => material.Id) .UpdateAsync(); await tagsManager.MaterialCreateAndSetTagsAsync(material, tags); db.CommitTransaction(); } }
public override void Trace(TraceEvent traceEvent) { // Apply standard event properties // Note: we must be sure to default any null values to empty string // otherwise the ETW event will fail to be persisted (silently) string subscriptionId = _subscriptionId ?? string.Empty; string appName = _appName ?? string.Empty; string source = traceEvent.Source ?? string.Empty; string summary = Sanitizer.Sanitize(traceEvent.Message) ?? string.Empty; // Apply any additional extended event info from the Properties bag string functionName = string.Empty; string eventName = string.Empty; string details = string.Empty; if (traceEvent.Properties != null) { object value; if (traceEvent.Properties.TryGetValue(ScriptConstants.TracePropertyIsUserTraceKey, out value) && value is bool && (bool)value == true) { // we don't write user traces to system logs return; } if (traceEvent.Properties.TryGetValue(ScriptConstants.TracePropertyFunctionNameKey, out value) && value != null) { functionName = value.ToString(); } if (traceEvent.Properties.TryGetValue(ScriptConstants.TracePropertyEventNameKey, out value) && value != null) { eventName = value.ToString(); } if (traceEvent.Properties.TryGetValue(ScriptConstants.TracePropertyEventDetailsKey, out value) && value != null) { details = Sanitizer.Sanitize(value.ToString()); } } if (string.IsNullOrEmpty(details) && traceEvent.Exception != null) { details = Sanitizer.Sanitize(traceEvent.Exception.ToFormattedString()); } _eventGenerator.LogFunctionTraceEvent(traceEvent.Level, subscriptionId, appName, functionName, eventName, source, details, summary); }
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 (IsLanguageWorkerConsoleLog(msg)) { msg = RemoveLogPrefix(msg); _workerChannelLogger?.LogWarning(msg); } else { _userLogsConsoleLogger?.LogInformation(msg); } } else if ((msg.IndexOf("error", StringComparison.OrdinalIgnoreCase) > -1) || (msg.IndexOf("fail", StringComparison.OrdinalIgnoreCase) > -1) || (msg.IndexOf("severe", StringComparison.OrdinalIgnoreCase) > -1)) { if (IsLanguageWorkerConsoleLog(msg)) { msg = RemoveLogPrefix(msg); _workerChannelLogger?.LogError(msg); } else { _userLogsConsoleLogger?.LogInformation(msg); } AddStdErrMessage(Sanitizer.Sanitize(msg)); } else { if (IsLanguageWorkerConsoleLog(msg)) { msg = RemoveLogPrefix(msg); _workerChannelLogger?.LogInformation(msg); } else { _userLogsConsoleLogger?.LogInformation(msg); } } } }
private static string GenerateGlimpseOutput(HttpContextBase context) { IDictionary <string, object> data; if (!context.TryGetData(out data)) { return("Error: No Glimpse Data Found"); } string json = CreateJsonPayload(data, context); Logger.Info("Glimpse JSON payload created for requestId " + context.GetGlimpseRequestId() + " (" + context.Request.Path + ")"); json = Sanitizer.Sanitize(json); return(json); }
public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { if (!IsEnabled(logLevel)) { return; } string formattedMessage = formatter?.Invoke(state, exception); // Make sure we have something to log if (string.IsNullOrEmpty(formattedMessage) && exception == null) { return; } (string exceptionType, string exceptionMessage, string exceptionDetails) = exception.GetExceptionDetails(); var scopeProps = _scopeProvider.GetScopeDictionary(); var stateProps = state as IEnumerable <KeyValuePair <string, object> > ?? new Dictionary <string, object>(); // 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", Sanitizer.Sanitize(formattedMessage)); WritePropertyIfNotNull(writer, "category", _category); WritePropertyIfNotNull(writer, "hostVersion", _hostVersion); WritePropertyIfNotNull(writer, "functionInvocationId", Utility.GetValueFromScope(scopeProps, ScopeKeys.FunctionInvocationId)); WritePropertyIfNotNull(writer, "functionName", Utility.ResolveFunctionName(stateProps, scopeProps)); 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()); }
internal async Task <HttpScriptInvocationResult> GetHttpScriptInvocationResult(HttpResponseMessage httpResponseMessage) { try { return(await httpResponseMessage.Content.ReadAsAsync <HttpScriptInvocationResult>()); } catch (Exception ex) { var exMessage = $"Invalid HttpResponseMessage:\n{httpResponseMessage}"; string httpContent = await GetHttpContentAsString(httpResponseMessage.Content); if (!string.IsNullOrEmpty(httpContent)) { exMessage = $"{exMessage}\n {Sanitizer.Sanitize(httpContent)}"; } throw new InvalidOperationException(exMessage, ex); } }
public void InferredNegatedEquationAddedOnlyOnce() { WorkDefine.Workflow testWF = new WorkDefine.Workflow("test") { Equations = new List <LogicDefine.Equation>() { new LogicDefine.Equation() { Condition = Mchnry.Flow.Logic.Operand.And, First = "evaluator.first", Id = "equation.testeq" } }, Activities = new List <WorkDefine.Activity>() { new WorkDefine.Activity() { //Action = "action.test", Id = "activity.test", Reactions = new List <WorkDefine.Reaction>() { new WorkDefine.Reaction() { Logic = "evaluator.test", Work = "action.reaction" }, new WorkDefine.Reaction() { Logic = "!equation.testeq", Work = "action.badreaction" }, new WorkDefine.Reaction() { Logic = "!equation.testeq", Work = "action.anotherbadreaction" } } } } }; StepTracer <LintTrace> tracer = new StepTracer <LintTrace>(); tracer.TraceFirst(new LintTrace(LintStatusOptions.Sanitizing, "Testing Sanitizer")); Sanitizer toTest = new Sanitizer(tracer, this.defaultConfig); WorkDefine.Workflow sanitized = toTest.Sanitize(testWF); Assert.Equal(1, sanitized.Equations.Count(g => g.Id == "equation.NOT.testeq")); }
/// <summary> /// Gets a the specified property belonging to the Content of the View in a safe way. /// </summary> /// <param name="name">The property name. Can be hierarchical.</param> /// <returns>String value of the property specified</returns> internal static string GetValue(string name, SNC.Content parentContent, OutputMethod outputMethod, bool storedData = false, CultureInfo cultureInfo = null) { switch (outputMethod) { case OutputMethod.Default: throw new NotSupportedException("OutputMethod cannot be Default"); case OutputMethod.Raw: return(GetValue(name, parentContent, storedData, cultureInfo)); case OutputMethod.Text: return(System.Web.HttpUtility.HtmlEncode(GetValue(name, parentContent, storedData, cultureInfo))); case OutputMethod.Html: return(Sanitizer.Sanitize(GetValue(name, parentContent, storedData, cultureInfo))); default: throw new NotImplementedException("Unknown OutputMethod: " + outputMethod); } }
public void Initialize(ITelemetry telemetry) { if (telemetry == null) { return; } if (telemetry is ISupportProperties propertyTelemetry) { foreach (KeyValuePair <string, string> property in propertyTelemetry.Properties) { propertyTelemetry.Properties[property.Key] = Sanitizer.Sanitize(property.Value); } } if (telemetry is TraceTelemetry traceTelemetry) { traceTelemetry.Message = Sanitizer.Sanitize(traceTelemetry.Message); } }
public static (string exceptionType, string exceptionMessage, string exceptionDetails) GetExceptionDetails(this Exception exception) { if (exception == null) { return(null, null, null); } // Find the inner-most exception Exception innerException = exception; while (innerException.InnerException != null) { innerException = innerException.InnerException; } string exceptionType = innerException.GetType().ToString(); string exceptionMessage = Sanitizer.Sanitize(innerException.Message); string exceptionDetails = Sanitizer.Sanitize(exception.ToFormattedString()); return(exceptionType, exceptionMessage, exceptionDetails); }
/// <summary> /// Formats an error message corresponding to the provided error code and account. /// </summary> /// <param name="error">The error code as returned by <see cref="TryParseAccount"/> method call.</param> /// <param name="connectionStringName">Friendly connection string name used to format error message</param> /// <returns>Formatted error message with details about reason of the failure and possible ways of mitigation</returns> public static string FormatParseAccountErrorMessage(StorageAccountParseResult error, string connectionStringName) { // Users may accidentally use their real connection strings here, so let's be safe before throwing. connectionStringName = Sanitizer.Sanitize(connectionStringName); switch (error) { case StorageAccountParseResult.MissingOrEmptyConnectionStringError: // We don't want to add 'AzureWebJobs' as a prefix unless it is one of our keys. string prefixedConnectionString = connectionStringName; if (connectionStringName == ConnectionStringNames.Dashboard || connectionStringName == ConnectionStringNames.Storage) { prefixedConnectionString = AmbientConnectionStringProvider.GetPrefixedConnectionStringName(connectionStringName); } return(String.Format(CultureInfo.CurrentCulture, "Microsoft Azure WebJobs SDK '{0}' connection string is missing or empty. " + "The Microsoft Azure Storage account connection string can be set in the following ways:" + Environment.NewLine + "1. Set the connection string named '{1}' in the connectionStrings section of the .config file in the following format " + "<add name=\"{1}\" connectionString=\"DefaultEndpointsProtocol=http|https;AccountName=NAME;AccountKey=KEY\" />, or" + Environment.NewLine + "2. Set the environment variable named '{1}', or" + Environment.NewLine + "3. Set corresponding property of JobHostConfiguration.", connectionStringName, prefixedConnectionString)); case StorageAccountParseResult.MalformedConnectionStringError: return(String.Format(CultureInfo.CurrentCulture, "Failed to validate Microsoft Azure WebJobs SDK {0} connection string. " + "The Microsoft Azure Storage account connection string is not formatted " + "correctly. Please visit https://go.microsoft.com/fwlink/?linkid=841340 for " + "details about configuring Microsoft Azure Storage connection strings.", connectionStringName)); } Debug.Assert(false, "Unsupported case of error message!"); return(String.Empty); }
public void WriteToCurrentLine(string message) { foreach (var character in message) { switch (character) { case '\b': _terminal.Backspace(); _formatter.Backspace(); break; case '\n': _client.Request(_sanitizer.Sanitize(_terminal.GetCurrentLine())); _terminal.WriteCurrentLine(TerminalStyle.Command); RewriteConsole(); break; default: _terminal.AppendToCurrentLine(character); break; } } }
public void Log_Sanitization() { string secretReplacement = "[Hidden Credential]"; string secretString = "{ \"AzureWebJobsStorage\": \"DefaultEndpointsProtocol=https;AccountName=testAccount1;AccountKey=mykey1;EndpointSuffix=core.windows.net\", \"AnotherKey\": \"AnotherValue\" }"; string sanitizedString = $"{{ \"AzureWebJobsStorage\": \"{secretReplacement}\", \"AnotherKey\": \"AnotherValue\" }}"; string secretException = "Invalid string: \"DefaultEndpointsProtocol=https;AccountName=testaccount;AccountKey=testkey;BlobEndpoint=https://testaccount.blob.core.windows.net/;QueueEndpoint=https://testaccount.queue.core.windows.net/;TableEndpoint=https://testaccount.table.core.windows.net/;FileEndpoint=https://testaccount.file.core.windows.net/;\""; string sanitizedDetails = $"System.InvalidOperationException : Invalid string: \"{secretReplacement}\""; string sanitizedExceptionMessage = $"Invalid string: \"{secretReplacement}\""; string eventName = string.Empty; string functionInvocationId = string.Empty; string activityId = string.Empty; Exception ex = new InvalidOperationException(Sanitizer.Sanitize(secretException)); _mockEventGenerator.Setup(p => p.LogFunctionTraceEvent(LogLevel.Error, _subscriptionId, _websiteName, _functionName, eventName, _category, sanitizedDetails, sanitizedString, ex.GetType().ToString(), sanitizedExceptionMessage, functionInvocationId, _hostInstanceId, activityId, _runtimeSiteName, _slotName, It.IsAny <DateTime>())); // it's the caller's responsibility to pre-sanitize any details in the log entries _logger.LogError(ex, Sanitizer.Sanitize(secretString)); _mockEventGenerator.VerifyAll(); }
protected void SetTitleAndDescription() { if (this.Field == null) { return; } var title = this.FindControlRecursive(TitleControlID) as Label; var desc = this.FindControlRecursive(DescriptionControlID) as Label; // title cannot contain HTML elements if (title != null) { title.Text = Sanitizer.Sanitize(Field.DisplayName); } // description may contain HTML (e.g. icons), we need to remove only the script parts if (desc != null) { desc.Text = Sanitizer.Sanitize(Field.Description); } }
public void RemovesNewlines() { var sanitizer = new Sanitizer(); Assert.AreEqual("hello world", sanitizer.Sanitize("hello\n world")); }