private void Audit(IInvocation invocation) { AuditAttribute audit = invocation.GetAudit(); if (audit != null) { AuditLogger.Add(Session.UserId ?? Guid.Empty, Session.Application, Session.IP, audit.Source, audit.Action.ToString(), invocation.Arguments); } }
/// <summary> /// Builds up a string containing each property and value in the class. The string displays the property name, property friendly name and property value. /// </summary> /// <typeparam name="T">Class Type</typeparam> /// <param name="instance">Instance of the class</param> /// <param name="delimiter">What delimiter do you want between each property? Defaults to comma; can pass others like Environment.NewLine, etc.</param> /// <param name="sortByPropertyName">If set to <c>SortByPropertyName.Yes</c> then output will be sorted by AuditAttribute.AuditSequence and then property name; otherwise no additional sorting is performed and properties; will be left in ordinal order.</param> /// <returns>A string containing each property name, friendly name and value, separated by the delimiter and optionally sorted by property name.</returns> public static String ClassToString <T>(T instance, String delimiter = GlobalConstants.DefaultDelimiter, SortByPropertyName sortByPropertyName = SortByPropertyName.Yes) { var sb = new StringBuilder(4096); var list = new List <SortablePropertyBasket>(); foreach (var propInfo in PclReflection.GetPropertiesInfo(instance)) { var auditAttributes = propInfo.GetCustomAttributes <AuditAttribute>(false); var auditAttributeList = new List <AuditAttribute>(auditAttributes); AuditAttribute auditAttribute = null; if (auditAttributeList.Count == 1) { auditAttribute = auditAttributeList[0]; } var auditSequence = 1; if (auditAttribute != null) { auditSequence = auditAttribute.AuditSequence; } if (propInfo.Name != "Item" && propInfo.Name != "ValidationErrors") { list.Add(propInfo.GetValue(instance, null) != null ? new SortablePropertyBasket(auditSequence, propInfo.Name, CamelCaseString.GetWords(propInfo.Name), propInfo.GetValue(instance, null).ToString()) : new SortablePropertyBasket(auditSequence, propInfo.Name, CamelCaseString.GetWords(propInfo.Name), Null)); } } if (list.Count > 0) { if (sortByPropertyName == SortByPropertyName.Yes) { list.Sort(); } foreach (var propertyBasket in list) { sb.Append(propertyBasket); sb.Append(delimiter); } if (sb.Length > delimiter.Length) { sb.Length -= delimiter.Length; } } else { sb.Append("Class has no properties"); } return(sb.ToString()); }
/// <summary> /// Builds up a string containing each property and value in the class decorated with the AuditAttribute. The string displays the property name, property friendly name and property value. /// </summary> /// <typeparam name="T">Class Type</typeparam> /// <param name="instance">Instance of the class</param> /// <param name="defaultValue">If no class properties are decorated with the <see cref="AuditAttribute"/> then a single entry will be added to the dictionary that is named 'DefaultValue' and will have the value of defaultValue.</param> /// <param name="delimiter">What delimiter do you want between each property? Defaults to comma; can pass others like Environment.NewLine, etc.</param> /// <param name="includeAllProperties">if set to <c>true</c> [include all attributes].</param> /// <returns>A string containing each property name, friendly name and value, separated by the delimiter and sorted by AuditAttribute.AuditSequence and then property name.</returns> public static String AuditToString <T>(T instance, String defaultValue, String delimiter = GlobalConstants.DefaultDelimiter, Boolean includeAllProperties = false) { var sb = new StringBuilder(2048); var list = new List <SortablePropertyBasket>(); var nonAttributedPropertyIndex = 0; foreach (var propInfo in PclReflection.GetPropertiesInfo(instance)) { var auditAttributes = propInfo.GetCustomAttributes <AuditAttribute>(false); var auditAttributeList = new List <AuditAttribute>(auditAttributes); AuditAttribute auditAttribute = null; if (auditAttributeList.Count == 1) { auditAttribute = auditAttributeList[0]; } if (auditAttribute != null) { list.Add(propInfo.GetValue(instance, null) != null ? new SortablePropertyBasket(auditAttribute.AuditSequence, propInfo.Name, CamelCaseString.GetWords(propInfo.Name), propInfo.GetValue(instance, null).ToString()) : new SortablePropertyBasket(auditAttribute.AuditSequence, propInfo.Name, CamelCaseString.GetWords(propInfo.Name), Null)); } else if (includeAllProperties && propInfo.Name != "Item") { nonAttributedPropertyIndex += 1; list.Add(propInfo.GetValue(instance, null) != null ? new SortablePropertyBasket(nonAttributedPropertyIndex, propInfo.Name, CamelCaseString.GetWords(propInfo.Name), propInfo.GetValue(instance, null).ToString()) : new SortablePropertyBasket(nonAttributedPropertyIndex, propInfo.Name, CamelCaseString.GetWords(propInfo.Name), Null)); } } if (list.Count > 0) { list.Sort(); foreach (SortablePropertyBasket propertyBasket in list) { sb.Append(propertyBasket); sb.Append(delimiter); } if (sb.Length > delimiter.Length) { sb.Length -= delimiter.Length; } } else { sb.Append(defaultValue); } return(sb.ToString()); }
/// <summary> /// Returns a String with each property and value in the class. The String displays the property name, property friendly name and property value. /// </summary> /// <typeparam name="T">Class Type</typeparam> /// <param name="obj">Instance of the class</param> /// <param name="delimiter">What delimiter do you want between each property. Defaults to comma. Could use vbcrlf, etc.</param> /// <param name="sortByPropertyName">Normally sorts the output by property name. To leave in ordinal order, set to False</param> public static String ClassToString <T>(T obj, String delimiter = GlobalConstants.STRING_DEFAULT_DELIMITER, SortByPropertyName sortByPropertyName = SortByPropertyName.Yes) { var sb = new StringBuilder(4096); var list = new List <SortablePropertyBasket>(); foreach (PropertyInfo prop in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { Object[] auditAttributes = prop.GetCustomAttributes(typeof(AuditAttribute), false); AuditAttribute auditAttribute = null; if (auditAttributes.Length == 1) { auditAttribute = auditAttributes[0] as AuditAttribute; } Int32 auditSequence = 1; if (auditAttribute != null) { auditSequence = auditAttribute.AuditSequence; } list.Add(prop.GetValue(obj, null) != null ? new SortablePropertyBasket(auditSequence, prop.Name, CamelCaseString.GetWords(prop.Name), prop.GetValue(obj, null).ToString()) : new SortablePropertyBasket(auditSequence, prop.Name, CamelCaseString.GetWords(prop.Name), _NULL)); } if (list.Count > 0) { if (sortByPropertyName == SortByPropertyName.Yes) { list.Sort(); } foreach (SortablePropertyBasket propertyBasket in list) { sb.Append(propertyBasket.ToString()); sb.Append(delimiter); } if (sb.Length > delimiter.Length) { sb.Length -= delimiter.Length; } } else { sb.Append(Resources.ClassMessageCreationHelper_ClassToString_Class_has_no_properties); } return(sb.ToString()); }
/// <summary> /// This function returns a String of each property decorated with the AuditAttribute. The String displays the property name, property friendly name and property value. This function is typically used when a developer need to make an audit log entry. It provides a very simple method to generate these messages. /// </summary> /// <typeparam name="T">Class Type</typeparam> /// <param name="obj">Instance of the class</param> /// <param name="defaultValue">If no properties have been decorated with the AuditAttribute, then this message is displayed.</param> /// <param name="delimiter">What delimiter do you want between each property. Defaults to comma. Could use vbcrlf, etc.</param> public static String AuditToString <T>(T obj, String defaultValue, String delimiter = GlobalConstants.STRING_DEFAULT_DELIMITER) { var sb = new StringBuilder(2048); var list = new List <SortablePropertyBasket>(); foreach (PropertyInfo prop in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { Object[] auditAttributes = prop.GetCustomAttributes(typeof(AuditAttribute), false); AuditAttribute auditAttribute = null; if (auditAttributes.Length == 1) { auditAttribute = auditAttributes[0] as AuditAttribute; } if (auditAttribute != null) { list.Add(prop.GetValue(obj, null) != null ? new SortablePropertyBasket(auditAttribute.AuditSequence, prop.Name, CamelCaseString.GetWords(prop.Name), prop.GetValue(obj, null).ToString()) : new SortablePropertyBasket(auditAttribute.AuditSequence, prop.Name, CamelCaseString.GetWords(prop.Name), _NULL)); } } if (list.Count > 0) { list.Sort(); foreach (SortablePropertyBasket propertyBasket in list) { sb.Append(propertyBasket.ToString()); sb.Append(delimiter); } if (sb.Length > delimiter.Length) { sb.Length -= delimiter.Length; } } else { sb.Append(defaultValue); } return(sb.ToString()); }
/// <summary> /// Populates the passed in IDictionary with property's name and value in the class for properties decorated with the <see cref="AuditAttribute"/>. /// </summary> /// <typeparam name="T">Class type.</typeparam> /// <param name="instance">The instance.</param> /// <param name="defaultValue">If no class properties are decorated with the <see cref="AuditAttribute"/> then a single entry will be added to the dictionary that is named 'DefaultValue' and will have the value of defaultValue.</param> /// <param name="dictionary">Pass an IDictionary object that needs to be populated. This could be the Data property of an exception object that you want to populate, etc.</param> /// <param name="sortByPropertyName">If set to <c>SortByPropertyName.Yes</c> then output will be sorted by AuditAttribute.AuditSequence and then property name; otherwise no additional sorting is performed and properties; will be left in ordinal order.</param> /// <returns>The dictionary passed in populated with properties and values.</returns> public static IDictionary <String, String> ClassToIDictionary <T>(T instance, String defaultValue, IDictionary <String, String> dictionary, SortByPropertyName sortByPropertyName = SortByPropertyName.Yes) { var list = new List <SortablePropertyBasket>(); foreach (var propInfo in PclReflection.GetPropertiesInfo(instance)) { var auditAttributes = propInfo.GetCustomAttributes <AuditAttribute>(false); var auditAttributeList = new List <AuditAttribute>(auditAttributes); AuditAttribute auditAttribute = null; if (auditAttributeList.Count == 1) { auditAttribute = auditAttributeList[0]; } if (auditAttribute != null) { list.Add(new SortablePropertyBasket(One, propInfo.Name, String.Empty, propInfo.GetValue(instance, null).ToString())); } } if (list.Count > 0) { if (sortByPropertyName == SortByPropertyName.Yes) { list.Sort(); } foreach (SortablePropertyBasket propertyBasket in list) { dictionary.Add(propertyBasket.PropertyName, propertyBasket.Value); } } else { dictionary.Add(DefaultValue, defaultValue); } return(dictionary); }
/// <summary> /// Used to generate a Dictionary(Of String, String) for each property in the entity. Dictionary is property name, property value. This method signature allows a IDictionary Object to be passed in. This feature is useful when generating a name value pair dictionary to store in an Exception Object's Data property. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj">The obj.</param> /// <param name="defaultValue">The default value.</param> /// <param name="dictionary">The dictionary.</param> /// <param name="sortByPropertyName">Name of the sort by property.</param> /// <returns></returns> public static IDictionary <String, String> ClassToIDictionary <T>(T obj, String defaultValue, IDictionary <String, String> dictionary, SortByPropertyName sortByPropertyName = SortByPropertyName.Yes) { var list = new List <SortablePropertyBasket>(); foreach (PropertyInfo prop in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { Object[] auditAttributes = prop.GetCustomAttributes(typeof(AuditAttribute), false); AuditAttribute auditAttribute = null; if (auditAttributes.Length == 1) { auditAttribute = auditAttributes[0] as AuditAttribute; } if (auditAttribute != null) { list.Add(new SortablePropertyBasket(_ONE, prop.Name, String.Empty, prop.GetValue(obj, null).ToString())); } } if (list.Count > 0) { if (sortByPropertyName == SortByPropertyName.Yes) { list.Sort(); } foreach (SortablePropertyBasket propertyBasket in list) { dictionary.Add(propertyBasket.PropertyName, propertyBasket.Value); } } else { dictionary.Add(_DEFAULTVALUE, defaultValue); } return(dictionary); }
/// <summary> /// Populates the dictionary with property's name and value in the class for properties decorated with the <see cref="AuditAttribute"/>. /// </summary> /// <typeparam name="T">Class type.</typeparam> /// <param name="instance">The instance.</param> /// <param name="defaultValue">If no class properties are decorated with the <see cref="AuditAttribute"/> then a single entry will be added to the dictionary that is named 'DefaultValue' and will have the value of defaultValue.</param>. /// <param name="dictionary">Pass an IDictionary object that needs to be populated. This could be the Data property of an exception object that you want to populate, etc.</param> /// <returns>IDictionary populated with properties and values.</returns> public static IDictionary <String, String> AuditToIDictionary <T>(T instance, String defaultValue, IDictionary <String, String> dictionary) { var list = new List <SortablePropertyBasket>(); foreach (var propInfo in PclReflection.GetPropertiesInfo(instance)) { var auditAttributes = propInfo.GetCustomAttributes <AuditAttribute>(false); var auditAttributeList = new List <AuditAttribute>(auditAttributes); AuditAttribute auditAttribute = null; if (auditAttributeList.Count == 1) { auditAttribute = auditAttributeList[0]; } if (auditAttribute != null) { list.Add(new SortablePropertyBasket(auditAttribute.AuditSequence, propInfo.Name, CamelCaseString.GetWords(propInfo.Name), propInfo.GetValue(instance, null).ToString())); } } if (list.Count > 0) { list.Sort(); foreach (var propertyBasket in list) { dictionary.Add(propertyBasket.PropertyName, propertyBasket.Value); } } else { dictionary.Add(DefaultValue, defaultValue); } return(dictionary); }
public void Test_MVC_AuditActionFilter_IncludeResquestResponse() { // Mock out the context to run the action filter. var request = new Mock <HttpRequestBase>(); var nvc = new NameValueCollection(); request.Setup(c => c.ContentType).Returns("application/json"); request.Setup(c => c.Unvalidated.Headers).Returns(() => nvc); request.SetupGet(r => r.InputStream).Returns(new MemoryStream(Encoding.UTF8.GetBytes(@"{ ""test"": 123 }"))); request.SetupGet(r => r.ContentLength).Returns(@"{ ""test"": 123 }".Length); request.SetupGet(r => r.ContentType).Returns(@"json object"); var httpResponse = new Mock <HttpResponseBase>(); httpResponse.Setup(c => c.StatusCode).Returns(200); var itemsDict = new Dictionary <object, object>(); var httpContext = new Mock <HttpContextBase>(); httpContext.SetupGet(c => c.Request).Returns(request.Object); httpContext.SetupGet(c => c.Items).Returns(() => itemsDict); httpContext.SetupGet(c => c.Response).Returns(() => httpResponse.Object); var controllerContext = new ControllerContext() { HttpContext = httpContext.Object }; controllerContext.HttpContext.Request.Unvalidated.Headers.Add("test-header", "header-value"); var ctrlDescriptor = new Mock <ControllerDescriptor>(); ctrlDescriptor.Setup(c => c.ControllerType).Returns(this.GetType()); // controller type (to check controller-level ignore) var param1Descriptor = new Mock <ParameterDescriptor>(); param1Descriptor.Setup(c => c.GetCustomAttributes(It.IsAny <Type>(), It.IsAny <bool>())).Returns(new object[] { }); // custom attribs for param param1Descriptor.Setup(c => c.ParameterName).Returns("test1"); var param2Descriptor = new Mock <ParameterDescriptor>(); param2Descriptor.Setup(c => c.GetCustomAttributes(It.IsAny <Type>(), It.IsAny <bool>())).Returns(new object[] { }); // custom attribs for param param2Descriptor.Setup(c => c.ParameterName).Returns("x"); var actionDescriptor = new Mock <ActionDescriptor>(); actionDescriptor.Setup(c => c.ActionName).Returns("get"); actionDescriptor.Setup(c => c.ControllerDescriptor).Returns(ctrlDescriptor.Object); actionDescriptor.Setup(c => c.GetCustomAttributes(It.IsAny <Type>(), It.IsAny <bool>())).Returns(new object[] { }); // custom attribs for method actionDescriptor.Setup(c => c.GetParameters()).Returns(new ParameterDescriptor[] { param1Descriptor.Object, param2Descriptor.Object }); var args = new Dictionary <string, object>() { { "test1", "value1" } }; var dataProvider = new Mock <AuditDataProvider>(); dataProvider.Setup(x => x.InsertEvent(It.IsAny <AuditEvent>())).Returns(Guid.NewGuid()); Audit.Core.Configuration.DataProvider = dataProvider.Object; Audit.Core.Configuration.CreationPolicy = EventCreationPolicy.InsertOnStartReplaceOnEnd; var filter = new AuditAttribute() { IncludeHeaders = true, IncludeModel = true, EventTypeName = "TestEvent", IncludeRequestBody = true, IncludeResponseBody = true }; var actionExecutingContext = new ActionExecutingContext(controllerContext, actionDescriptor.Object, new Dictionary <string, object> { { "test1", "value1" } }); filter.OnActionExecuting(actionExecutingContext); var scopeFromController = AuditAttribute.GetCurrentScope(httpContext.Object); var actionFromController = scopeFromController.Event.GetMvcAuditAction(); var actionExecutedContext = new ActionExecutedContext(controllerContext, actionDescriptor.Object, false, null); filter.OnActionExecuted(actionExecutedContext); var resultExecute = new ResultExecutedContext(controllerContext, new RedirectResult("url"), false, null); filter.OnResultExecuted(resultExecute); var action = itemsDict["__private_AuditAction__"] as AuditAction; var scope = itemsDict["__private_AuditScope__"] as AuditScope; //Assert dataProvider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Once()); dataProvider.Verify(p => p.ReplaceEvent(It.IsAny <object>(), It.IsAny <AuditEvent>()), Times.Once()); Assert.AreEqual(action, actionFromController); Assert.AreEqual(scope, scopeFromController); dataProvider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Once()); Assert.AreEqual("header-value", action.Headers["test-header"]); Assert.AreEqual("get", action.ActionName); Assert.AreEqual("value1", action.ActionParameters["test1"]); Assert.AreEqual(@"json object", action.RequestBody.Type); Assert.AreEqual(@"{ ""test"": 123 }", action.RequestBody.Value); Assert.AreEqual(@"{ ""test"": 123 }".Length, action.RequestBody.Length); Assert.AreEqual("RedirectResult", action.ResponseBody.Type); Assert.AreEqual("url", action.ResponseBody.Value); }
public void Test_MVC_AuditActionFilter_IgnoreParam() { var request = new Mock <HttpRequestBase>(); var nvc = new NameValueCollection(); //var request = new HttpRequest(null, "http://200.10.10.20:1010/api/values", null); request.Setup(c => c.ContentType).Returns("application/json"); request.Setup(c => c.Unvalidated.Headers).Returns(() => nvc); var httpResponse = new Mock <HttpResponseBase>(); httpResponse.Setup(c => c.StatusCode).Returns(200); var itemsDict = new Dictionary <object, object>(); var httpContext = new Mock <HttpContextBase>(); httpContext.SetupGet(c => c.Request).Returns(request.Object); httpContext.SetupGet(c => c.Items).Returns(() => itemsDict); httpContext.SetupGet(c => c.Response).Returns(() => httpResponse.Object); var controllerContext = new ControllerContext() { HttpContext = httpContext.Object }; controllerContext.HttpContext.Request.Unvalidated.Headers.Add("test-header", "header-value"); var ctrlDescriptor = new Mock <ControllerDescriptor>(); ctrlDescriptor.Setup(c => c.ControllerType).Returns(this.GetType()); // controller type (to check controller-level ignore) var param1Descriptor = new Mock <ParameterDescriptor>(); param1Descriptor.Setup(c => c.GetCustomAttributes(It.IsAny <Type>(), It.IsAny <bool>())).Returns(new object[] { new AuditIgnoreAttribute() }); // custom attribs for param param1Descriptor.Setup(c => c.ParameterName).Returns("test1"); var param2Descriptor = new Mock <ParameterDescriptor>(); param2Descriptor.Setup(c => c.GetCustomAttributes(It.IsAny <Type>(), It.IsAny <bool>())).Returns(new object[] { }); // custom attribs for param param2Descriptor.Setup(c => c.ParameterName).Returns("x"); var actionDescriptor = new Mock <ActionDescriptor>(); actionDescriptor.Setup(c => c.ActionName).Returns("get"); actionDescriptor.Setup(c => c.ControllerDescriptor).Returns(ctrlDescriptor.Object); actionDescriptor.Setup(c => c.GetCustomAttributes(It.IsAny <Type>(), It.IsAny <bool>())).Returns(new object[] { }); // custom attribs for method actionDescriptor.Setup(c => c.GetParameters()).Returns(new ParameterDescriptor[] { param1Descriptor.Object, param2Descriptor.Object }); var args = new Dictionary <string, object>() { { "test1", "value1" }, { "x", new AuditAttribute() { EventTypeName = "TEST" } } }; var dataProvider = new Mock <AuditDataProvider>(); dataProvider.Setup(x => x.InsertEvent(It.IsAny <AuditEvent>())).Returns(Guid.NewGuid()); Audit.Core.Configuration.DataProvider = dataProvider.Object; Audit.Core.Configuration.CreationPolicy = EventCreationPolicy.InsertOnEnd; var filter = new AuditAttribute() { IncludeHeaders = true, IncludeModel = true, EventTypeName = "TestEvent", SerializeActionParameters = true }; var actionExecutingContext = new ActionExecutingContext(controllerContext, actionDescriptor.Object, args); filter.OnActionExecuting(actionExecutingContext); var actionExecutedContext = new ActionExecutedContext(controllerContext, actionDescriptor.Object, false, null); filter.OnActionExecuted(actionExecutedContext); var resultExecute = new ResultExecutedContext(controllerContext, new RedirectResult("url"), false, null); filter.OnResultExecuted(resultExecute); var action = itemsDict["__private_AuditAction__"] as AuditAction; var scope = itemsDict["__private_AuditScope__"] as AuditScope; //Assert dataProvider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Once()); dataProvider.Verify(p => p.ReplaceEvent(It.IsAny <object>(), It.IsAny <AuditEvent>()), Times.Never()); Assert.AreEqual(1, action.ActionParameters.Count); Assert.AreEqual("TEST", (action.ActionParameters["x"] as AuditAttribute).EventTypeName); }
public void Method1_IgnoredParam([AuditIgnore] string test1, AuditAttribute x, [AuditIgnore] string extra) { }
public void Method1(string test1, AuditAttribute x, string extra) { }
public async Task Test_MVC_AuditActionFilter_Core_InsertOnEnd() { // Mock out the context to run the action filter. var request = new Mock <HttpRequest>(); request.SetupGet(r => r.Scheme).Returns("http"); request.SetupGet(r => r.Host).Returns(new HostString("200.10.10.20:1010")); request.SetupGet(r => r.Path).Returns("/home/index"); var httpResponse = new Mock <HttpResponse>(); httpResponse.SetupGet(c => c.StatusCode).Returns(200); var itemsDict = new Dictionary <object, object>(); var httpContext = new Mock <HttpContext>(); httpContext.SetupGet(c => c.Request).Returns(request.Object); httpContext.SetupGet(c => c.Items).Returns(() => itemsDict); httpContext.SetupGet(c => c.Response).Returns(() => httpResponse.Object); var ci = new Mock <ConnectionInfo>(); ci.SetupGet(_ => _.RemoteIpAddress).Returns(() => null); httpContext.SetupGet(c => c.Connection).Returns(() => ci.Object); var actionContext = new ActionContext() { HttpContext = httpContext.Object, RouteData = new RouteData(), ActionDescriptor = new ControllerActionDescriptor() { ActionName = "index", ControllerName = "home" } }; var args = new Dictionary <string, object>() { { "test1", "value1" } }; var filters = new List <IFilterMetadata>(); var controller = new Mock <Controller>(); var dataProvider = new Mock <AuditDataProvider>(); dataProvider.Setup(x => x.InsertEventAsync(It.IsAny <AuditEvent>())).ReturnsAsync(() => Task.FromResult(Guid.NewGuid())); Audit.Core.Configuration.DataProvider = dataProvider.Object; Audit.Core.Configuration.CreationPolicy = EventCreationPolicy.InsertOnEnd; var filter = new AuditAttribute() { IncludeHeaders = true, IncludeModel = true, EventTypeName = "TestEvent" }; var actionExecutingContext = new ActionExecutingContext(actionContext, filters, args, controller.Object); var actionExecutedContext = new ActionExecutedContext(actionContext, filters, controller.Object); actionExecutedContext.Result = new ObjectResult("this is the result"); var resultExecuting = new ResultExecutingContext(actionContext, new List <IFilterMetadata>(), new RedirectResult("url"), controller.Object); var resultExecute = new ResultExecutedContext(actionContext, new List <IFilterMetadata>(), new RedirectResult("url"), controller.Object); await filter.OnActionExecutionAsync(actionExecutingContext, async() => await Task.FromResult(actionExecutedContext)); var scopeFromController = AuditAttribute.GetCurrentScope(httpContext.Object); var actionFromController = scopeFromController.Event.GetMvcAuditAction(); await filter.OnResultExecutionAsync(resultExecuting, () => Task.FromResult <ResultExecutedContext>(resultExecute)); var action = itemsDict["__private_AuditAction__"] as AuditAction; var scope = itemsDict["__private_AuditScope__"] as AuditScope; //Assert dataProvider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Never); dataProvider.Verify(p => p.InsertEventAsync(It.IsAny <AuditEvent>()), Times.Once); dataProvider.Verify(p => p.ReplaceEvent(It.IsAny <object>(), It.IsAny <AuditEvent>()), Times.Never); dataProvider.Verify(p => p.ReplaceEventAsync(It.IsAny <object>(), It.IsAny <AuditEvent>()), Times.Never); Assert.AreEqual(action, actionFromController); Assert.AreEqual(scope, scopeFromController); Assert.AreEqual("http://200.10.10.20:1010/home/index", action.RequestUrl); Assert.AreEqual("home", action.ControllerName); Assert.AreEqual("value1", action.ActionParameters["test1"]); Assert.AreEqual(200, action.ResponseStatusCode); }
public void Test_AuditActionFilter_Manual() { // Mock out the context to run the action filter. var request = new Mock <HttpRequestBase>(); var nvc = new NameValueCollection(); //var request = new HttpRequest(null, "http://200.10.10.20:1010/api/values", null); request.Setup(c => c.ContentType).Returns("application/json"); #if NET40 request.Setup(c => c.Headers).Returns(() => nvc); #else request.Setup(c => c.Unvalidated.Headers).Returns(() => nvc); #endif var httpResponse = new Mock <HttpResponseBase>(); httpResponse.Setup(c => c.StatusCode).Returns(200); var itemsDict = new Dictionary <object, object>(); var httpContext = new Mock <HttpContextBase>(); httpContext.SetupGet(c => c.Request).Returns(request.Object); httpContext.SetupGet(c => c.Items).Returns(() => itemsDict); httpContext.SetupGet(c => c.Response).Returns(() => httpResponse.Object); var controllerContext = new ControllerContext() { HttpContext = httpContext.Object }; #if NET40 controllerContext.HttpContext.Request.Headers.Add("test-header", "header-value"); #else controllerContext.HttpContext.Request.Unvalidated.Headers.Add("test-header", "header-value"); #endif var actionDescriptor = new Mock <ActionDescriptor>(); actionDescriptor.Setup(c => c.ActionName).Returns("get"); var args = new Dictionary <string, object>() { { "test1", "value1" } }; var dataProvider = new Mock <AuditDataProvider>(); dataProvider.Setup(x => x.InsertEvent(It.IsAny <AuditEvent>())).Returns(Guid.NewGuid()); Audit.Core.Configuration.DataProvider = dataProvider.Object; Audit.Core.Configuration.CreationPolicy = EventCreationPolicy.Manual; var filter = new AuditAttribute() { IncludeHeaders = true, IncludeModel = true, EventTypeName = "TestEvent" }; var actionExecutingContext = new ActionExecutingContext(controllerContext, actionDescriptor.Object, new Dictionary <string, object> { { "test1", "value1" } }); filter.OnActionExecuting(actionExecutingContext); var scopeFromController = AuditAttribute.GetCurrentScope(httpContext.Object); var actionFromController = scopeFromController.Event.GetMvcAuditAction(); var actionExecutedContext = new ActionExecutedContext(controllerContext, actionDescriptor.Object, false, null); filter.OnActionExecuted(actionExecutedContext); var resultExecute = new ResultExecutedContext(controllerContext, new RedirectResult("url"), false, null); filter.OnResultExecuted(resultExecute); var action = itemsDict["__private_AuditAction__"] as AuditAction; var scope = itemsDict["__private_AuditScope__"] as AuditScope; //Assert dataProvider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Once()); dataProvider.Verify(p => p.ReplaceEvent(It.IsAny <object>(), It.IsAny <AuditEvent>()), Times.Never()); Assert.AreEqual(action, actionFromController); Assert.AreEqual(scope, scopeFromController); dataProvider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Once()); Assert.AreEqual("header-value", action.Headers["test-header"]); Assert.AreEqual("get", action.ActionName); Assert.AreEqual("value1", action.ActionParameters["test1"]); }
public void Test_AuditActionFilter() { // Mock out the context to run the action filter. var request = new Mock <HttpRequestBase>(); var nvc = new NameValueCollection(); //var request = new HttpRequest(null, "http://200.10.10.20:1010/api/values", null); request.Setup(c => c.ContentType).Returns("application/json"); request.Setup(c => c.Headers).Returns(() => nvc); var httpResponse = new Mock <HttpResponseBase>(); httpResponse.Setup(c => c.StatusCode).Returns(200); var itemsDict = new Dictionary <object, object>(); var httpContext = new Mock <HttpContextBase>(); httpContext.SetupGet(c => c.Request).Returns(request.Object); httpContext.SetupGet(c => c.Items).Returns(() => itemsDict); httpContext.SetupGet(c => c.Response).Returns(() => httpResponse.Object); var controllerContext = new ControllerContext() { HttpContext = httpContext.Object }; controllerContext.HttpContext.Request.Headers.Add("test-header", "header-value"); var actionDescriptor = new Mock <ActionDescriptor>(); actionDescriptor.Setup(c => c.ActionName).Returns("get"); var args = new Dictionary <string, object>() { { "test1", "value1" } }; var dataProvider = new Mock <AuditDataProvider>(); Audit.Core.Configuration.DataProvider = dataProvider.Object; var filter = new AuditAttribute() { IncludeHeaders = true, IncludeModel = true, EventTypeName = "TestEvent" }; var actionExecutingContext = new ActionExecutingContext(controllerContext, actionDescriptor.Object, new Dictionary <string, object> { { "test1", "value1" } }); //.Properties.Add("MS_HttpContext", httpContext.Object); filter.OnActionExecuting(actionExecutingContext); var actionExecutedContext = new ActionExecutedContext(controllerContext, actionDescriptor.Object, false, null); filter.OnActionExecuted(actionExecutedContext); var action = itemsDict["__private_AuditAction__"] as AuditAction; var scope = itemsDict["__private_AuditScope__"] as AuditScope; //Assert dataProvider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Once); Assert.Equal("header-value", action.Headers["test-header"]); Assert.Equal("get", action.ActionName); Assert.Equal("value1", action.ActionParameters["test1"]); }
public void Test_AuditActionFilter_Core() { // Mock out the context to run the action filter. var request = new Mock <HttpRequest>(); request.SetupGet(r => r.Scheme).Returns("http"); request.SetupGet(r => r.Host).Returns(new HostString("200.10.10.20:1010")); request.SetupGet(r => r.Path).Returns("/home/index"); var httpResponse = new Mock <HttpResponse>(); httpResponse.SetupGet(c => c.StatusCode).Returns(200); var itemsDict = new Dictionary <object, object>(); var httpContext = new Mock <HttpContext>(); httpContext.SetupGet(c => c.Request).Returns(request.Object); httpContext.SetupGet(c => c.Items).Returns(() => itemsDict); httpContext.SetupGet(c => c.Response).Returns(() => httpResponse.Object); var actionContext = new ActionContext() { HttpContext = httpContext.Object, RouteData = new RouteData(), ActionDescriptor = new ControllerActionDescriptor() { ActionName = "index", ControllerName = "home" } }; var args = new Dictionary <string, object>() { { "test1", "value1" } }; var filters = new List <IFilterMetadata>(); var controller = new Mock <Controller>(); var dataProvider = new Mock <AuditDataProvider>(); Audit.Core.Configuration.DataProvider = dataProvider.Object; var filter = new AuditAttribute() { IncludeHeaders = true, IncludeModel = true, EventTypeName = "TestEvent" }; var actionExecutingContext = new ActionExecutingContext(actionContext, filters, args, controller.Object); filter.OnActionExecuting(actionExecutingContext); var scopeFromController = AuditAttribute.GetCurrentScope(httpContext.Object); var actionFromController = scopeFromController.Event.GetMvcAuditAction(); var actionExecutedContext = new ActionExecutedContext(actionContext, filters, controller.Object); actionExecutedContext.Result = new ObjectResult("this is the result"); filter.OnActionExecuted(actionExecutedContext); var action = itemsDict["__private_AuditAction__"] as AuditAction; var scope = itemsDict["__private_AuditScope__"] as AuditScope; //Assert dataProvider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Once); Assert.Equal(action, actionFromController); Assert.Equal(scope, scopeFromController); Assert.Equal("http://200.10.10.20:1010/home/index", action.RequestUrl); Assert.Equal("home", action.ControllerName); Assert.Equal("value1", action.ActionParameters["test1"]); Assert.Equal(200, action.ResponseStatusCode); }
public async Task Test_MVC_AuditActionFilter_Core_IgnoreParam() { // Mock out the context to run the action filter. var request = new Mock <HttpRequest>(); request.SetupGet(r => r.Scheme).Returns("http"); request.SetupGet(r => r.Host).Returns(new HostString("200.10.10.20:1010")); request.SetupGet(r => r.Path).Returns("/home/index"); var httpResponse = new Mock <HttpResponse>(); httpResponse.SetupGet(c => c.StatusCode).Returns(200); var itemsDict = new Dictionary <object, object>(); var httpContext = new Mock <HttpContext>(); httpContext.SetupGet(c => c.Request).Returns(request.Object); httpContext.SetupGet(c => c.Items).Returns(() => itemsDict); httpContext.SetupGet(c => c.Response).Returns(() => httpResponse.Object); var actionContext = new ActionContext() { HttpContext = httpContext.Object, RouteData = new RouteData(), ActionDescriptor = new ControllerActionDescriptor() { ActionName = "index", ControllerName = "home", ControllerTypeInfo = typeof(MockMethodInfo).GetTypeInfo(), MethodInfo = typeof(MockMethodInfo).GetMethod("Method1_IgnoredParam") } }; var args = new Dictionary <string, object>() { { "test1", "value1" }, { "x", new AuditAttribute() { EventTypeName = "TEST_REFERENCE_TYPE" } } }; var filters = new List <IFilterMetadata>(); var controller = new Mock <Controller>(); var dataProvider = new Mock <AuditDataProvider>(); dataProvider.Setup(x => x.InsertEventAsync(It.IsAny <AuditEvent>())).ReturnsAsync(() => Task.FromResult(Guid.NewGuid())); Audit.Core.Configuration.DataProvider = dataProvider.Object; Audit.Core.Configuration.CreationPolicy = EventCreationPolicy.InsertOnStartReplaceOnEnd; var filter = new AuditAttribute() { IncludeHeaders = true, IncludeModel = true, EventTypeName = "TestEvent", SerializeActionParameters = true }; var actionExecutingContext = new ActionExecutingContext(actionContext, filters, args, controller.Object); var actionExecutedContext = new ActionExecutedContext(actionContext, filters, controller.Object); actionExecutedContext.Result = new ObjectResult("this is the result"); var resultExecuting = new ResultExecutingContext(actionContext, new List <IFilterMetadata>(), new RedirectResult("url"), controller.Object); var resultExecute = new ResultExecutedContext(actionContext, new List <IFilterMetadata>(), new RedirectResult("url"), controller.Object); await filter.OnActionExecutionAsync(actionExecutingContext, async() => await Task.FromResult(actionExecutedContext)); await filter.OnResultExecutionAsync(resultExecuting, () => Task.FromResult <ResultExecutedContext>(resultExecute)); //Assert var action = itemsDict["__private_AuditAction__"] as AuditAction; var scope = itemsDict["__private_AuditScope__"] as AuditScope; //Assert dataProvider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Never); dataProvider.Verify(p => p.InsertEventAsync(It.IsAny <AuditEvent>()), Times.Once); dataProvider.Verify(p => p.ReplaceEvent(It.IsAny <object>(), It.IsAny <AuditEvent>()), Times.Never); dataProvider.Verify(p => p.ReplaceEventAsync(It.IsAny <object>(), It.IsAny <AuditEvent>()), Times.Once); Assert.AreEqual(1, action.ActionParameters.Count); Assert.AreEqual("TEST_REFERENCE_TYPE", (action.ActionParameters["x"] as AuditAttribute).EventTypeName); Assert.AreEqual(200, action.ResponseStatusCode); }