AuditDataProvider

Namespace: Audit.NET
We found 10 examples in language CSharp for this search. You will see 28 fragments of code.
using System;
using System.Reflection;
using Audit.Core;

namespace Demo.Audit.DynamicProxy
{
    /// <summary>
    /// Settings for an interception.
    /// </summary>
    public class InterceptionSettings
    {
        /// <summary>
        /// Gets or sets the type of the event. Default is "{class}.{method}".
        /// Can include the following placeholders:
        ///  - {class}: Replaced by the class name
        ///  - {method}: Replaced by the method name
        /// </summary>
        /// <value>The type of the event.</value>
        public string EventType { get; set; } = "{class}.{method}";
        /// <summary>
        /// Gets or sets a value indicating whether the audit should ignore the property getters and setters.
        /// If <c>true</c>, the property accesses will not be logged.
        /// </summary>
        public bool IgnoreProperties { get; set; }
        /// <summary>
        /// Gets or sets a value indicating whether the audit should ignore the event attach and dettach actions.
        /// If <c>true</c>, the event accesses will not be logged.
        /// </summary>
        public bool IgnoreEvents { get; set; }
        /// <summary>
        /// Gets or sets the audit data provider to use.
        /// </summary>
        public AuditDataProvider AuditDataProvider { get; set; }
        /// <summary>
        /// Gets or sets the methods filter, a function that returns true for the methods to be included or false otherwise.
        /// By default all methods are included.
        /// </summary>
        public Func<MethodInfo, bool> MethodFilter { get; set; }
        /// <summary>
        /// Gets or sets the event creation policy to use for this interception. Default is NULL to use the globally configured creation policy.
        /// </summary>
        public EventCreationPolicy? EventCreationPolicy { get; set; }
    }
}


        public object[] AllocateInputs()
        {
            return _baseInvoker.AllocateInputs();
        }

        /// <summary>
        /// Returns an object and a set of output objects from an instance and set of input objects.
        /// </summary>
        /// <param name="instance">The object to be invoked.</param>
        /// <param name="inputs">The inputs to the method.</param>
        /// <param name="outputs">The outputs from the method.</param>
        public object Invoke(object instance, object[] inputs, out object[] outputs)
        {
            object result = null;
            // Create the Wcf audit event
            var auditWcfEvent = CreateWcfAuditEvent(instance, inputs);
            // Create the audit scope
            var eventType = _eventType.Replace("{contract}", auditWcfEvent.ContractName)
                .Replace("{operation}", auditWcfEvent.OperationName);
            var auditEventWcf = new AuditEventWcfAction()
            {
                WcfEvent = auditWcfEvent
            };
            // Create the audit scope
            using (var auditScope = AuditScope.Create(new AuditScopeOptions()
            {
                EventType = eventType,
                CreationPolicy = _creationPolicy,
                AuditEvent = auditEventWcf,
                DataProvider = GetAuditDataProvider(instance),
                CallingMethod = _operationDescription.SyncMethod ?? _operationDescription.TaskMethod
            }))
            {
                // Store a reference to this audit scope on a thread static field
                AuditBehavior.CurrentAuditScope = auditScope;
                try
                {
                    result = _baseInvoker.Invoke(instance, inputs, out outputs);
                }
                catch (Exception ex)
                {
                    AuditBehavior.CurrentAuditScope = null;
                    auditWcfEvent.Fault = GetWcfFaultData(ex);
                    auditWcfEvent.Success = false;
                    (auditScope.Event as AuditEventWcfAction).WcfEvent = auditWcfEvent;
                    throw;
                }
                AuditBehavior.CurrentAuditScope = null;
                auditWcfEvent.OutputParameters = GetEventElements(outputs);
                auditWcfEvent.Result = new AuditWcfEventElement(result);
                (auditScope.Event as AuditEventWcfAction).WcfEvent = auditWcfEvent;
            }
            return result;
        }

        /// <summary>
        /// Asynchronous implementation of the Invoke (Begin)
        /// </summary>
        public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
        {
            IAsyncResult result = null;
            // Create the Wcf audit event
            var auditWcfEvent = CreateWcfAuditEvent(instance, inputs);
            // Create the audit scope
            var eventType = _eventType.Replace("{contract}", auditWcfEvent.ContractName)
                .Replace("{operation}", auditWcfEvent.OperationName);
            var auditEventWcf = new AuditEventWcfAction()
            {
                WcfEvent = auditWcfEvent
            };
            // Create the audit scope
            var auditScope = AuditScope.Create(new AuditScopeOptions()
            {
                EventType = eventType,
                CreationPolicy = _creationPolicy,
                AuditEvent = auditEventWcf,
                DataProvider = GetAuditDataProvider(instance),
                CallingMethod = _operationDescription.SyncMethod ?? _operationDescription.TaskMethod
            });
            // Store a reference to this audit scope
            var callbackState = new AuditScopeState()
            {
                AuditScope = auditScope,
                OriginalUserCallback = callback,
                OriginalUserState = state
            };
            AuditBehavior.CurrentAuditScope = auditScope;
            try
            {
                result = _baseInvoker.InvokeBegin(instance, inputs, this.InvokerCallback, callbackState);
            }
            catch (Exception ex)
            {
                AuditBehavior.CurrentAuditScope = null;
                auditWcfEvent.Fault = GetWcfFaultData(ex);
                auditWcfEvent.Success = false;
                (auditScope.Event as AuditEventWcfAction).WcfEvent = auditWcfEvent;
                auditScope.Dispose();
                throw;
            }
            AuditBehavior.CurrentAuditScope = null;
            return new AuditScopeAsyncResult(result, callbackState);
        }

        /// <summary>
        /// Asynchronous implementation of the Invoke (End)
        /// </summary>
        public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
        {
            var auditAsyncResult = result as AuditScopeAsyncResult;
            var auditScopeState = auditAsyncResult.AuditScopeState;
            object callResult;
            var auditScope = auditScopeState.AuditScope;
            var auditWcfEvent = (auditScope.Event as AuditEventWcfAction).WcfEvent;
            try
            {
                callResult = _baseInvoker.InvokeEnd(instance, out outputs, auditAsyncResult.OriginalAsyncResult);
            }
            catch (Exception ex)
            {
                AuditBehavior.CurrentAuditScope = null;
                auditWcfEvent.Fault = GetWcfFaultData(ex);
                auditWcfEvent.Success = false;
                (auditScope.Event as AuditEventWcfAction).WcfEvent = auditWcfEvent;
                auditScope.Dispose();
                throw;
            }
            AuditBehavior.CurrentAuditScope = null;
            auditWcfEvent.OutputParameters = GetEventElements(outputs);
            auditWcfEvent.Result = new AuditWcfEventElement(callResult);
            (auditScope.Event as AuditEventWcfAction).WcfEvent = auditWcfEvent;
            auditScope.Dispose();
            return callResult;
        }
        #endregion

        #region Private Methods
        private WcfEvent CreateWcfAuditEvent(object instance, object[] inputs)
        {
            var securityContext = ServiceSecurityContext.Current;
            var operationContext = OperationContext.Current;
            var imProps = OperationContext.Current.IncomingMessageProperties;
            var endpoint = imProps.ContainsKey(RemoteEndpointMessageProperty.Name) ? imProps[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty : null;
            return new WcfEvent()
            {
                Action = _operation.Action,
                ReplyAction = _operation.ReplyAction,
                ContractName = _operationDescription.DeclaringContract.Name,
                IsAsync = _operationDescription.SyncMethod == null,
                MethodSignature = (_operationDescription.SyncMethod ?? _operationDescription.TaskMethod).ToString(),
                OperationName = _operation.Name,
                ClientAddress = endpoint?.Address,
                HostAddress = string.Join(", ", operationContext.InstanceContext.Host?.BaseAddresses?.Select(a => a.AbsoluteUri)),
                InstanceQualifiedName = instance.GetType().AssemblyQualifiedName,
                InputParameters = GetEventElements(inputs),
                IdentityName = securityContext?.WindowsIdentity?.Name ?? securityContext?.PrimaryIdentity?.Name,
                Success = true
            };
        }

        /// <summary>
        /// Get the dataprovider from property AuditDataProvider
        /// </summary>
        private AuditDataProvider GetAuditDataProvider(object instance)
        {
            var prop = instance.GetType().GetProperty("AuditDataProvider", typeof(AuditDataProvider));
            if (prop != null)
            {
                return prop.GetGetMethod().Invoke(instance, null) as AuditDataProvider;
            }
            return null;
        }


        public override object InsertEvent(AuditEvent auditEvent)
        {
            GoogleLoggerProvider googleLoggerProvider = GoogleLoggerProvider.Create(_serviceProvider, "gcplogging");
            ILogger logger = googleLoggerProvider.CreateLogger("Audit.NET");

            logger.LogInformation(JsonSerializer.Serialize(auditEvent));
            return null;
        }


        public override object InsertEvent(AuditEvent auditEvent)
        {
            var action = auditEvent.GetWebApiAuditAction();

            using (LogContext.Push(new AuditLogEnricher(auditEvent, action)))
            {
                Log.Information(MessageTemplate, auditEvent.EventType, action.RequestUrl, action.ResponseStatus, auditEvent.Duration);
            }

            return null;
        }


        public async Task<Cow> GetCow(int id)
        {
            var cowSpecification = new CowSpecifications(a => a.CowId == id);
            var cow = await _uow.Repository<Cow>().GetEntityWithSpec(cowSpecification);
            return cow;
        }

        public async Task<IReadOnlyList<Cow>> GetCows()
        {
            var cowSpecification = new CowSpecifications();
            var cowList = await _uow.Repository<Cow>().ListAsync(cowSpecification);
            return cowList;
        }

        public async Task<Outcome<Cow>> Update(int cowId, StateDto stateDto)
        {
            var result = new Outcome<Cow>();

            if (!Enum.GetNames(typeof(CowState)).Any(x => x.Equals(stateDto.State, StringComparison.InvariantCultureIgnoreCase)))
            {
                result.ErrorMessage = "State is not valid";
                return result;
            }

            var cowSpecification = new CowSpecifications(a => a.CowId == cowId);
            var cow = await _uow.Repository<Cow>().GetEntityWithSpec(cowSpecification);
            if (cow != null)
            {
                var auditData = _auditDataProvider.GetAuditList(DateTime.Now.Date, string.Empty, "Cows", cow.Farm.Name, cow.CowId);
                if (auditData != null && auditData.Any())
                {
                    cow.RecordFlag = "Error";
                }
                var state = Enum.GetNames(typeof(CowState)).FirstOrDefault(x => x.Equals(stateDto.State, StringComparison.InvariantCultureIgnoreCase));

                cow.State = (CowState)Enum.Parse(typeof(CowState), state);
                cow.UpdateDt = DateTime.Now;
                _uow.Repository<Cow>().Update(cow);
                int output = await _uow.Complete();

                result.Result = cow;
            }
            else
                result.ErrorMessage = "Cow not found";

            return result;
        }


        public List<PolicyTermAuditDispute> GetAuditDisputesForPolicyId(int policyId)
        {
            Ensure.ArgumentValidId(policyId, "Policy Id");

            try
            {
                var audit = _auditDataProvider.GetById(policyId);
                if (audit != null) return _policyAuditDisputeDataProvider.GetAuditDisputesForAuditId(audit.Id).SortByDisputeDateDescThenByNoteDateDescThenByTextAsc();
            }
            catch (ValidationException ex)
            {
                _log.FatalFormat($"{ex.Message} {ex.StackTrace}");
            }
            return new List<PolicyTermAuditDispute>();
        }

        public PolicyTermAuditDispute GetAuditDisputeForDisputeId(int auditDisputeId)
        {
            Ensure.ArgumentValidId(auditDisputeId, "Audit Dispute Id");

            try
            {
                return _policyAuditDisputeDataProvider.GetAuditDisputeById(auditDisputeId);
            }
            catch (ValidationException ex)
            {
                _log.FatalFormat($"{ex.Message} {ex.StackTrace}");
            }
            return null;
        }

        [TraceLog]
        public IResult SaveAuditDispute(PolicyTermAuditDispute policyTermAuditDispute)
        {
            Ensure.ArgumentNotNull(policyTermAuditDispute, "Policy term audit dispute");
            try
            {
                var result = _policyAuditDisputeDataProvider.Save(policyTermAuditDispute);
                if (result.ResultType == ResultType.Success) return result;

                var failResult = (FailResult) result;
                {
                    _log.ErrorFormat($"Save failed: {failResult.Display}");
                    return failResult;
                }
            }
            catch (ValidationException ex)
            {
                _log.FatalFormat($"{ex.Message} {ex.StackTrace}");
                return new FailResult($"{ex.Message} {ex.StackTrace}");
            }
        }


        public async Task<Outcome<Sensor>> Add(SensorAddDto sensorDto)
        {
            var result = new Outcome<Sensor>();

            if (!Enum.GetNames(typeof(SensorState)).Any(x => x.Equals(sensorDto.State, StringComparison.InvariantCultureIgnoreCase)))
            {
                result.ErrorMessage = "State is not valid";
                return result;
            }

            var farm = await _uow.Repository<Farm>().GetEntityWithSpec(new FarmNameSpecifications(a => a.Name.ToLower() == sensorDto.Farm.ToLower()));

            if (farm != null)
            {
                var state = Enum.GetNames(typeof(SensorState)).FirstOrDefault(x => x.Equals(sensorDto.State, StringComparison.InvariantCultureIgnoreCase));
                var sensor = new Sensor();
                sensor.FarmId = farm.FarmId;
                sensor.State = (SensorState)Enum.Parse(typeof(SensorState), state);

                sensor.CreateDt = DateTime.Now;
                _uow.Repository<Sensor>().Add(sensor);
                int output = await _uow.Complete();

                if (output >= 1)
                {
                    result.Result = sensor;
                    return result;
                }
            }
            else result.ErrorMessage = "Farm not found";

            return result;
        }

        public async Task<Sensor> GetSensor(int id)
        {
            var sensorSpecification = new SensorSpecifications(a => a.SensorId == id);
            var sensor = await _uow.Repository<Sensor>().GetEntityWithSpec(sensorSpecification);
            return sensor;
        }

        public async Task<IReadOnlyList<Sensor>> GetSensors()
        {
            var sensorSpecification = new SensorSpecifications();
            var sensorList = await _uow.Repository<Sensor>().ListAsync(sensorSpecification);
            return sensorList;
        }

        public async Task<Outcome<Sensor>> Update(int sensorId, StateDto stateDto)
        {
            var result = new Outcome<Sensor>();

            if (!Enum.GetNames(typeof(SensorState)).Any(x => x.Equals(stateDto.State, StringComparison.InvariantCultureIgnoreCase)))
            {
                result.ErrorMessage = "State is not valid";
                return result;
            }

            var sensor = _uow.Repository<Sensor>().GetEntityWithSpec(new SensorSpecifications(a => a.SensorId == sensorId)).Result;

            if (sensor != null)
            {
                var auditData = _auditDataProvider.GetAuditList(DateTime.Now.Date, string.Empty, "Sensors", sensor.Farm.Name, sensor.SensorId);
                if (auditData != null && auditData.Any())
                {
                    sensor.RecordFlag = "Error";
                }
                var state = Enum.GetNames(typeof(SensorState)).FirstOrDefault(x => x.Equals(stateDto.State, StringComparison.InvariantCultureIgnoreCase));
                sensor.State = (SensorState)Enum.Parse(typeof(SensorState), state);
                sensor.UpdateDt = DateTime.Now;
                _uow.Repository<Sensor>().Update(sensor);
                int output = await _uow.Complete();
                result.Result = sensor;
            }
            else result.ErrorMessage = "Sensor not found";

            return result;

        }


        private string GetFileName(AuditEvent auditEvent)
        {
            try
            {
                EventEntry eventEntry = auditEvent.GetEntityFrameworkEvent().Entries.FirstOrDefault();
                if (eventEntry != null)
                {
                    string tableName = eventEntry.Table;
                    object id = eventEntry.PrimaryKey.FirstOrDefault().Value;
                    string action = eventEntry.Action;

                    return $"{tableName}_{action}_{id}_{DateTime.Now:yyyyMMddHHmmssffff}.json";
                }

                return $"Log{Guid.NewGuid()}.json";
            }
            catch
            {
                return $"Log{Guid.NewGuid()}.json";
            }
        }

        public override object InsertEvent(AuditEvent auditEvent)
        {
            try
            {
                string fileName = GetFileName(auditEvent);

                string path = Path.Combine(_directoryPath, fileName);

                File.WriteAllText(path, auditEvent.ToJson());
                return fileName;
            }
            catch
            {
                return $"Log{Guid.NewGuid()}.json";
            }
        }

        public override void ReplaceEvent(object eventId, AuditEvent auditEvent)
        {
            var fileName = eventId.ToString();
            File.WriteAllText(fileName, auditEvent.ToJson());
        }

        public override T GetEvent<T>(object eventId)
        {
            var fileName = eventId.ToString();
            return JsonConvert.DeserializeObject<T>(File.ReadAllText(fileName));
        }


        /// <summary>
        /// Get list of cows
        /// </summary>
        /// <returns><seealso cref="IReadOnlyList{CowDto}"/></returns>
        [HttpGet()]
        [ProducesResponseType(typeof(IReadOnlyList<CowDto>), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<ActionResult<IReadOnlyList<CowDto>>> GetCows()
        {
            var cowList = await _cowDataProvider.GetCows();
            return Ok(_mapper.Map<IReadOnlyList<CowDto>>(cowList));
        }

        /// <summary>
        /// Get Cow based on cow ID
        /// </summary>
        /// <param name="id">Cow Id</param>
        /// <returns><seealso cref="CowDto"/></returns>
        [HttpGet("{id}")]
        [ProducesResponseType(typeof(CowDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<ActionResult<CowDto>> GetCow(int id)
        {
            var cow = await _cowDataProvider.GetCow(id);

            var mappedDto = _mapper.Map<CowDto>(cow);

            if (mappedDto != null)
                return Ok(mappedDto);
            else
                return NotFound("Cow not found");
        }

        /// <summary>
        /// Update the cow's status based on CowId
        /// </summary>
        /// <param name="cowId">cowId to update cow</param>
        /// <param name="stateDto">Dto to update status</param>
        /// <returns><seealso cref="CowDto"/></returns>
        [HttpPut("{cowId}")]
        [ProducesResponseType(typeof(CowDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<ActionResult<CowDto>> Update(int cowId, [FromBody]StateDto stateDto)
        {
            var outcome = await _cowDataProvider.Update(cowId, stateDto);

            if (outcome.Successful)
            {
                var cowDto = _mapper.Map<CowDto>(outcome.Result);
                return Ok(cowDto);
            }

            return BadRequest(outcome.ErrorMessage);
        }

        /// <summary>
        /// Get Cow count base on farm , state and Date
        /// </summary>
        /// <param name="farm">farm</param>
        /// <param name="state">state like Open, Inseminated, Pregnant, Dry</param>
        /// <param name="onDate">onDate</param>
        /// <returns>int</returns>
        [HttpGet("count")]
        [ProducesResponseType(typeof(int), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<ActionResult<int>> GetCowCountBasedOnDate(string farm, string state, DateTime onDate)
        {
            var countOutcome = await Task.FromResult(_auditDataProvider.GetStateCountPerDate(onDate, state, "Cows", farm));

            if (countOutcome.Successful)
                return Ok(countOutcome.Result);

            return BadRequest(countOutcome.ErrorMessage);
        }

        public override object InsertEvent(AuditEvent auditEvent)
        {
            return auditEvent.ToJson();
        }

Audit.Core.AuditDataProvider : Object

Methods :

public Object Serialize(T value = )
public abstract Object InsertEvent(AuditEvent auditEvent = )
public Void ReplaceEvent(Object eventId = , AuditEvent auditEvent = )
public T GetEvent(Object eventId = )
public Task<Object> InsertEventAsync(AuditEvent auditEvent = )
public Task<T> GetEventAsync(Object eventId = )
public Task ReplaceEventAsync(Object eventId = , AuditEvent auditEvent = )
public AuditEvent GetEvent(Object eventId = )
public Task<AuditEvent> GetEventAsync(Object eventId = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()