/// <summary> /// Constructor /// </summary> /// <param name="file">File adaptor</param> /// <param name="folder">Folder</param> /// <param name="name">File Name including extension</param> public FileResource(IFile file, string folder, string name) { File = Code.ExpectsArgument(file, nameof(file), TaggingUtilities.ReserveTag(0x238208d2 /* tag_9669s */)); Folder = Code.ExpectsNotNullOrWhiteSpaceArgument(folder, nameof(folder), TaggingUtilities.ReserveTag(0x238208d3 /* tag_9669t */)); Name = Code.ExpectsNotNullOrWhiteSpaceArgument(name, nameof(name), TaggingUtilities.ReserveTag(0x238208d4 /* tag_9669u */)); bool locationSet = false; try { if (!HasInvalidPathChars(Folder) && !HasInvalidPathChars(Name)) { Location = Path.Combine(Folder, Name); locationSet = true; } else { ULSLogging.LogTraceTag(0x238208d5 /* tag_9669v */, Categories.ConfigurationDataSet, Levels.Error, "Failed to combine FileResource.Location for folder: '{0}', name: '{1}'", Folder, Name); } } catch (ArgumentException exception) { ULSLogging.ReportExceptionTag(0x238208d6 /* tag_9669w */, Categories.ConfigurationDataSet, exception, "Exception constructing FileResource for folder: '{0}', name: '{1}'", Folder, Name); } if (!locationSet) { Location = Name; } }
/// <summary> /// Constructor /// </summary> /// <param name="assembly">assembly containing embedded resource</param> /// <param name="resourceName">resource name in assembly</param> public EmbeddedResource(Assembly assembly, string resourceName) { Assembly = Code.ExpectsArgument(assembly, nameof(assembly), TaggingUtilities.ReserveTag(0x238208c0 /* tag_9669a */)); Name = Code.ExpectsNotNullOrWhiteSpaceArgument(resourceName, nameof(resourceName), TaggingUtilities.ReserveTag(0x238208c1 /* tag_9669b */)); ResourceContent = new Lazy <Tuple <ResourceReadStatus, byte[]> >(() => { ResourceReadStatus status = ResourceReadStatus.NotFound; byte[] content = null; try { string resourceContent = Assembly.LoadEmbeddedResourceAsString(Name); if (resourceContent != null) { content = Encoding.UTF8.GetBytes(resourceContent); status = ResourceReadStatus.Success; } } catch (Exception ex) { ULSLogging.ReportExceptionTag(0x238208c2 /* tag_9669c */, Categories.ConfigurationDataSet, ex, "Unable to read resource {resourceName}", resourceName); status = ResourceReadStatus.ReadFailed; } return(Tuple.Create(status, content)); }, LazyThreadSafetyMode.PublicationOnly); }
public void AddUlsLoggerAddapter_SubscribesToEvents() { Mock <ILogger> mockLogger = new Mock <ILogger>(); Mock <ILoggerFactory> mockFactory = new Mock <ILoggerFactory>(); mockFactory.Setup(f => f.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object); new HostBuilder() .ConfigureServices(collection => { collection .AddSingleton(mockFactory.Object) .AddUlsLoggerAddapter(); }) .Build() .Start(); uint eventId = 1; Category category = new Category("Test"); Level logLevel = Levels.Error; string logMessage = "TestLogMessage"; Exception exception = new Exception(); mockLogger.Invocations.Clear(); ULSLogging.LogTraceTag(eventId, category, logLevel, logMessage); Assert.AreEqual(1, mockLogger.Invocations.Count, "ULSLogging.LogTraceTag not calling ILogger"); mockLogger.Invocations.Clear(); ULSLogging.ReportExceptionTag(eventId, category, exception, logMessage); Assert.AreEqual(1, mockLogger.Invocations.Count, "ULSLogging.ReportExceptionTag not calling ILogger"); }
/// <summary> /// Executes the async call and logs errors to ULS. /// </summary> /// <param name="tagId">ULS tag. Should be auto generated by git tagger, no need to specify.</param> /// <param name="asyncFunc">Async delegate etc.</param> /// <param name="caller">Caller function name. No need to specify explicitly, will be set automatically on run time.</param> /// <returns>The a task of type T.</returns> public static async Task ExecuteAndLogAsync( uint tagId, Func <Task> asyncFunc, [CallerMemberName] string caller = null) { Code.ExpectsArgument(asyncFunc, nameof(asyncFunc), TaggingUtilities.ReserveTag(0x2381b1e0 /* tag_961h6 */)); try { await asyncFunc().ConfigureAwait(false); } catch (DocumentClientException exception) { ULSLogging.ReportExceptionTag( tagId, Categories.DocumentDb, exception, $"Operation: {caller} {exception.ToErrorMessage()}"); throw; } catch (Exception exception) { ULSLogging.ReportExceptionTag(tagId, Categories.DocumentDb, exception, $"Exception detected. Caller: {caller} Error: {exception.Message}."); throw; } }
/// <summary> /// Tries to parse a TimedScopeInstanceName instance from a string /// </summary> /// <param name="toParse">String to be parsed, cannot be null</param> /// <param name="parsed">This output parameter is set to a new TimedScopeInstanceName instance when succeeded, null otherwise</param> /// <param name="preferMetaData">If <c>true</c>, the second field is assumed to be MetaData value</param> /// <returns>Success status</returns> public static bool TryParse(string toParse, out TimedScopeInstanceName parsed, bool preferMetaData = false) { parsed = null; if (string.IsNullOrWhiteSpace(toParse)) { return(false); } try { // The scope instance names have the following form: scope.classification[.description][/subtype][/metadata] // We are going to extract the classification substring, the remaining string with the classification and // description substring removed should form an ordinary timed scope name so we will parse it by TimedScopeName.TryParse. // Split the string by the field separators ('/') first string[] parts = toParse.Split(new[] { FieldsSeparator }, StringSplitOptions.None); // The first part is further divided by classification separator. It should have two or three fields, the first is // a scope, the second is a classification string[] firstFieldsubParts = parts[0].Split(new[] { FailureClassificationSeparator }, StringSplitOptions.None); if (firstFieldsubParts.Length < 2 || firstFieldsubParts.Length > 3) { return(false); } string scope = firstFieldsubParts[0]; string classification = firstFieldsubParts[1]; // Try to parse the classification substring TimedScopeResult parsedClassification; if (!Enum.TryParse(classification, out parsedClassification)) { return(false); } // Reconstruct the scope name string without classification and try to parse it parts[0] = scope; string scopeName = string.Join(FieldsSeparator.ToString(CultureInfo.InvariantCulture), parts); TimedScopeName parsedScopeName; if (!TimedScopeName.TryParse(scopeName, out parsedScopeName, preferMetaData)) { return(false); } // Create a new instance parsed = new TimedScopeInstanceName(parsedScopeName, parsedClassification); return(true); } catch (Exception exception) { // The parsing shouldn't throw but we catch exceptions to be safe ULSLogging.ReportExceptionTag(0x23817706 /* tag_96x2g */, Categories.Common, exception, "An unexpected exception occured during TimedScopeInstanceName.TryParse. Returning false."); return(false); } }
/// <summary> /// Tries to parse a TimedScopeName instance from a string /// </summary> /// <param name="toParse">String to be parsed, cannot be null</param> /// <param name="parsed">This output parameter is set to a new TimedScopeName instance when succeeded, null otherwise</param> /// <param name="preferMetaData">If <c>true</c>, the second field is assumed to be MetaData value</param> /// <returns>Success status</returns> public static bool TryParse(string toParse, out TimedScopeName parsed, bool preferMetaData = false) { parsed = null; if (string.IsNullOrWhiteSpace(toParse)) { return(false); } try { // The scope name should have the following form: scope[/subtype][/metadata] // We just split the string, check the number of fields and assign correct fields string[] parts = toParse.Split(new[] { Separator }, StringSplitOptions.None); string scope = parts[0]; string subType = null; string metaData = null; if (string.IsNullOrWhiteSpace(scope)) { return(false); } if (parts.Length == 2) { if (preferMetaData) { metaData = parts[1]; } else { subType = parts[1]; } } else if (parts.Length == 3) { subType = parts[1]; metaData = parts[2]; } else if (parts.Length > 3) { return(false); } parsed = new TimedScopeName(scope, subType, metaData); return(true); } catch (Exception exception) { // The parsing shouldn't throw but we catch exceptions to be safe ULSLogging.ReportExceptionTag(0x23817704 /* tag_96x2e */, Categories.Common, exception, "An unexpected exception occured during TimedScopeName.TryParse. Returning false."); return(false); } }
// The following comment tells ULS auto-tagging to not tag below // ASSERTTAG_IGNORE_START /// <summary> /// Report an exception /// </summary> /// <param name="tagid">tag</param> /// <param name="category">category</param> /// <param name="exception">exception</param> /// <param name="addToLoadingErrors">add to dataset loading errors</param> /// <param name="message">message</param> /// <param name="parameters">message format parameters</param> public void ReportExceptionTag(uint tagid, Category category, Exception exception, bool addToLoadingErrors, string message, params object[] parameters) { ULSLogging.ReportExceptionTag(tagid, category, exception, message, parameters); if (addToLoadingErrors) { string fullError = string.Format(CultureInfo.InvariantCulture, "{0} Exception: {1}", message, exception); LogError(fullError, parameters); } }
/// <summary>Creates an untyped object containing the XML data. This object /// can be casted to the type passed in parameter "type" by the caller.</summary> /// <param name="stream">The memory stream from which to read.</param> /// <param name="compressionType">Compression type of the input stream </param> /// <param name="type">The object type to read.</param> /// <param name="schema">The schema to use.</param> /// <param name="schemaUri">The schema URI to use.</param> /// <param name="context">XmlParserContext to be used to read the stream</param> /// <param name="settings">XmlReaderSettings to be used to read the stream</param> /// <param name="serialiser">XmlSerialiser to be used to read the stream</param> /// <returns>The deserialised object.</returns> private static object Read(Stream stream, CompressionType compressionType, Type type, string schema, string schemaUri, XmlParserContext context, XmlReaderSettings settings, XmlSerializer serialiser) { try { if (compressionType == CompressionType.GZip) { using (GZipStream gzipStream = new GZipStream(stream, CompressionMode.Decompress)) { return(Read(gzipStream, CompressionType.NoCompression, type, schema, schemaUri, context, settings, serialiser)); } } if (context == null) { context = GetXmlParserContext(schemaUri); } if (settings == null) { settings = type.GetXmlReaderSettings(schema, schemaUri); } using (XmlReader reader = XmlReader.Create(stream, settings, context)) { if (serialiser == null) { serialiser = new XmlSerializer(type); } return(serialiser.Deserialize(reader)); } } catch (InvalidDataException exception) { ULSLogging.ReportExceptionTag(0x2382088b /* tag_9668l */, Categories.Common, exception, "XmlExtensions failed to read/decompress incorrect file stream."); return(null); } catch (InvalidOperationException exception) { ULSLogging.ReportExceptionTag(0x2382088c /* tag_9668m */, Categories.Common, exception, "XmlExtensions failed to parse file for given object's state."); return(null); } catch (Exception exception) { ULSLogging.ReportExceptionTag(0x2382088d /* tag_9668n */, Categories.Common, exception, "XmlExtensions failed to parse file."); return(null); } }
public void AddOmexCompatibilityServices_RegisterTypes() { Mock <ILogger> mockLogger = new Mock <ILogger>(); Mock <ILoggerFactory> mockFactory = new Mock <ILoggerFactory>(); mockFactory.Setup(f => f.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object); new HostBuilder() .ConfigureServices(collection => { collection .AddTimedScopes() .AddSingleton(mockFactory.Object) .AddOmexCompatibilityServices(); }) .Build() .Start(); EventId eventId = new EventId(1); Category category = new Category("Test"); LogLevel logLevel = LogLevel.Error; string logMessage = "TestLogMessage"; Exception exception = new Exception(); mockLogger.Invocations.Clear(); ULSLogging.LogTraceTag(eventId, category, logLevel, logMessage); Assert.AreEqual(1, mockLogger.Invocations.Count, "ULSLogging.LogTraceTag not calling ILogger"); mockLogger.Invocations.Clear(); ULSLogging.ReportExceptionTag(eventId, category, exception, logMessage); Assert.AreEqual(1, mockLogger.Invocations.Count, "ULSLogging.ReportExceptionTag not calling ILogger"); mockLogger.Invocations.Clear(); Code.Validate(false, logMessage, eventId); Assert.AreEqual(1, mockLogger.Invocations.Count, "Code.Validate not calling ILogger"); using (TimedScope startedTimedScope = new TimedScopeDefinition("TestStartedTimedScope").Create(TimedScopeResult.SystemError)) { AssertResult(ActivityResultStrings.SystemError); } using (TimedScope notStartedTimedScope = new TimedScopeDefinition("TestNotStartedTimedScope").Create(TimedScopeResult.ExpectedError, false)) { notStartedTimedScope.Start(); AssertResult(ActivityResultStrings.ExpectedError); } }
/// <summary> /// Load the test groups DataSet /// </summary> /// <param name="file">file to load the groups DataSet from</param> private void Load(byte[] file) { try { Configuration.TestGroups testGroups; using (MemoryStream stream = new MemoryStream(file, false)) { testGroups = stream.Read <Configuration.TestGroups>(GroupsSchema, null); } LoadGroupsData(testGroups, out m_userGroups, out m_groupUsers); } catch (InvalidOperationException exception) { ULSLogging.ReportExceptionTag(0x23821094 /* tag_967cu */, Categories.TestGroupsDataSet, exception, true, "Failed to load test groups DataSet due to exception."); } }
/// <summary> /// Loads DataSet /// </summary> /// <param name="arguments">The arguments for the update event.</param> /// <returns>Loaded DataSet</returns> private TDataSet LoadDataSet(ResourceUpdatedEventArgs arguments) { ULSLogging.LogTraceTag(0x2382100c /* tag_967am */, Categories.ConfigurationDataSet, Levels.Verbose, "Loading data set for '{0}'.", typeof(TDataSet).Name); TDataSet dataSet = m_dataSetDefault ?? new TDataSet(); try { dataSet.Load(arguments.Details); } catch (Exception exception) { ULSLogging.ReportExceptionTag(0x2382100d /* tag_967an */, Categories.ConfigurationDataSet, exception, "Exception encountered while loading '{0}'", typeof(TDataSet).Name); } return(dataSet); }
/// <summary> /// Retrieves resource contents /// </summary> /// <param name="content">Resource content</param> /// <returns>Resource read status</returns> public ResourceReadStatus GetContent(out byte[] content) { content = null; if (!File.Exists(Location)) { ULSLogging.LogTraceTag(0x238208d7 /* tag_9669x */, Categories.ConfigurationDataSet, Levels.Verbose, "FileResource does not exist: '{0}'", Location); return(ResourceReadStatus.NotFound); } try { content = File.ReadAllBytes(Location); return(ResourceReadStatus.Success); } catch (Exception exception) { ULSLogging.ReportExceptionTag(0x238208d8 /* tag_9669y */, Categories.ConfigurationDataSet, exception, "Exception reading file '{0}'", Location); content = null; return(ResourceReadStatus.ReadFailed); } }