protected void Page_Load(object sender, EventArgs e) { try { if (!Page.IsPostBack) { if (!string.IsNullOrEmpty(Request.QueryString["Guid"])) { gudId = Convert.ToString(Request.QueryString["Guid"]); objAuditLog = objCommonBLL.GetAuditLogDetailsByGuid(gudId); if (objAuditLog != null) { if (objAuditLog.IsActive == true) { Response.Redirect(objAuditLog.PageName + "?Guid=" + gudId); } } } } } catch (Exception ex) { log.Error("Page_Load \n Message: " + ex.Message + "\n Source: " + ex.Source + "\n StackTrace: " + ex.StackTrace); ExceptionLog.WriteLog(PageName + " @ Page_Load ", ex.Message + " \n " + ex.StackTrace); } }
/// <summary> /// Method for changing password. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnChangePassword_Click(object sender, EventArgs e) { try { if (!string.IsNullOrEmpty(Request.QueryString["Guid"])) { GudId = Convert.ToString(Request.QueryString["Guid"]); objAuditLog = objCommonBLL.GetAuditLogDetailsByGuid(GudId); if (objAuditLog != null) { if (objAuditLog.IsActive == true) { objUserLogin.UserId = objAuditLog.UserId; objUserLogin.Password = CommonUtils.Encrypt(txtPassword.Text.Trim()); objUserLogin.UpdatedBy = Convert.ToInt32(Session["UserId"]); objUserLogin.UpdatedOn = DateTime.Now; objUserBLL.UpdatePassword(objUserLogin, GudId); Response.Redirect("Login.aspx"); } } } } catch (Exception ex) { log.Error("btnChangePassword_Click \n Message: " + ex.Message + "\n Source: " + ex.Source + "\n StackTrace: " + ex.StackTrace); ExceptionLog.WriteLog(PageName + " @ btnChangePassword_Click ", ex.Message + " \n " + ex.StackTrace); } }
internal RecorderContext(IInvocation invocation, IServiceOperationRecorder recorder) { _invocation = invocation; _recorder = recorder; _auditLog = new AuditLog(ProductInformation.Component, _recorder.Category); _operationName = string.Format("{0}.{1}", _invocation.InvocationTarget.GetType().FullName, _invocation.Method.Name); }
public ActionResult AuditLog() { var bank = BankRepository.GetBank(); var auditLog = new AuditLog(bank); var audits = AuditLogRepository.GetAll(); return View(); }
/// <summary> /// Method for adding audit details /// </summary> /// <param name="objAuditLog"></param> /// <returns></returns> public int AddAuditLog(AuditLog objAuditLog) { int result = 0; try { SqlCommand objSqlCommand = new SqlCommand(); SqlParameter[] objLstParams = new SqlParameter[8]; SqlParameter objUserId = new SqlParameter("@UserId", SqlDbType.Int); objUserId.Value = objAuditLog.UserId; objLstParams[0] = objUserId; SqlParameter objGudId = new SqlParameter("@GudId", SqlDbType.VarChar); objGudId.Value = Convert.ToString(objAuditLog.GudId); objLstParams[1] = objGudId; SqlParameter objCreatedBy = new SqlParameter("@CreatedBy", SqlDbType.Int); objCreatedBy.Value = objAuditLog.CreatedBy; objLstParams[2] = objCreatedBy; SqlParameter objCreatedOn = new SqlParameter("@CreatedOn", SqlDbType.DateTime); objCreatedOn.Value = objAuditLog.CreatedOn; objLstParams[3] = objCreatedOn; SqlParameter objUpdatedBy = new SqlParameter("@UpdatedBy", SqlDbType.Int); objUpdatedBy.Value = objAuditLog.UpdatedBy; objLstParams[4] = objUpdatedBy; SqlParameter objUpdatedOn = new SqlParameter("@UpdatedOn", SqlDbType.DateTime); objUpdatedOn.Value = objAuditLog.UpdatedOn; objLstParams[5] = objUpdatedOn; SqlParameter objPageName = new SqlParameter("@PageName", SqlDbType.VarChar); objPageName.Value = objAuditLog.PageName; objLstParams[6] = objPageName; SqlParameter objIsActive = new SqlParameter("@IsActive", SqlDbType.Bit); objIsActive.Value = objAuditLog.IsActive; objLstParams[7] = objIsActive; result = Convert.ToInt32(SqlHelper.ExecuteScalar(SqlHelper.ConnectionString, CommandType.StoredProcedure, SP_AddAuditLog, objLstParams)); objSqlCommand.Parameters.Clear(); } catch (Exception ex) { log.Error("AddAuditLog \n Message: " + ex.Message + "\n Source: " + ex.Source + "\n StackTrace: " + ex.StackTrace); ExceptionLog.WriteLog(COMMONDATA + " @ AddAuditLog ", ex.Message + " \n " + ex.StackTrace); } return result; }
public ActionResult Deposit(int id, decimal amount) { var bank = BankRepository.GetBank(); var auditLog = new AuditLog(bank); var customer = CustomerRepository.GetCustomerById(id); if (customer == null) throw new NotSupportedException(); var account = AccountRepository.GetAccountByCustomer(customer); if (account == null) throw new NotSupportedException(); account.Deposit(amount); AuditLogRepository.WriteEntries(auditLog); return RedirectToAction("View", "BankAccount", customer.Id); }
public ActionResult Create(string firstName, string lastName, int? ficoScore) { var bank = BankRepository.GetBank(); var auditLog = new AuditLog(bank); if (ficoScore == null) throw new NotSupportedException(); var customer = new Customer(firstName, lastName, ficoScore.Value); var creditPassed = bank.CheckCredit(customer); if (creditPassed) { var newCustomer = CustomerRepository.CreateCustomer(customer); var account = bank.OpenAccount(newCustomer); var newAccount = AccountRepository.CreateAccount(account); return RedirectToAction("View", "BankAccount", newCustomer.Id); } AuditLogRepository.WriteEntries(auditLog); return View(); }
public void WriteLogEntry(IEnumerable<EntityChange> changeSet, AuditLog auditLog) { AuditLogEntry entry = null; try { entry = CreateLogEntry(changeSet); auditLog.WriteEntry(entry.Category, entry.Details); } catch(Exception ex) { // Error saving the audit log repository. Write to log file instead. Platform.Log(LogLevel.Error, ex, "Error occurred when writing audit log"); StringBuilder sb = new StringBuilder(); sb.AppendLine("Audit log entry failed to save:"); if (entry!=null) { sb.AppendLine(String.Format("Operation: {0}", entry.Operation)); sb.AppendLine(String.Format("Details: {0}", entry.Details)); } else { foreach (EntityChange change in changeSet) { sb.AppendLine(String.Format("Changeset: {0} on entity: {1}", change.ChangeType, change.EntityRef)); if (change.PropertyChanges != null) { foreach (PropertyChange property in change.PropertyChanges) { sb.AppendLine(String.Format("{0} : Old Value: {1}\tNew Value: {2}", property.PropertyName, property.OldValue, property.NewValue)); } } } } Platform.Log(LogLevel.Info, sb.ToString()); } }
public void EndLog() { DateTime endTime = DateTime.Now; TimeSpan runTime = endTime - startTime; AuditLog auditLog = new AuditLog(); auditLog.LogTime = DateTime.Now; auditLog.Line = string.Format("Running time - {0}", runTime); _auditLog.Add(auditLog); try { if (line.Equals("Y")) { _logFile.WriteLine("Running time - {0}", runTime); _logFile.Close(); } } catch (Exception e) { _logFile.WriteLine(e); _logFile.Close(); } }
/// <summary> /// A switch was activated. Figure out the context and execute the /// appropriate action. The input manager triggers this event. Every /// switch has an associated action. It could be a command or the switch /// can be used to select highlighted item on a trigger. /// The action is executed depending on the state of the animation player. /// </summary> /// <param name="sender">event sender</param> /// <param name="e">event args</param> private void actuatorManager_EvtSwitchActivated(object sender, ActuatorSwitchEventArgs e) { IActuatorSwitch switchObj = e.SwitchObj; try { if (_player == null || _currentPanel == null) { return; } Log.Debug("switch: " + switchObj.Name); Log.Debug(" Panel: " + _currentPanel.Name); if (_currentPanel.UIControl is System.Windows.Forms.Form) { bool visible = Windows.GetVisible(_currentPanel.UIControl); Log.Debug("Form: " + _currentPanel.UIControl.Name + ", playerState: " + _player.State + ", visible: " + visible); if (!visible) { return; } } // get the action associated with the switch String onTrigger = switchObj.Command; if (String.IsNullOrEmpty(onTrigger)) { Log.Debug("OnTrigger is null. returning"); return; } // execute action if the player is in the right state. if (_player.State != PlayerState.Stopped && _player.State != PlayerState.Unknown && _player.State != PlayerState.Paused && String.Compare(onTrigger, SwitchSetting.TriggerCommand, true) != 0) { runSwitchMappedCommand(switchObj); return; } if (_player.State == PlayerState.Timeout || _player.State == PlayerState.Interrupted) { Log.Debug("Calling player transition for firstanimation"); _player.Transition(_firstAnimation); return; } Log.Debug("Player state is " + _player.State); if (_player.State != PlayerState.Running) { Log.Debug(_currentPanel.Name + ": Player is not Running. Returning"); return; } playBeep(switchObj); AnimationWidget highlightedWidget = _player.HighlightedWidget; Animation currentAnimation = _player.CurrentAnimation; highlightedWidget = _switchDownHighlightedWidget; currentAnimation = _switchDownAnimation; if (highlightedWidget == null) { highlightedWidget = _switchAcceptedHighlightedWidget; currentAnimation = _switchAcceptedAnimation; } if (highlightedWidget == null) { highlightedWidget = _player.HighlightedWidget; currentAnimation = _player.CurrentAnimation; } resetSwitchEventStates(); if (currentAnimation != null && highlightedWidget != null) { setSwitchState(false); var widgetName = (highlightedWidget.UIWidget is IButtonWidget) ? "Button" : highlightedWidget.UIWidget.Name; AuditLog.Audit(new AuditEventUISwitchDetect(switchObj.Name, _currentPanel.Name, highlightedWidget.UIWidget.GetType().Name, widgetName)); Log.Debug(_currentPanel.Name + ": Switch on " + highlightedWidget.UIWidget.Name + " type: " + highlightedWidget.UIWidget.GetType().Name); // check if the widget has a onSelect code fragment. If so execute it. Otherwise // then check if the animation seq that this widget is a part of, has a onSelect. // If it does, execute that. PCode code; SetSelectedWidget(highlightedWidget.UIWidget); if (highlightedWidget.OnSelect.HasCode()) { code = highlightedWidget.OnSelect; _interpreter.Execute(code); } else if (currentAnimation.OnSelect.HasCode()) { code = currentAnimation.OnSelect; _interpreter.Execute(code); } } else { Log.Debug(_currentPanel.Name + ": No current animation or highlighed widget!!"); } } catch (Exception ex) { Log.Debug(ex.ToString()); } finally { setSwitchState(false); } }
/// <summary> /// Insert AuditLog. /// Each entry is read-only. /// </summary> /// <param name="log"></param> public void InsertAuditLog(AuditLog log) { const string sqlInsert = @"INSERT INTO RSCHED_AUDIT_HISTORY([TIME_STAMP] ,[ACTION] ,[FIRE_INSTANCE_ID] ,[JOB_NAME] ,[JOB_GROUP] ,[JOB_TYPE] ,[TRIGGER_NAME] ,[TRIGGER_GROUP] ,[FIRE_TIME_UTC] ,[SCHEDULED_FIRE_TIME_UTC] ,[JOB_RUN_TIME] ,[PARAMS] ,[REFIRE_COUNT] ,[RECOVERING] ,[RESULT] ,[EXECUTION_EXCEPTION]) VALUES ( @timeStamp, @action, @fireInstanceId, @jobName, @jobGroup, @jobType, @triggerName, @triggerGroup, @fireTimeUtc, @scheduledFireTimeUtc, @jobRunTime, @params, @refireCount, @recovering, @result, @executionException);"; using (var con = new SqlConnection(_connectionString)) { try { con.Open(); using (var command = new SqlCommand(sqlInsert, con)) { command.Parameters.AddWithValue("@timeStamp", DateTime.UtcNow); command.Parameters.AddWithValue("@action", log.Action); command.Parameters.AddWithValue("@fireInstanceId", log.FireInstanceId); command.Parameters.AddWithValue("@jobName", log.JobName); command.Parameters.AddWithValue("@jobGroup", log.JobGroup); command.Parameters.AddWithValue("@jobType", log.JobType); command.Parameters.AddWithValue("@triggerName", log.TriggerName); command.Parameters.AddWithValue("@triggerGroup", log.TriggerGroup); command.Parameters.AddWithValue("@fireTimeUtc", log.FireTimeUtc); command.Parameters.AddWithValue("@scheduledFireTimeUtc", log.ScheduledFireTimeUtc); command.Parameters.AddWithValue("@jobRunTime", log.JobRunTime.Ticks); command.Parameters.AddWithValue("@params", log.Params); command.Parameters.AddWithValue("@refireCount", log.RefireCount); command.Parameters.AddWithValue("@recovering", log.Recovering); command.Parameters.AddWithValue("@result", log.Result ?? string.Empty); command.Parameters.AddWithValue("@executionException", log.ExecutionException ?? string.Empty); command.ExecuteScalar(); } } catch (Exception ex) { Logger.ErrorFormat("Error persisting AuditLog. {0}", ex.Message); } } }
/// <summary> /// Writes an audit log entry for the current change-set, assuming the /// <see cref="ChangeSetRecorder"/> property is set and recording is enabled. /// </summary> private void AuditTransaction() { if (_enableChangeSetRecording && _changeSetRecorder != null) { // write to the "ChangeSet" audit log var auditLog = new AuditLog(ProductInformation.Component, "ChangeSet"); _changeSetRecorder.WriteLogEntry(_interceptor.FullChangeSet, auditLog); } }
public async Task <Result <Contract> > Handle(Contract request, CancellationToken cancellationToken) { if (request.UserRole == "Secretary" || request.UserRole == "Recruiter") { return(Result.Fail <Contract>("Acesso Negado")); } ObjectId instructorId = String.IsNullOrEmpty(request.InstructorId) ? ObjectId.Empty : ObjectId.Parse(request.InstructorId); var tutorsIds = request.TutorsIds != null?request.TutorsIds.Select(x => ObjectId.Parse(x)).ToList() : new List <ObjectId>(); var eventResult = Event.Create( request.Title, request.Excerpt, request.ImageUrl, instructorId, request.Instructor, request.InstructorMiniBio, request.InstructorImageUrl, request.Tags, request.VideoUrl, request.VideoDuration, request.Duration, request.CertificateUrl, tutorsIds, request.StoreUrl, request.ForceProblemStatement ); if (eventResult.IsFailure) { return(Result.Fail <Contract>(eventResult.Error)); } var newEvent = eventResult.Data; newEvent.PrepQuizQuestionList = new List <PrepQuizQuestion>(); if (request.PrepQuizQuestionList != null && request.PrepQuizQuestionList.Count > 0) { var questions = request.PrepQuizQuestionList.Select(x => x.Question).ToArray(); for (int i = 0; i < request.PrepQuizQuestionList.Count; i++) { var prepQuizResult = PrepQuizQuestion.Create(request.PrepQuizQuestionList[i].Question, request.PrepQuizQuestionList[i].FileAsAnswer, questions); if (prepQuizResult.IsFailure) { return(Result.Fail <Contract>(prepQuizResult.Error)); } newEvent.PrepQuizQuestionList.Add(prepQuizResult.Data); } } if (string.IsNullOrEmpty(request.Id)) { if (request.UserRole == "Student") { return(Result.Fail <Contract>("Acesso Negado")); } string config = _configuration[$"EcommerceIntegration:Active"]; if (request.CreateInEcommerce.HasValue && request.CreateInEcommerce.Value && config == "True") { var response = await CreateEcommerceProduct(newEvent); string content = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.Created) { var parsed = JObject.Parse(content); newEvent.EcommerceId = (long)parsed["product"]["id"]; } else { var error = ErrorLog.Create( ErrorLogTypeEnum.EcommerceIntegration, "create-track", content ).Data; await _db.ErrorLogCollection.InsertOneAsync( error, cancellationToken : cancellationToken ); } } var newEventList = new List <Event> { newEvent }; await _db.EventCollection.InsertOneAsync( newEvent, cancellationToken : cancellationToken ); var creationLog = AuditLog.Create(ObjectId.Parse(request.UserId), newEvent.Id, newEvent.GetType().ToString(), JsonConvert.SerializeObject(newEventList), EntityAction.Add); await _db.AuditLogCollection.InsertOneAsync(creationLog); request.Id = newEvent.Id.ToString(); request.EcommerceId = newEvent.EcommerceId; } else { var evt = await(await _db .Database .GetCollection <Event>("Events") .FindAsync(x => x.Id == ObjectId.Parse(request.Id), cancellationToken: cancellationToken)) .FirstOrDefaultAsync(cancellationToken: cancellationToken); if (evt == null) { return(Result.Fail <Contract>("Evento não Encontrado")); } if (request.UserRole == "Student") { var userId = ObjectId.Parse(request.UserId); if (!evt.InstructorId.HasValue || evt.InstructorId.Value != userId) { return(Result.Fail <Contract>("Acesso Negado")); } } var oldEventList = JsonConvert.SerializeObject(new List <Event> { newEvent }); evt.Title = newEvent.Title; evt.Excerpt = newEvent.Excerpt; evt.ImageUrl = newEvent.ImageUrl; evt.InstructorId = newEvent.InstructorId; evt.Instructor = newEvent.Instructor; evt.InstructorMiniBio = newEvent.InstructorMiniBio; evt.InstructorImageUrl = newEvent.InstructorImageUrl; evt.Tags = newEvent.Tags; evt.VideoUrl = newEvent.VideoUrl; evt.VideoDuration = newEvent.VideoDuration; evt.Duration = newEvent.Duration; evt.PrepQuiz = newEvent.PrepQuiz; evt.CertificateUrl = newEvent.CertificateUrl; evt.TutorsIds = newEvent.TutorsIds; evt.StoreUrl = newEvent.StoreUrl; evt.EcommerceId = request.EcommerceId; evt.PrepQuizQuestionList = newEvent.PrepQuizQuestionList; evt.ForceProblemStatement = newEvent.ForceProblemStatement; await _db.EventCollection.ReplaceOneAsync(t => t.Id == evt.Id, evt, cancellationToken : cancellationToken ); var newEventList = new List <Event> { evt }; var changeLog = AuditLog.Create(ObjectId.Parse(request.UserId), evt.Id, evt.GetType().ToString(), JsonConvert.SerializeObject(newEventList), EntityAction.Update, oldEventList); await _db.AuditLogCollection.InsertOneAsync(changeLog); if (evt.EcommerceId.HasValue) { string config = _configuration[$"EcommerceIntegration:Active"]; if (config == "True") { await UpdateEcommerceProduct(evt); } } } return(Result.Ok(request)); }
protected virtual void Add(AuditLog auditLog) { AbstractRepository.CurrentSession.Save(auditLog); }
public void Handle(AuditDomainEvent auditDomainEvent) { _efContext.AuditLog.Add(AuditLog.Create(auditDomainEvent.Description)); _efContext.SaveChanges(); }
public int CreateAuditLog(AuditLog audit_log) { IAuditLogBusinessEngine audit_be = _business_engine_factory.GetBusinessEngine <IAuditLogBusinessEngine>(); return(audit_be.AuditLogSave(audit_log)); }
private void AuditChange(ObjectStateEntry entry) { var obj = entry.Entity as IModelObject; if (obj == null) return; var audit = new AuditLog { Action = entry.State.ToString(), Changed = DateTime.Now, ObjectId = obj.Id, User = Thread.CurrentPrincipal.Identity.Name, Collection = entry.EntitySet.Name }; switch (entry.State) { case EntityState.Added: audit.Comment = obj.GetReportHtml(); break; case EntityState.Modified: string report = string.Format("<b>{0}</b><br/>", entry.Entity); foreach (var prop in entry.GetModifiedProperties()) { var displayFormat = entry.Entity.GetType().GetProperty(prop).GetCustomAttribute<DisplayFormatAttribute>(); string format = displayFormat == null ? "{0}" : displayFormat.DataFormatString; report += string.Format( "{0}: {1} => {2}<br/>", prop, string.Format(format, entry.OriginalValues[prop]), string.Format(format, entry.CurrentValues[prop])); } audit.Comment = report; break; case EntityState.Deleted: object original; this.ComparisonContext.TryGetObjectByKey(entry.EntityKey, out original); audit.Comment = ((IModelObject)original).GetReportHtml(); break; default: throw new NotImplementedException("Unhandled state" + entry.State.ToString()); } this.AuditLog.Add(audit); }
public override int SaveChanges() { ObjectContext oc = ((IObjectContextAdapter)this).ObjectContext; var osm = oc.ObjectStateManager; oc.DetectChanges(); Dictionary<string, IModelObject> updatedRelations = new Dictionary<string, IModelObject>(); // Deleted objects - we need to fetch more data before we can report what the change was in readable form. foreach (ObjectStateEntry entry in osm.GetObjectStateEntries(EntityState.Deleted)) { if (entry.IsRelationship) { IModelObject obj1 = oc.GetObjectByKey((EntityKey)entry.OriginalValues[0]) as IModelObject; IModelObject obj2 = oc.GetObjectByKey((EntityKey)entry.OriginalValues[1]) as IModelObject; if (obj1 == null || obj2 == null) { continue; } string key = string.Format("{0}{1}", obj1.Id, obj2.Id); updatedRelations.Add(key, obj1); } else { AuditChange(entry); } } //// Added and modified objects - we can describe the state of the object with //// the information already present. foreach (ObjectStateEntry entry in osm.GetObjectStateEntries( EntityState.Added | EntityState.Modified)) { if (entry.IsRelationship) { var key1 = ((EntityKey)entry.CurrentValues[0]); if (key1.IsTemporary) continue; var key2 = ((EntityKey)entry.CurrentValues[1]); IModelObject obj1 = oc.GetObjectByKey(key1) as IModelObject; IModelObject obj2 = oc.GetObjectByKey(key2) as IModelObject; if (obj1 == null || obj2 == null) { continue; } var audit = new AuditLog { Action = "Modified", Changed = DateTime.Now, User = Thread.CurrentPrincipal.Identity.Name, ObjectId = obj2.Id, Collection = entry.EntitySet.Name, Comment = null }; string key = string.Format("{0}{1}", obj1.Id, obj2.Id); IModelObject original = null; if (updatedRelations.TryGetValue(key, out original)) { audit.Collection = key2.EntitySetName; audit.Comment = string.Format("{0}<br/>{1} => {2}", obj2, original, obj1); this.AuditLog.Add(audit); } } else if (entry.Entity is IModelObject) { IModelObject obj = (IModelObject)entry.Entity; // Keep track of the change for reporting. obj.LastChanged = DateTime.Now; obj.ChangedBy = Thread.CurrentPrincipal.Identity.Name; AuditChange(entry); Document doc = obj as Document; if (doc != null) { SaveDocumentFile(doc); } } } return base.SaveChanges(); }
/// <summary> /// Log an Audit message. /// </summary> /// <param name="helper"></param> public static void LogAuditMessage(DicomAuditHelper helper) { lock (_syncLock) { if (_log == null) _log = new AuditLog(ProductInformation.Component,"DICOM"); string serializeText = null; try { serializeText = helper.Serialize(false); _log.WriteEntry(helper.Operation, serializeText); } catch(Exception ex) { Platform.Log(LogLevel.Error, ex, "Error occurred when writing audit log"); StringBuilder sb = new StringBuilder(); sb.AppendLine("Audit Log failed to save:"); sb.AppendLine(String.Format("Operation: {0}", helper.Operation)); sb.AppendLine(String.Format("Details: {0}", serializeText)); Platform.Log(LogLevel.Info, sb.ToString()); } } }
public void Log(string logMessage) { DateTime logTime = DateTime.Now; //Write to Console System.Console.WriteLine("{0}: {1}", logTime, logMessage); //Write to AuditLog table AuditLog auditLog = new AuditLog(); auditLog.LogTime = logTime; auditLog.Line = logMessage; _auditLog.Add(auditLog); //Write to log file _logFile.WriteLine("{0}: {1}", logTime, logMessage); // Update the underlying file. _logFile.Flush(); }
/// <summary> /// Method for updating user status /// </summary> /// <param name="objAuditLog"></param> /// <param name="GudId"></param> /// <returns></returns> public bool UpdateUserStatus(AuditLog objAuditLog, string gudId) { bool result = false; try { SqlCommand objSqlCommand = new SqlCommand(); SqlParameter[] objLstParams = new SqlParameter[2]; SqlParameter objGudId = new SqlParameter("@GudId", SqlDbType.VarChar); objGudId.Value = Convert.ToString(gudId); objLstParams[0] = objGudId; SqlParameter objUserId = new SqlParameter("@UserId", SqlDbType.Int); objUserId.Value = Convert.ToString(objAuditLog.UserId); objLstParams[1] = objUserId; result = Convert.ToBoolean(SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionString, CommandType.StoredProcedure, SP_UpdateUserStatus, objLstParams)); objSqlCommand.Parameters.Clear(); } catch (Exception ex) { log.Error("UpdateUserStatus \n Message: " + ex.Message + "\n Source: " + ex.Source + "\n StackTrace: " + ex.StackTrace); ExceptionLog.WriteLog(COMMONDATA + " @ UpdateUserStatus ", ex.Message + " \n " + ex.StackTrace); } return result; }
/// <summary> /// Method for updating User status /// </summary> /// <param name="objAuditLog"></param> /// <param name="GudId"></param> /// <returns></returns> public bool UpdateUserStatus(AuditLog objAuditLog, string gudId) { return objUserDAL.UpdateUserStatus(objAuditLog, gudId); }
/// <summary> /// Writes an audit log entry for the specified change set. /// </summary> void IEntityChangeSetRecorder.WriteLogEntry(IEnumerable <EntityChange> changeSet, AuditLog auditLog) { var xml = JsmlSerializer.Serialize(WriteChangeSet(_operationName, changeSet), "ChangeSet"); auditLog.WriteEntry(_operationName, xml); }
/// <summary> /// Writes an audit log entry for the specified change set. /// </summary> void IEntityChangeSetRecorder.WriteLogEntry(IEnumerable<EntityChange> changeSet, AuditLog auditLog) { var xml = JsmlSerializer.Serialize(WriteChangeSet(_operationName, changeSet), "ChangeSet"); auditLog.WriteEntry(_operationName, xml); }
public SoftDeletedLogDetailsAuditor(DbEntityEntry dbEntry, AuditLog log, DbPropertyValues dbEntryDbValues) : base(dbEntry, log, dbEntryDbValues) { }
public async Task <Result> Handle(Contract request, CancellationToken cancellationToken) { if (request.UserRole == "Secretary") { return(Result.Fail("Acesso Negado")); } var moduleId = ObjectId.Parse(request.ModuleId); var module = await _db.ModuleDraftCollection.AsQueryable() .Where(x => ( x.DeletedAt == null || x.DeletedAt == DateTimeOffset.MinValue ) && !x.DraftPublished && ( x.Id == moduleId || x.ModuleId == moduleId ) ) .FirstOrDefaultAsync(cancellationToken: cancellationToken); if (module == null) { var originalModule = await GetModule(request.ModuleId); if (originalModule == null) { return(Result.Fail("Módulo não existe")); } module = await CreateModuleDraft( request, originalModule, cancellationToken ); } var subjectConceptDictionary = new Dictionary <string, List <string> >(); foreach (var subject in module.Subjects) { var subjectConcepts = subject.Concepts.Select(x => x.Name).ToList(); subjectConceptDictionary.Add(subject.Id.ToString(), subjectConcepts); } var questions = new List <QuestionDraft>(); request.File = request.File.Substring(request.File.IndexOf(",", StringComparison.Ordinal) + 1); Byte[] bytes = Convert.FromBase64String(request.File); using (Stream stream = new MemoryStream(bytes)) { using (var xlPackage = new ExcelPackage(stream)) { var baseWorksheet = xlPackage.Workbook.Worksheets[0]; var currentLine = 2; while (baseWorksheet.Cells[currentLine, 1].Value != null) { /* * IDExterno Assunto * ID Nível * Descrição Questão * Tempo médio de Resposta em minutos * Resposta 1 * Valor Resposta 1 * Conceitos certos Resposta 1 * Resposta 2 * Valor Resposta 2 * Conceitos certos Resposta 2 * Resposta 3 * Valor Resposta 3 * Conceitos certos Resposta 3 * Resposta 4 * Valor Resposta 4 * Conceitos certos Resposta 4 * Resposta 5 * Valor Resposta 5 * Conceitos certos Resposta 5 */ var subjectId = baseWorksheet.Cells[currentLine, 1].Value.ToString(); if (!subjectConceptDictionary.ContainsKey(subjectId)) { return(Result.Fail <bool>("Assunto não encontrado")); } var subjectConcepts = subjectConceptDictionary[subjectId]; var quest = new AddOrModifyQuestionCommand.Contract(); if (!int.TryParse(baseWorksheet.Cells[currentLine, 2].Value.ToString(), out int level)) { var availableLevels = Level.GetLevels().Data.Select(x => x.Id.ToString()) .Aggregate((x, y) => x + "," + y); return(Result.Fail <bool>( $"Não foi possível definir o nível de dificuldade da pergunta da linha {currentLine}. Valores possíveis são ({availableLevels})")); } quest.Level = level; quest.Text = baseWorksheet.Cells[currentLine, 3].Value?.ToString(); if (quest.Text == null || quest.Text.Length < 10) { return(Result.Fail <bool>( $"Texto da pergunta da linha {currentLine} não pode ser menor que 10 caracteres")); } var durationStr = baseWorksheet.Cells[currentLine, 4].Value?.ToString(); if (durationStr != null && int.TryParse(durationStr, out int duration)) { quest.Duration = duration; } if (baseWorksheet.Cells[currentLine, 5].Value != null) { var answer1 = this.getAnswerFromWorksheet(baseWorksheet, currentLine, 5, "Resposta 1"); if (answer1.IsFailure) { return(Result.Fail <bool>(answer1.Error)); } quest.Answers.Add(answer1.Data); } if (baseWorksheet.Cells[currentLine, 8].Value != null) { var answer2 = this.getAnswerFromWorksheet(baseWorksheet, currentLine, 8, "Resposta 2"); if (answer2.IsFailure) { return(Result.Fail <bool>(answer2.Error)); } quest.Answers.Add(answer2.Data); } if (baseWorksheet.Cells[currentLine, 11].Value != null) { var answer3 = this.getAnswerFromWorksheet(baseWorksheet, currentLine, 11, "Resposta 3"); if (answer3.IsFailure) { return(Result.Fail <bool>(answer3.Error)); } quest.Answers.Add(answer3.Data); } if (baseWorksheet.Cells[currentLine, 14].Value != null) { var answer4 = this.getAnswerFromWorksheet(baseWorksheet, currentLine, 14, "Resposta 4"); if (answer4.IsFailure) { return(Result.Fail <bool>(answer4.Error)); } quest.Answers.Add(answer4.Data); } if (baseWorksheet.Cells[currentLine, 17].Value != null) { var answer5 = this.getAnswerFromWorksheet(baseWorksheet, currentLine, 17, "Resposta 5"); if (answer5.IsFailure) { return(Result.Fail <bool>(answer5.Error)); } quest.Answers.Add(answer5.Data); } var concepts = quest.Answers.SelectMany(x => x.Concepts).Select(x => x.Concept).Distinct().ToList(); quest.Concepts = concepts.ToArray(); var notContainedConcepts = concepts.Where(x => !subjectConcepts.Contains(x)).ToList(); if (notContainedConcepts.Any()) { return(Result.Fail <bool>($"Os conceitos ({notContainedConcepts.Aggregate((x, y) => x + "," + y)}) das repostas da linha {currentLine} não estão contidos no assunto")); } // Colocando os conceitos errados da pergunta foreach (var answer in quest.Answers) { var answerConcepts = answer.Concepts.Select(x => x.Concept); var notPresentConcepts = concepts.Where(x => !answerConcepts.Contains(x)).Select( x => new AddOrModifyQuestionCommand.ContractAnswerConcept() { Concept = x.Trim(), IsRight = false }); answer.Concepts.AddRange(notPresentConcepts); } var answers = quest.Answers.Select(x => new Answer(x.Description, x.Points, x.Concepts.Select(y => new AnswerConcept(y.Concept, y.IsRight)).ToList())).ToList(); var newObject = QuestionDraft.Create( module.Id, quest.Text, quest.Level, quest.Duration, quest.Concepts, answers, ObjectId.Parse(request.ModuleId), ObjectId.Parse(subjectId) ); if (newObject.IsFailure) { return(Result.Fail <bool>($"Erro na linha {currentLine}: {newObject.Error}")); } questions.Add(newObject.Data); currentLine++; } } } if (!request.AddQuestions) { var baseQuestionDraftCollection = await _db.QuestionDraftCollection .AsQueryable() .Where(x => x.DraftId == module.Id ) .ToListAsync(); await _db.QuestionDraftCollection.DeleteManyAsync(x => x.DraftId == module.Id, cancellationToken : cancellationToken ); var deleteLog = AuditLog.Create(ObjectId.Parse(request.UserId), moduleId, baseQuestionDraftCollection.GetType().ToString(), JsonConvert.SerializeObject(baseQuestionDraftCollection), EntityAction.Delete); await _db.AuditLogCollection.InsertOneAsync(deleteLog); } await _db.QuestionDraftCollection.InsertManyAsync( questions, cancellationToken : cancellationToken ); var creationLog = AuditLog.Create(ObjectId.Parse(request.UserId), moduleId, questions[0].GetType().ToString(), JsonConvert.SerializeObject(questions), EntityAction.Add); await _db.AuditLogCollection.InsertOneAsync(creationLog); return(Result.Ok()); }
private void Start() { Instance = this; transform.Find("Prefabs").gameObject.SetActive(false); twitchGame = GetComponentInChildren <TwitchGame>(true); twitchGame.twitchBombPrefab = GetComponentInChildren <TwitchBomb>(true); twitchGame.twitchModulePrefab = GetComponentInChildren <TwitchModule>(true); twitchGame.moduleCamerasPrefab = GetComponentInChildren <ModuleCameras>(true); TwitchGame.Instance = twitchGame; GameRoom.InitializeSecondaryCamera(); _gameInfo = GetComponent <KMGameInfo>(); _gameInfo.OnStateChange += OnStateChange; CoroutineQueue = GetComponent <CoroutineQueue>(); Leaderboard.Instance.LoadDataFromFile(); LeaderboardController.Install(); ModuleData.LoadDataFromFile(); ModuleData.WriteDataToFile(); AuditLog.SetupLog(); MainThreadQueue.Initialize(); TwitchPlaySettings.LoadDataFromFile(); MusicPlayer.LoadMusic(); IRCConnection.Instance.OnMessageReceived.AddListener(OnMessageReceived); twitchGame.ParentService = this; TwitchPlaysAPI.Setup(); GameObject infoObject = new GameObject("TwitchPlays_Info"); infoObject.transform.parent = gameObject.transform; _publicProperties = infoObject.AddComponent <TwitchPlaysProperties>(); _publicProperties.TwitchPlaysService = this; // TODO: Useless variable? if (TwitchPlaySettings.data.SkipModManagerInstructionScreen || IRCConnection.Instance.State == IRCConnectionState.Connected) { ModManagerManualInstructionScreen.HasShownOnce = true; } UpdateUiHue(); if (TwitchPlaySettings.data.DarkMode) { HeaderBackground.color = new Color32(0x0E, 0x0E, 0x10, 0xFF); HeaderText.color = new Color32(0xEF, 0xEF, 0xEC, 0xFF); MessagesBackground.color = new Color32(0x3A, 0x3A, 0x3D, 0xFF); } else { HeaderBackground.color = new Color32(0xEE, 0xEE, 0xEE, 0xFF); HeaderText.color = new Color32(0x4F, 0x4F, 0x4F, 0xFF); MessagesBackground.color = new Color32(0xD8, 0xD8, 0xD8, 0xFF); } SetupChatSimulator(); // Delete the steam_appid.txt since it was created for a one-time steam boot. // Steam will have initialized before this. if (File.Exists("steam_appid.txt")) { File.Delete("steam_appid.txt"); } }
public async Task <Result <bool> > Handle(Contract request, CancellationToken cancellationToken) { if (request.UserRole == "Student" || request.UserRole == "Secretary" || request.UserRole == "Recruiter") { return(Result.Fail <bool>("Acesso Negado")); } var eId = ObjectId.Parse(request.EventId); var eventDb = await(await _db .Database .GetCollection <Event>("Events") .FindAsync(x => x.Id == eId, cancellationToken: cancellationToken)) .FirstOrDefaultAsync(cancellationToken: cancellationToken); if (eventDb == null) { return(Result.Fail <bool>("Módulo não Encontrado")); } eventDb.DeletedBy = ObjectId.Parse(request.UserId); eventDb.DeletedAt = DateTimeOffset.Now; var tracks = await _db.Database .GetCollection <Track>("Tracks") .AsQueryable() .ToListAsync(); foreach (Track track in tracks) { int removed = track.EventsConfiguration.RemoveAll(x => x.EventId == eventDb.Id ); if (removed > 0) { await _db.TrackCollection.ReplaceOneAsync(t => t.Id == track.Id, track, cancellationToken : cancellationToken ); } } var eventAppCollection = _db.Database.GetCollection <UserEventItem>("EventApplications"); var eventAppQuery = eventAppCollection.AsQueryable(); bool deleteEvent = eventAppQuery.FirstOrDefault(x => x.EventId == eventDb.Id) == null; var oldEventList = new List <Event> { eventDb }; if (deleteEvent) { await _db.EventCollection.DeleteOneAsync(t => t.Id == eventDb.Id, cancellationToken : cancellationToken ); } else { await _db.EventCollection.ReplaceOneAsync(t => t.Id == eventDb.Id, eventDb, cancellationToken : cancellationToken ); } var changeLog = AuditLog.Create(ObjectId.Parse(request.UserId), eventDb.Id, eventDb.GetType().ToString(), "", EntityAction.Delete, JsonConvert.SerializeObject(oldEventList)); await _db.AuditLogCollection.InsertOneAsync(changeLog); return(Result.Ok(true)); }
/// <summary> /// Method for adding audit log. /// </summary> /// <param name="objAuditLog"></param> /// <returns></returns> public int AddAuditLog(AuditLog objAuditLog) { return objCommonDAL.AddAuditLog(objAuditLog); }
public AuditLogGeneratedEventArgs(AuditLog log, object entity, ExpandoObject metadata) { Log = log; Entity = entity; Metadata = metadata; }
public void UpdateAuditLog(AuditLog auditLog) { _db.Entry(auditLog).State = EntityState.Modified; }
private async Task NewAuditLine(string newLine) { AuditLog line = new AuditLog(); await line.WriteToAuditLog(newLine); }
public AccountState Event(AccountCreated occurred) { return(new AccountState(occurred.AccountNumber, LoadSimulation(), AuditLog.Add(new StateLog("AccountCreated", occurred.UniqueGuid(), occurred.OccurredOn())))); }
/// <summary> /// Insert Delivery order details /// </summary> /// <param name="deliveryOrderEntity">Delivery order details entity</param> /// <returns></returns> public Tuple <bool, string> InsertDeliveryOrderEntry(DocumentDeliveryOrderEntity deliveryOrderEntity) { string RowID = string.Empty, SRNo = string.Empty; using (sqlConnection = new SqlConnection(GlobalVariable.ConnectionString)) { DataSet ds = new DataSet(); sqlCommand = new SqlCommand(); try { if (sqlConnection.State == 0) { sqlConnection.Open(); } objTrans = sqlConnection.BeginTransaction(); sqlCommand.Transaction = objTrans; sqlCommand.Connection = sqlConnection; sqlCommand.CommandText = "InsertDeliveryOrderDetails"; sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.AddWithValue("@DoDate", deliveryOrderEntity.DoDate); sqlCommand.Parameters.AddWithValue("@TransactionCode", deliveryOrderEntity.TransactionCode); sqlCommand.Parameters.AddWithValue("@IndentNo", deliveryOrderEntity.IndentNo); sqlCommand.Parameters.AddWithValue("@PermitDate", deliveryOrderEntity.PermitDate); sqlCommand.Parameters.AddWithValue("@OrderPeriod", deliveryOrderEntity.OrderPeriod); sqlCommand.Parameters.AddWithValue("@ReceivorCode", deliveryOrderEntity.ReceivorCode); sqlCommand.Parameters.AddWithValue("@IssuerCode", deliveryOrderEntity.IssuerCode); sqlCommand.Parameters.AddWithValue("@IssuerType", deliveryOrderEntity.IssuerType); sqlCommand.Parameters.AddWithValue("@GrandTotal", deliveryOrderEntity.GrandTotal); sqlCommand.Parameters.AddWithValue("@Regioncode", deliveryOrderEntity.Regioncode); sqlCommand.Parameters.AddWithValue("@Remarks", deliveryOrderEntity.Remarks); sqlCommand.Parameters.AddWithValue("@deliverytype", deliveryOrderEntity.deliverytype); sqlCommand.Parameters.AddWithValue("@ExportFlag", "N"); sqlCommand.Parameters.AddWithValue("@Flag1", "-"); sqlCommand.Parameters.AddWithValue("@Flag2", "-"); sqlCommand.Parameters.AddWithValue("@Dono1", deliveryOrderEntity.Dono); sqlCommand.Parameters.AddWithValue("@RowId1", deliveryOrderEntity.RowId); sqlCommand.Parameters.Add("@Dono", SqlDbType.NVarChar, 10); sqlCommand.Parameters.Add("@RowId", SqlDbType.NVarChar, 30); sqlCommand.Parameters["@Dono"].Direction = ParameterDirection.Output; sqlCommand.Parameters["@RowId"].Direction = ParameterDirection.Output; sqlCommand.ExecuteNonQuery(); RowID = (string)sqlCommand.Parameters["@RowId"].Value; SRNo = (string)sqlCommand.Parameters["@Dono"].Value; deliveryOrderEntity.Dono = SRNo; deliveryOrderEntity.RowId = RowID; //#if (!DEBUG) ManageDocumentDeliveryOrder documentDO = new ManageDocumentDeliveryOrder(); Task.Run(() => documentDO.GenerateDeliveryOrderText(deliveryOrderEntity)); //#else // ManageDocumentDeliveryOrder documentDO = new ManageDocumentDeliveryOrder(); // documentDO.GenerateDeliveryOrderText(deliveryOrderEntity); //#endif //Delete Sr Item Details sqlCommand.Parameters.Clear(); sqlCommand.Dispose(); sqlCommand = new SqlCommand(); sqlCommand.Transaction = objTrans; sqlCommand.Connection = sqlConnection; sqlCommand.CommandText = "DeleteDeliveryOrderDetails"; sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.AddWithValue("@Dono", SRNo); sqlCommand.ExecuteNonQuery(); //Insert data into SR Item details foreach (var item in deliveryOrderEntity.documentDeliveryItems) { sqlCommand.Parameters.Clear(); sqlCommand.Dispose(); sqlCommand = new SqlCommand(); sqlCommand.Transaction = objTrans; sqlCommand.Connection = sqlConnection; sqlCommand.CommandText = "InsertDeliveryItemDetails"; sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.AddWithValue("@Dono", SRNo); sqlCommand.Parameters.AddWithValue("@RowId", RowID); sqlCommand.Parameters.AddWithValue("@Itemcode", item.Itemcode); sqlCommand.Parameters.AddWithValue("@NetWeight", item.NetWeight); sqlCommand.Parameters.AddWithValue("@Wtype", item.Wtype); sqlCommand.Parameters.AddWithValue("@Scheme", item.Scheme); sqlCommand.Parameters.AddWithValue("@Rate", item.Rate); sqlCommand.Parameters.AddWithValue("@Total", item.Total); sqlCommand.Parameters.AddWithValue("@Rcode", item.Rcode); sqlCommand.Parameters.AddWithValue("@ExportFlag", "N"); sqlCommand.Parameters.AddWithValue("Flag1", "-"); sqlCommand.Parameters.AddWithValue("Flag2", "-"); sqlCommand.ExecuteNonQuery(); } //Insert data into SR Item details foreach (var item in deliveryOrderEntity.deliveryPaymentDetails) { sqlCommand.Parameters.Clear(); sqlCommand.Dispose(); sqlCommand = new SqlCommand(); sqlCommand.Transaction = objTrans; sqlCommand.Connection = sqlConnection; sqlCommand.CommandText = "InsertDeliveryPaymentDetails"; sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.AddWithValue("@Dono", SRNo); sqlCommand.Parameters.AddWithValue("@RowId", RowID); sqlCommand.Parameters.AddWithValue("@PaymentMode", item.PaymentMode); sqlCommand.Parameters.AddWithValue("@PaymentAmount", item.PaymentAmount); sqlCommand.Parameters.AddWithValue("@ChequeNo", item.ChequeNo); sqlCommand.Parameters.AddWithValue("@ChDate", item.ChDate); sqlCommand.Parameters.AddWithValue("@bank", item.bank); sqlCommand.Parameters.AddWithValue("@payableat", item.payableat); sqlCommand.Parameters.AddWithValue("@Rcode", item.Rcode); sqlCommand.Parameters.AddWithValue("@ExportFlag", "N"); sqlCommand.Parameters.AddWithValue("Flag1", "-"); sqlCommand.Parameters.AddWithValue("Flag2", "-"); sqlCommand.ExecuteNonQuery(); } //Insert data into SR Item details foreach (var item in deliveryOrderEntity.deliveryMarginDetails) { sqlCommand.Parameters.Clear(); sqlCommand.Dispose(); sqlCommand = new SqlCommand(); sqlCommand.Transaction = objTrans; sqlCommand.Connection = sqlConnection; sqlCommand.CommandText = "InsertDeliveryMarginDetails"; sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.AddWithValue("@Dono", SRNo); sqlCommand.Parameters.AddWithValue("@RowId", RowID); sqlCommand.Parameters.AddWithValue("@SchemeCode", item.SchemeCode); sqlCommand.Parameters.AddWithValue("@ItemCode", item.ItemCode); sqlCommand.Parameters.AddWithValue("@MarginWtype", item.MarginWtype); sqlCommand.Parameters.AddWithValue("@MarginNkgs", item.MarginNkgs); sqlCommand.Parameters.AddWithValue("@MarginRate", item.MarginRate); sqlCommand.Parameters.AddWithValue("@MarginAmount", item.MarginAmount); sqlCommand.Parameters.AddWithValue("@Rcode", item.Rcode); sqlCommand.Parameters.AddWithValue("@ExportFlag", "N"); sqlCommand.Parameters.AddWithValue("Flag1", "-"); sqlCommand.Parameters.AddWithValue("Flag2", "-"); sqlCommand.ExecuteNonQuery(); } ////Insert data into SR Item details foreach (var item in deliveryOrderEntity.deliveryAdjustmentDetails) { sqlCommand.Parameters.Clear(); sqlCommand.Dispose(); sqlCommand = new SqlCommand(); sqlCommand.Transaction = objTrans; sqlCommand.Connection = sqlConnection; sqlCommand.CommandText = "InsertDeliveryAdjustmentDetails"; sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.AddWithValue("@Dono", SRNo); sqlCommand.Parameters.AddWithValue("@RowId", RowID); sqlCommand.Parameters.AddWithValue("@AdjustedDoNo", item.AdjustedDoNo); sqlCommand.Parameters.AddWithValue("@Amount", item.Amount); sqlCommand.Parameters.AddWithValue("@AdjustmentType", item.AdjustmentType); sqlCommand.Parameters.AddWithValue("@AdjustDate", item.AdjustDate); sqlCommand.Parameters.AddWithValue("@AmountNowAdjusted", item.AmountNowAdjusted); sqlCommand.Parameters.AddWithValue("@Balance", item.Balance); sqlCommand.Parameters.AddWithValue("@Rcode", item.Rcode); sqlCommand.Parameters.AddWithValue("@ExportFlag", "N"); sqlCommand.Parameters.AddWithValue("Flag1", "-"); sqlCommand.Parameters.AddWithValue("Flag2", "-"); sqlCommand.ExecuteNonQuery(); } //Insert Data into Sales tax detail table InsertSalesTaxDetails(deliveryOrderEntity, SRNo); sqlCommand.Parameters.Clear(); sqlCommand.Dispose(); objTrans.Commit(); return(new Tuple <bool, string>(true, GlobalVariable.SavedMessage + SRNo)); } catch (Exception ex) { AuditLog.WriteError(ex.Message + " : " + ex.StackTrace); objTrans.Rollback(); return(new Tuple <bool, string>(false, GlobalVariable.ErrorMessage)); } finally { sqlConnection.Close(); sqlCommand.Dispose(); ds.Dispose(); } } }
public void InsertAuditLog(AuditLog model) { _repo.InsertAuditLog(model); }
public void InsertSalesTaxDetails(DocumentDeliveryOrderEntity deliveryOrderEntity, string SRNo) { try { if (deliveryOrderEntity.DOTaxStatus == "YES") { //Get values to calculate the GST value. DataSet ds = new DataSet(); ManageSQLConnection manageSQLConnection = new ManageSQLConnection(); List <KeyValuePair <string, string> > sqlParameters = new List <KeyValuePair <string, string> >(); sqlParameters.Add(new KeyValuePair <string, string>("@EffectDate", deliveryOrderEntity.DoDate)); ds = manageSQLConnection.GetDataSetValues("GetRateMasterData", sqlParameters); ManageReport report = new ManageReport(); if (report.CheckDataAvailable(ds)) { sqlCommand.Parameters.Clear(); sqlCommand.Dispose(); List <RateEntity> _rateEntity = new List <RateEntity>(); _rateEntity = report.ConvertDataTableToList <RateEntity>(ds.Tables[0]); sqlCommand = new SqlCommand(); sqlCommand.Transaction = objTrans; sqlCommand.Connection = sqlConnection; sqlCommand.CommandText = "DeleteDOSalesTaxDetails"; sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.AddWithValue("@BillNo", SRNo); sqlCommand.Parameters.AddWithValue("@GCode", deliveryOrderEntity.IssuerCode); sqlCommand.ExecuteNonQuery(); var creditSales = (deliveryOrderEntity.TransactionCode == "TR019") ? true : false; decimal gst = 0, taxPercent = 0, taxAmnt = 0, rate = 0, amnt = 0; foreach (var item in deliveryOrderEntity.documentDeliveryItems) { //Filter the value based on HSN no and Scheme. var result = (from a in _rateEntity where a.Hsncode == item.HsnCode && a.Scheme == item.Scheme select a).FirstOrDefault(); if (result != null) { item.TaxPercent = Convert.ToString(result.TaxPercentage); rate = result.Rate; } else { item.TaxPercent = "100"; rate = 0; } sqlCommand.Parameters.Clear(); sqlCommand.Dispose(); sqlCommand = new SqlCommand(); sqlCommand.Transaction = objTrans; sqlCommand.Connection = sqlConnection; sqlCommand.CommandText = "InsertIntoGSTSalesTax"; sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.AddWithValue("@BillNo", SRNo); sqlCommand.Parameters.AddWithValue("@BillDate", deliveryOrderEntity.DoDate); sqlCommand.Parameters.AddWithValue("@Month", deliveryOrderEntity.Month); sqlCommand.Parameters.AddWithValue("@Year", deliveryOrderEntity.Year); sqlCommand.Parameters.AddWithValue("@CompanyID", deliveryOrderEntity.PartyID); sqlCommand.Parameters.AddWithValue("@CreditSales", creditSales); sqlCommand.Parameters.AddWithValue("@TaxPercentage", item.TaxPercent); sqlCommand.Parameters.AddWithValue("@Hsncode", item.HsnCode); sqlCommand.Parameters.AddWithValue("@CommodityID", item.Itemcode); sqlCommand.Parameters.AddWithValue("@TaxType", "CGST"); sqlCommand.Parameters.AddWithValue("@Measurement", item.Wtype); sqlCommand.Parameters.AddWithValue("@Quantity", item.NetWeight); taxPercent = (Convert.ToDecimal(item.TaxPercent) / 2); // rate = ((Convert.ToDouble(item.Rate)) - ((Convert.ToDouble(item.Rate) * Convert.ToDouble(item.TaxPercent)) / 100)); sqlCommand.Parameters.AddWithValue("@Rate", rate); amnt = (Convert.ToDecimal(item.NetWeight) * rate); sqlCommand.Parameters.AddWithValue("@Amount", amnt); gst = ((amnt * taxPercent) / 100); sqlCommand.Parameters.AddWithValue("@CGST", gst); sqlCommand.Parameters.AddWithValue("@SGST", gst); taxAmnt = (gst * 2); sqlCommand.Parameters.AddWithValue("@TaxAmount", taxAmnt); sqlCommand.Parameters.AddWithValue("@Total", (amnt + taxAmnt)); sqlCommand.Parameters.AddWithValue("@RCode", item.Rcode); sqlCommand.Parameters.AddWithValue("@GCode", deliveryOrderEntity.IssuerCode); sqlCommand.Parameters.AddWithValue("@CreatedBy", deliveryOrderEntity.UserID); sqlCommand.Parameters.AddWithValue("@Scheme", item.Scheme); sqlCommand.Parameters.AddWithValue("@DORate", item.Rate); sqlCommand.Parameters.AddWithValue("@DOTotal", item.Total); sqlCommand.ExecuteNonQuery(); } } } } catch (Exception ex) { AuditLog.WriteError(ex.Message); } }
public static void Main(String[] args) { // Disallow multiple instances if (FileUtils.IsACATRunning()) { return; } Windows.TurnOffDPIAwareness(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); parseCommandLine(args); var assembly = Assembly.GetExecutingAssembly(); // get appname and copyright information object[] attributes = assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false); var appName = (attributes.Length != 0) ? ((AssemblyTitleAttribute)attributes[0]).Title : String.Empty; var appVersion = string.Format(Resources.Version0, assembly.GetName().Version); //attributes = assembly.GetCustomAttributes(typeof (AssemblyCopyrightAttribute), false); //var appCopyright = (attributes.Length != 0) // ? ((AssemblyCopyrightAttribute) attributes[0]).Copyright // : String.Empty; var appCopyright = Resources.AssemblyCopyright.Replace("\\n", Environment.NewLine); Log.Info("***** " + appName + ". " + appVersion + ". " + appCopyright + " *****"); CoreGlobals.AppGlobalPreferences = GlobalPreferences.Load(FileUtils.GetPreferencesFileFullPath(GlobalPreferences.FileName)); //Set the active user/profile information setUserName(); setProfileName(); //Create user and profile if they don't already exist if (!createUserAndProfile()) { return; } if (!loadUserPreferences()) { return; } Log.SetupListeners(); Splash splash = new Splash(FileUtils.GetImagePath("SplashScreenImage.png"), appName, appVersion, appCopyright, 1000); splash.Show(); Context.PreInit(); Common.PreInit(); Context.AppAgentMgr.EnableAppAgentContextSwitch = false; if (!Context.Init(Context.StartupFlags.Minimal | Context.StartupFlags.TextToSpeech | Context.StartupFlags.WordPrediction | Context.StartupFlags.AgentManager | Context.StartupFlags.WindowsActivityMonitor | Context.StartupFlags.Abbreviations)) { splash.Close(); splash = null; TimedMessageBox.Show(Context.GetInitCompletionStatus()); if (Context.IsInitFatal()) { return; } } AuditLog.Audit(new AuditEvent("Application", "start")); Context.ShowTalkWindowOnStartup = false; Context.AppAgentMgr.EnableContextualMenusForDialogs = false; Context.AppAgentMgr.EnableContextualMenusForMenus = false; Context.AppAgentMgr.DefaultAgentForContextSwitchDisable = Context.AppAgentMgr.NullAgent; if (splash != null) { splash.Close(); } if (!Context.PostInit()) { MessageBox.Show(Context.GetInitCompletionStatus(), "Initialization Error"); return; } Common.Init(); Context.AppWindowPosition = Windows.WindowPosition.CenterScreen; var formName = String.IsNullOrEmpty(_formName) ? "TalkApplicationScanner" : _formName; var form = PanelManager.Instance.CreatePanel(formName); if (form != null) { // Add ad-hoc agent that will handle the form IApplicationAgent agent = new TalkAppAgent(); Context.AppAgentMgr.AddAgent(form.Handle, agent); Context.AppPanelManager.Show(form as IPanel); } else { MessageBox.Show("Invalid form name " + form, "Error"); return; } try { Application.Run(); AuditLog.Audit(new AuditEvent("Application", "stop")); Context.Dispose(); Common.Uninit(); //Utils.Dispose(); Log.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
public async Task <string> AcceptJob(int AbsenceId, string SubstituteId, string AcceptVia) { try { string AcceptJob = await _jobService.AcceptJob(AbsenceId, SubstituteId, AcceptVia); if (AcceptJob == "success") { //Send Notification here AbsenceModel absenceDetail = _absenceService.GetAbsenceDetailByAbsenceId(AbsenceId); IEnumerable <SubzzV2.Core.Entities.User> users = _userService.GetAdminListByAbsenceId(AbsenceId); Message message = new Message(); message.ConfirmationNumber = absenceDetail.ConfirmationNumber; message.AbsenceId = absenceDetail.AbsenceId; message.StartTime = DateTime.ParseExact(Convert.ToString(absenceDetail.StartTime), "HH:mm:ss", CultureInfo.InvariantCulture).ToSubzzTime(); message.EndTime = DateTime.ParseExact(Convert.ToString(absenceDetail.EndTime), "HH:mm:ss", CultureInfo.InvariantCulture).ToSubzzTime(); message.StartDate = Convert.ToDateTime(absenceDetail.StartDate).ToString("D"); message.EndDate = Convert.ToDateTime(absenceDetail.EndDate).ToString("D"); message.StartTimeSMS = DateTime.ParseExact(Convert.ToString(absenceDetail.StartTime), "HH:mm:ss", CultureInfo.InvariantCulture).ToSubzzTimeForSms(); message.EndTimeSMS = DateTime.ParseExact(Convert.ToString(absenceDetail.EndTime), "HH:mm:ss", CultureInfo.InvariantCulture).ToSubzzTimeForSms(); if (message.StartDate == message.EndDate) { message.DateToDisplayInSMS = Convert.ToDateTime(absenceDetail.StartDate).ToSubzzDateForSMS(); } else { message.DateToDisplayInSMS = Convert.ToDateTime(absenceDetail.StartDate).ToSubzzShortDateForSMS() + "-" + Convert.ToDateTime(absenceDetail.EndDate).ToSubzzDateForSMS(); } if (!string.IsNullOrEmpty(absenceDetail.OrganizationPhoneNumber) && absenceDetail.OrganizationPhoneNumber.Length > 5) { message.FromPhoneNumber = absenceDetail.OrganizationPhoneNumber; } else { message.FromPhoneNumber = absenceDetail.DistrictPhoneNumber; } message.EmployeeName = absenceDetail.EmployeeName; message.Position = absenceDetail.PositionDescription; message.Subject = absenceDetail.SubjectDescription; message.Grade = absenceDetail.Grade; message.Location = absenceDetail.AbsenceLocation; message.School = absenceDetail.OrganizationName; message.Notes = absenceDetail.SubstituteNotes; message.SubstituteName = absenceDetail.SubstituteName; message.Reason = absenceDetail.AbsenceReasonDescription; message.Photo = absenceDetail.SubstituteProfilePicUrl; message.AttachedFileName = absenceDetail.AttachedFileName; message.FileContentType = absenceDetail.FileContentType; message.Duration = absenceDetail.DurationType == 1 ? "Full Day" : absenceDetail.DurationType == 2 ? "First Half" : absenceDetail.DurationType == 3 ? "Second Half" : "Custom"; //Notification notification = new Notification(); Task.Run(() => SendJobAcceptEmails(users, message, absenceDetail)); // Audit Log var audit = new AuditLog { UserId = CurrentUser.Id, EntityId = absenceDetail.ConfirmationNumber.ToString(), EntityType = AuditLogs.EntityType.Absence, ActionType = AuditLogs.ActionType.Accepted, DistrictId = CurrentUser.DistrictId, OrganizationId = CurrentUser.OrganizationId == "-1" ? null : CurrentUser.OrganizationId }; _audit.InsertAuditLog(audit); } return(AcceptJob); } catch (Exception ex) { } return(null); }
public async Task <JsonResult> OnGetDataAuditTrail() { dynamic result = new ExpandoObject(); List <dynamic> DS = new List <dynamic>(); List <dynamic> secondaryDS = new List <dynamic>(); List <dynamic> tertiaryDS = new List <dynamic>(); var departmentLogs = AuditLogsRepo.WithDetails().Where(x => x.Url == HttpContext.Request.Path.Value && x.EntityChanges != null && x.EntityChanges.Count > 0).ToList(); List <PS_PayComponentType_Dto> Entities = await PS_PayComponentTypeAppService.GetAllPayComponentTypesAsync(); TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; for (int i = 0; i < departmentLogs.Count; i++) { AuditLog auditLog = departmentLogs[i]; if (auditLog.EntityChanges == null || auditLog.EntityChanges.Count == 0) { continue; } var entityChanges = auditLog.EntityChanges.ToList(); for (int j = 0; j < entityChanges.Count; j++) { EntityChange entityChange = entityChanges[j]; dynamic changeRow = new ExpandoObject(); changeRow.AuditLogId = entityChange.Id; changeRow.EntityChangeId = entityChange.Id; PS_PayComponentType_Dto department = Entities.First(x => x.Id.ToString() == entityChange.EntityId); changeRow.Id = department.Id; changeRow.Name = department.Name; changeRow.Date = entityChange.ChangeTime.ToShortDateString(); changeRow.Time = entityChange.ChangeTime.ToShortTimeString(); changeRow.User = auditLog.UserName; changeRow.Status = entityChange.ChangeType.GetDisplayName(); DS.Add(changeRow); dynamic generalTypeRow = new ExpandoObject(); generalTypeRow.EntityChangeId = entityChange.Id; generalTypeRow.TypeId = 1; generalTypeRow.Type = "General"; generalTypeRow.Name = ""; generalTypeRow.Status = "Updated"; changeRow.Type = "General"; //changeRow.Name = ""; changeRow.ChangeStatus = "Updated"; secondaryDS.Add(generalTypeRow); var generalPropertyChanges = entityChange.PropertyChanges.ToList(); for (int k = 0; k < generalPropertyChanges.Count; k++) { EntityPropertyChange propertyChange = generalPropertyChanges[k]; dynamic propertyChangeRow = new ExpandoObject(); propertyChangeRow.TypeId = 1; propertyChangeRow.EntityChangeId = propertyChange.EntityChangeId; propertyChangeRow.Field = textInfo.ToTitleCase(propertyChange.PropertyName.ToSentenceCase()); propertyChangeRow.NewValue = propertyChange.NewValue != "null" && propertyChange.NewValue != "\"\"" ? propertyChange.NewValue.TrimStart('"').TrimEnd('"') : "—"; propertyChangeRow.OriginalValue = propertyChange.OriginalValue != "null" && propertyChange.OriginalValue != "\"\"" ? propertyChange.OriginalValue.TrimStart('"').TrimEnd('"') : "—";; changeRow.Field = textInfo.ToTitleCase(propertyChange.PropertyName.ToSentenceCase()); changeRow.NewValue = propertyChange.NewValue != "null" && propertyChange.NewValue != "\"\"" ? propertyChange.NewValue.TrimStart('"').TrimEnd('"') : "—"; changeRow.OriginalValue = propertyChange.OriginalValue != "null" && propertyChange.OriginalValue != "\"\"" ? propertyChange.OriginalValue.TrimStart('"').TrimEnd('"') : "—";; tertiaryDS.Add(propertyChangeRow); } //List<EmployeeExtraPropertyHistory> extraPropertyHistories = entityChange.GetProperty<List<EmployeeExtraPropertyHistory>>("extraPropertiesHistory"); //if (extraPropertyHistories != null && extraPropertyHistories.Count > 0) //{ // foreach (EmployeeExtraPropertyHistory extraPropertyHistory in extraPropertyHistories) // { // dynamic typeRow = new ExpandoObject(); // typeRow.EntityChangeId = entityChange.Id; // typeRow.TypeId = extraPropertyHistory.TypeId; // typeRow.Type = extraPropertyHistory.Type; // typeRow.Name = extraPropertyHistory.Name; // typeRow.Status = extraPropertyHistory.Status; // secondaryDS.Add(typeRow); // var propertyChanges = extraPropertyHistory.PropertyChanges.ToList(); // for (int k = 0; k < propertyChanges.Count; k++) // { // EmployeeTypePropertyChange propertyChange = propertyChanges[k]; // dynamic propertyChangeRow = new ExpandoObject(); // propertyChangeRow.TypeId = extraPropertyHistory.TypeId; // propertyChangeRow.EntityChangeId = typeRow.EntityChangeId; // propertyChangeRow.Field = textInfo.ToTitleCase(propertyChange.PropertyName.ToSentenceCase()); // propertyChangeRow.NewValue = propertyChange.NewValue != "null" && propertyChange.NewValue != "\"\"" ? propertyChange.NewValue.TrimStart('"').TrimEnd('"') : "—"; // propertyChangeRow.OriginalValue = propertyChange.OriginalValue != "null" && propertyChange.OriginalValue != "\"\"" ? propertyChange.OriginalValue.TrimStart('"').TrimEnd('"') : "—"; ; // tertiaryDS.Add(propertyChangeRow); // } // } //} } } result.ds = DS; result.secondaryDS = secondaryDS; result.tertiaryDS = tertiaryDS; var secondaryGrid = new JsonResult(result); return(secondaryGrid); }
public UnDeletedLogDetailsAudotor(EntityEntry dbEntry, AuditLog log) : base(dbEntry, log) { }
public virtual Task <AuditLog> ConvertAsync(AuditLogInfo auditLogInfo) { var auditLogId = GuidGenerator.Create(); var extraProperties = new ExtraPropertyDictionary(); if (auditLogInfo.ExtraProperties != null) { foreach (var pair in auditLogInfo.ExtraProperties) { extraProperties.Add(pair.Key, pair.Value); } } var entityChanges = auditLogInfo .EntityChanges? .Select(entityChangeInfo => new EntityChange(GuidGenerator, auditLogId, entityChangeInfo, tenantId: auditLogInfo.TenantId)) .ToList() ?? new List <EntityChange>(); var actions = auditLogInfo .Actions? .Select(auditLogActionInfo => new AuditLogAction(GuidGenerator.Create(), auditLogId, auditLogActionInfo, tenantId: auditLogInfo.TenantId)) .ToList() ?? new List <AuditLogAction>(); var remoteServiceErrorInfos = auditLogInfo.Exceptions?.Select(exception => ExceptionToErrorInfoConverter.Convert(exception, options => { options.SendExceptionsDetailsToClients = ExceptionHandlingOptions.SendExceptionsDetailsToClients; options.SendStackTraceToClients = ExceptionHandlingOptions.SendStackTraceToClients; })) ?? new List <RemoteServiceErrorInfo>(); var exceptions = remoteServiceErrorInfos.Any() ? JsonSerializer.Serialize(remoteServiceErrorInfos, indented: true) : null; var comments = auditLogInfo .Comments? .JoinAsString(Environment.NewLine); var auditLog = new AuditLog( auditLogId, auditLogInfo.ApplicationName, auditLogInfo.TenantId, auditLogInfo.TenantName, auditLogInfo.UserId, auditLogInfo.UserName, auditLogInfo.ExecutionTime, auditLogInfo.ExecutionDuration, auditLogInfo.ClientIpAddress, auditLogInfo.ClientName, auditLogInfo.ClientId, auditLogInfo.CorrelationId, auditLogInfo.BrowserInfo, auditLogInfo.HttpMethod, auditLogInfo.Url, auditLogInfo.HttpStatusCode, auditLogInfo.ImpersonatorUserId, auditLogInfo.ImpersonatorUserName, auditLogInfo.ImpersonatorTenantId, auditLogInfo.ImpersonatorTenantName, extraProperties, entityChanges, actions, exceptions, comments ); return(Task.FromResult(auditLog)); }
public bool writeEventLog(AuditLog AL) { DataStore.writeEventLog(AL); return true; }
public DataTable ManageDORegister(DataSet ds) { try { if (ds.Tables.Count > 1) { DataTable ndt = ds.Tables[0].Clone(); var dataTableForDO = ds.Tables[0].DefaultView.ToTable(true, "Dono"); foreach (DataRow item in dataTableForDO.Rows) { DataRow[] dataRowForDODET = ds.Tables[0].Select("Dono='" + Convert.ToString(item["Dono"]) + "'"); DataRow[] dataRowForPayment = ds.Tables[1].Select("Dono='" + Convert.ToString(item["Dono"]) + "'"); int detCount = dataRowForDODET.Count(); int payCount = dataRowForPayment.Count(); if (payCount == 0) { foreach (DataRow dr in dataRowForDODET) { ndt.ImportRow(dr); ndt.AcceptChanges(); } } else if (detCount >= payCount) { int i = 0; foreach (DataRow dr in dataRowForDODET) { if (i < payCount) { dr["Cheque_DD"] = Convert.ToString(dataRowForPayment[i]["Cheque_DD"]); dr["PaymentAmount"] = Convert.ToString(dataRowForPayment[i]["PaymentAmount"]); ndt.ImportRow(dr); } else { ndt.ImportRow(dr); } ndt.AcceptChanges(); i++; } } else if (payCount > detCount) { int i = 0; foreach (DataRow dr in dataRowForDODET) { if (i < payCount) { dr["Cheque_DD"] = Convert.ToString(dataRowForPayment[i]["Cheque_DD"]); dr["PaymentAmount"] = Convert.ToString(dataRowForPayment[i]["PaymentAmount"]); ndt.ImportRow(dr); } else { ndt.ImportRow(dr); } ndt.AcceptChanges(); i++; } // i = i - 1; if (payCount > i) { try { for (int j = i; j >= payCount - i; j++) { DataRow dataRow = dataRowForDODET[0]; dataRow["Totals"] = "0"; dataRow["Scheme"] = ""; dataRow["Commodity"] = ""; dataRow["Netwt_Kgs"] = "0"; dataRow["Rate_Rs"] = "0"; dataRow["Itemamount"] = "0"; dataRow["PreviousAmount"] = "0"; dataRow["Adjusted"] = "0"; dataRow["Balance"] = "0"; dataRow["MarginAmount"] = "0"; dataRow["Cheque_DD"] = Convert.ToString(dataRowForPayment[j]["Cheque_DD"]); dataRow["PaymentAmount"] = Convert.ToString(dataRowForPayment[j]["PaymentAmount"]); ndt.ImportRow(dataRow); ndt.AcceptChanges(); } } catch (Exception ex) { AuditLog.WriteError("PayCount is more than Itemcount : " + ex.Message + " " + ex.StackTrace); } } //Totals,Scheme,Commodity,Netwt_Kgs,Rate_Rs,Itemamount,PreviousAmount,Adjusted,Balance,MarginAmount } } return(ndt); } return(ds.Tables[0]); } catch (Exception ex) { AuditLog.WriteError(" ManageDORegister : " + ex.Message + " " + ex.StackTrace); } return(null); }
public bool emailLog(AuditLog AL, EmailLog EL) { DataStore.writeEmailLog( EL, AL); return true; }
private bool AttemptInvokeCommand <TObj>(StaticCommand command, IRCMessage msg, string cmdStr, Match m, TObj extraObject) { if (command.HasAttribute <DebuggingOnlyAttribute>() && !TwitchPlaySettings.data.EnableDebuggingCommands) { return(false); } if (command.HasAttribute <ElevatorOnlyAttribute>() && !(GameRoom.Instance is ElevatorGameRoom)) { return(false); } if (command.HasAttribute <ElevatorDisallowedAttribute>() && GameRoom.Instance is ElevatorGameRoom) { return(false); } if (!UserAccess.HasAccess(msg.UserNickName, TwitchPlaySettings.data.AnarchyMode ? command.Attr.AccessLevelAnarchy : command.Attr.AccessLevel, orHigher: true)) { IRCConnection.SendMessageFormat("@{0}, you need {1} access to use that command{2}.", msg.UserNickName, UserAccess.LevelToString(TwitchPlaySettings.data.AnarchyMode ? command.Attr.AccessLevelAnarchy : command.Attr.AccessLevel), TwitchPlaySettings.data.AnarchyMode ? " in anarchy mode" : ""); // Return true so that the command counts as processed return(true); } if (extraObject is TwitchModule mdl) { if (mdl.Solved && !command.HasAttribute <SolvedAllowedAttribute>() && !TwitchPlaySettings.data.AnarchyMode) { IRCConnection.SendMessageFormat(TwitchPlaySettings.data.AlreadySolved, mdl.Code, mdl.PlayerName, msg.UserNickName, mdl.BombComponent.GetModuleDisplayName()); // Return true so that the command counts as processed (otherwise you get the above message multiple times) return(true); } if (mdl.Hidden) { IRCConnection.SendMessage($"Module {mdl.Code} is currently hidden and cannot be interacted with."); return(true); } } // Check if commands are allowed to be sent to a holdable as they could be disabled in the settings. if (extraObject is TwitchHoldable holdable && !UserAccess.HasAccess(msg.UserNickName, AccessLevel.SuperUser, true) && ( (!TwitchPlaySettings.data.EnableMissionBinder && holdable.CommandType == typeof(MissionBinderCommands)) || (!TwitchPlaySettings.data.EnableFreeplayBriefcase && holdable.CommandType == typeof(FreeplayCommands)) ) ) { IRCConnection.SendMessage("That holdable is currently disabled and you cannot be interact with it."); return(true); } Leaderboard.Instance.GetRank(msg.UserNickName, out Leaderboard.LeaderboardEntry entry); if (entry?.Team == null && extraObject is TwitchModule && OtherModes.VSModeOn) { if (TwitchPlaySettings.data.AutoSetVSModeTeams) { if (TwitchPlaySettings.data.VSModePlayerLockout) { IRCConnection.SendMessage($@"{msg.UserNickName}, you have not joined a team, and the bomb has already started. Use !join to play the next bomb."); } else { IRCConnection.SendMessage($@"{msg.UserNickName}, you have not joined a team, and cannot solve modules in this mode until you do, please use !join to be assigned a team."); } } else { IRCConnection.SendMessage($@"{msg.UserNickName}, you have not joined a team, and cannot solve modules in this mode until you do, please use !join evil or !join good."); } // Return true so that the command counts as processed (otherwise you get the above message multiple times) return(true); } if (!TwitchGame.IsAuthorizedDefuser(msg.UserNickName, msg.IsWhisper)) { return(true); } BanData ban = UserAccess.IsBanned(msg.UserNickName); if (ban != null) { if (double.IsPositiveInfinity(ban.BanExpiry)) { IRCConnection.SendMessage($"Sorry @{msg.UserNickName}, You were restricted from using commands. You can request permission to send commands again by talking to the staff.", msg.UserNickName, !msg.IsWhisper); } else { int secondsRemaining = (int)(ban.BanExpiry - DateTime.Now.TotalSeconds()); int daysRemaining = secondsRemaining / 86400; secondsRemaining %= 86400; int hoursRemaining = secondsRemaining / 3600; secondsRemaining %= 3600; int minutesRemaining = secondsRemaining / 60; secondsRemaining %= 60; string timeRemaining = $"{secondsRemaining} seconds."; if (daysRemaining > 0) { timeRemaining = $"{daysRemaining} days, {hoursRemaining} hours, {minutesRemaining} minutes, {secondsRemaining} seconds."; } else if (hoursRemaining > 0) { timeRemaining = $"{hoursRemaining} hours, {minutesRemaining} minutes, {secondsRemaining} seconds."; } else if (minutesRemaining > 0) { timeRemaining = $"{minutesRemaining} minutes, {secondsRemaining} seconds."; } IRCConnection.SendMessage($"Sorry @{msg.UserNickName}, You were temporarily restricted from using commands. You can participate again in {timeRemaining} or request permission by talking to the staff.", msg.UserNickName, !msg.IsWhisper); } return(true); } var parameters = command.Method.GetParameters(); var groupAttrs = parameters.Select(p => (GroupAttribute)p.GetCustomAttributes(typeof(GroupAttribute), false).FirstOrDefault()).ToArray(); var arguments = new object[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { // Capturing groups from the regular expression if (groupAttrs[i] != null && m != null) { var group = m.Groups[groupAttrs[i].GroupIndex]; NumberParseResult result; // Helper function to parse numbers (ints, floats, doubles) NumberParseResult IsNumber <TNum>(TryParse <TNum> tryParse) { var isNullable = parameters[i].ParameterType == typeof(Nullable <>).MakeGenericType(typeof(TNum)); if (parameters[i].ParameterType != typeof(TNum) && !isNullable) { return(NumberParseResult.NotOfDesiredType); } if (group.Success && tryParse(group.Value, out TNum rslt)) { arguments[i] = rslt; return(NumberParseResult.Success); } if (isNullable) { return(NumberParseResult.Success); } IRCConnection.SendMessage(group.Success ? "@{0}, “{1}” is not a valid number." : "@{0}, the command could not be parsed.", msg.UserNickName, !msg.IsWhisper, msg.UserNickName, group.Success ? group.Value : null); return(NumberParseResult.Error); } // Strings if (parameters[i].ParameterType == typeof(string)) { arguments[i] = m.Success ? group.Value : null; } // Booleans — only specifies whether the group matched or not else if (parameters[i].ParameterType == typeof(bool)) { arguments[i] = group.Success; } // Numbers (int, float, double); includes nullables else if ( (result = IsNumber <int>(int.TryParse)) != NumberParseResult.NotOfDesiredType || (result = IsNumber <float>(float.TryParse)) != NumberParseResult.NotOfDesiredType || (result = IsNumber <double>(double.TryParse)) != NumberParseResult.NotOfDesiredType) { if (result == NumberParseResult.Error) { return(true); } } } // Built-in parameter names else if (parameters[i].ParameterType == typeof(string) && parameters[i].Name == "user") { arguments[i] = msg.UserNickName; } else if (parameters[i].ParameterType == typeof(string) && parameters[i].Name == "cmd") { arguments[i] = cmdStr; } else if (parameters[i].ParameterType == typeof(bool) && parameters[i].Name == "isWhisper") { arguments[i] = msg.IsWhisper; } else if (parameters[i].ParameterType == typeof(IRCMessage)) { arguments[i] = msg; } else if (parameters[i].ParameterType == typeof(KMGameInfo)) { arguments[i] = GetComponent <KMGameInfo>(); } else if (parameters[i].ParameterType == typeof(KMGameInfo.State)) { arguments[i] = CurrentState; } else if (parameters[i].ParameterType == typeof(FloatingHoldable) && extraObject is TwitchHoldable twitchHoldable) { arguments[i] = twitchHoldable.Holdable; } // Object we passed in (module, bomb, holdable) else if (parameters[i].ParameterType.IsAssignableFrom(typeof(TObj))) { arguments[i] = extraObject; } else if (parameters[i].IsOptional) { arguments[i] = parameters[i].DefaultValue; } else { IRCConnection.SendMessage("@{0}, this is a bug; please notify the devs. Error: the “{1}” command has an unrecognized parameter “{2}”. It expects a type of “{3}”, and the extraObject is of type “{4}”.", msg.UserNickName, !msg.IsWhisper, msg.UserNickName, command.Method.Name, parameters[i].Name, parameters[i].ParameterType.Name, extraObject?.GetType().Name); return(true); } } var invokeResult = command.Method.Invoke(null, arguments); if (invokeResult is bool invRes) { return(invRes); } else if (invokeResult is IEnumerator coroutine) { ProcessCommandCoroutine(coroutine, extraObject); } else if (invokeResult != null) { IRCConnection.SendMessage("@{0}, this is a bug; please notify the devs. Error: the “{1}” command returned something unrecognized.", msg.UserNickName, !msg.IsWhisper, msg.UserNickName, command.Method.Name); } if ((TwitchPlaySettings.data.AnarchyMode ? command.Attr.AccessLevelAnarchy : command.Attr.AccessLevel) > AccessLevel.Defuser) { AuditLog.Log(msg.UserNickName, UserAccess.HighestAccessLevel(msg.UserNickName), msg.Text); } return(true); }
public static void writeEventLog(AuditLog AL) { using (POCDBContext context = new POCDBContext()) { context.spInsertTransLog(AL.userid, AL.eventtypeid, AL.source, AL.logmessage); } }
/// <summary> /// Creates the a talk window form and show it. Restores talk window /// contents if configuredto do so. Raises an event indicating the /// talk window was created. Window creation is done in a separate /// thread with its own message loop /// </summary> private void createAndShowTalkWindow() { var viewerThread = new Thread(delegate() { if (!_inTalkWindowCreationThread) { _inTalkWindowCreationThread = true; IsTalkWindowActive = true; // Create our context, and install it: SynchronizationContext.SetSynchronizationContext( new System.Windows.Threading.DispatcherSynchronizationContext( System.Windows.Threading.Dispatcher.CurrentDispatcher)); CreateTalkWindow(); showGlass(); //notifyTalkWindowPreVisibilityChanged(true); Windows.SetTopMost(_talkWindowForm); Form form = null; if (PanelManagement.PanelManager.Instance.GetCurrentForm() != null) { form = PanelManagement.PanelManager.Instance.GetCurrentForm() as Form; } if (form != null) { SetTalkWindowPosition(PanelManagement.PanelManager.Instance.GetCurrentForm() as Form); } Windows.ShowForm(_talkWindowForm); Windows.ActivateForm(_talkWindowForm); AuditLog.Audit(new AuditEventTalkWindow("show")); if (CoreGlobals.AppPreferences.RetainTalkWindowContentsOnHide) { _talkWindow.TalkWindowText = _talkWindowText; } if (EvtTalkWindowCreated != null) { EvtTalkWindowCreated(this, new TalkWindowCreatedEventArgs(_talkWindowForm)); } System.Windows.Threading.Dispatcher.Run(); Log.Debug("Exited DISPATCHER.RUN"); _inTalkWindowCreationThread = false; } }); viewerThread.SetApartmentState(ApartmentState.STA); Log.Debug("Starting thread, _inTalkWindowCreationThread is : " + _inTalkWindowCreationThread); viewerThread.Start(); }
public void AddAuditLog(AuditLog auditLog) { _db.AuditLogs.Add(auditLog); _db.SaveChanges(); }
/// <summary> /// Log an Audit message. /// </summary> /// <param name="helper"></param> public static void LogAuditMessage(DicomAuditHelper helper) { // Found doing this on the local thread had a performance impact with some DICOM operations, // make run as a task in the background to make it work faster. Task.Factory.StartNew(delegate { lock (_syncLock) { if (_log == null) _log = new AuditLog(ProductInformation.Component, "DICOM"); string serializeText = null; try { serializeText = helper.Serialize(false); _log.WriteEntry(helper.Operation, serializeText, GetUserName(), GetUserSessionId()); } catch (Exception ex) { Platform.Log(LogLevel.Error, ex, "Error occurred when writing audit log"); var sb = new StringBuilder(); sb.AppendLine("Audit Log failed to save:"); sb.AppendLine(String.Format("Operation: {0}", helper.Operation)); sb.AppendLine(String.Format("Details: {0}", serializeText)); Platform.Log(LogLevel.Info, sb.ToString()); } } }); }
/// <summary> /// /// </summary> /// <param name="auditLog"></param> public void DeleteAuditLog(AuditLog auditLog) { _db.AuditLogs.Remove(auditLog); _db.SaveChanges(); }
private static void getActiveWindow(bool flag = false) { AutomationElement focusedElement = null; try { IntPtr foregroundWindow = Windows.GetForegroundWindow(); var title = Windows.GetWindowTitle(foregroundWindow); Log.Debug("fgHwnd = " + ((foregroundWindow != IntPtr.Zero) ? foregroundWindow.ToString() : "null") + ", title: " + title); if (Windows.GetOSVersion() == Windows.WindowsVersion.Win10 && title.StartsWith("Jump List for")) { return; } focusedElement = AutomationElement.FocusedElement; Log.Debug("focusedElement is " + ((focusedElement != null) ? "not null" : "null")); Log.Debug("_currentfocusedElement is " + ((_currentFocusedElement != null) ? "not null" : "null")); bool elementChanged = true; var process = GetProcessForWindow(foregroundWindow); // check if anything changed. did the window focus change? // did focus change within the window? if (focusedElement != null && (_forceGetActiveWindow || flag || foregroundWindow != _currentHwnd || _currentFocusedElement == null || (elementChanged = IsDifferent(focusedElement, _currentFocusedElement)))) { //Log.Debug("Reason: _forceGetActiveWindow: " + _forceGetActiveWindow); //Log.Debug("Reason: flag: " + flag); //Log.Debug("Reason: fgHwnd != _currentHwnd : " + (fgHwnd != _currentHwnd)); //Log.Debug("Reason: _currentFocusedElement == null : " + (_currentFocusedElement == null)); //Log.Debug("Reason: elementChanged : " + elementChanged); if (_forceGetActiveWindow) { _forceGetActiveWindow = false; } if (EvtFocusChanged != null) { var monitorInfo = new WindowActivityMonitorInfo { FgHwnd = foregroundWindow, Title = title, FgProcess = process, FocusedElement = focusedElement, IsNewWindow = _currentHwnd != foregroundWindow }; if (flag) { monitorInfo.IsNewWindow = true; } if (monitorInfo.IsNewWindow || _currentFocusedElement == null || elementChanged) { monitorInfo.IsNewFocusedElement = true; } #if VERBOSE Log.Debug("#$#>>>>>>>>>>>>>>>> Triggering FOCUS changed event"); Log.Debug("#$# title: " + title); Log.Debug("#$# fgHwnd " + monitorInfo.FgHwnd); Log.Debug("#$# nativewinhandle: " + focusedElement.Current.NativeWindowHandle); Log.Debug("#$# Process: " + process.ProcessName); Log.Debug("#$# class: " + focusedElement.Current.ClassName); Log.Debug("#$# controltype: " + focusedElement.Current.ControlType.ProgrammaticName); Log.Debug("#$# automationid: " + focusedElement.Current.AutomationId); Log.Debug("#$# newWindow: " + monitorInfo.IsNewWindow); Log.Debug("#$# newFocusElement: " + monitorInfo.IsNewFocusedElement); Log.Debug("#$# IsMinimized : " + Windows.IsMinimized(monitorInfo.FgHwnd)); #endif if (monitorInfo.IsNewWindow) { AuditLog.Audit(new AuditEventActiveWindowChange(process.ProcessName, title)); } if (EvtFocusChanged != null) { EvtFocusChanged(monitorInfo); } _currentFocusedElement = focusedElement; } else { Log.Debug("EvtFocusChanged is null"); } } _currentHwnd = foregroundWindow; // raise the heartbeat event if (EvtWindowMonitorHeartbeat != null && focusedElement != null && _heartbeatToggle) { var monitorInfo = new WindowActivityMonitorInfo { FgHwnd = foregroundWindow, FocusedElement = focusedElement, Title = title, FgProcess = process }; EvtWindowMonitorHeartbeat(monitorInfo); } _heartbeatToggle = !_heartbeatToggle; } catch (Exception e) { Log.Debug("exception: " + e); _currentFocusedElement = null; } }
/// <summary> /// Method for Getting audit log details /// </summary> /// <param name="GudId"></param> /// <returns></returns> public AuditLog GetAuditLogDetailsByGuid(string gudId) { AuditLog objAuditLog = new AuditLog(); try { SqlParameter objGudId = new SqlParameter("@GudId", SqlDbType.VarChar); objGudId.Value = gudId; using (DataSet AuditLogTable = SqlHelper.ExecuteDataset(SqlHelper.ConnectionString, CommandType.StoredProcedure, SP_GetAuditLogDetailsByGuid, objGudId)) { if (AuditLogTable.Tables[0].Rows.Count > 0) { for (int i = 0; i < AuditLogTable.Tables[0].Rows.Count; i++) { objAuditLog.Id = Convert.ToInt32(AuditLogTable.Tables[0].Rows[i]["Id"]); objAuditLog.UserId = Convert.ToInt32(AuditLogTable.Tables[0].Rows[i]["UserId"]); //objAuditLog.GudId = Convert.ToString(AuditLogTable.Tables[0].Rows[i]["GudId"]); objAuditLog.CreatedBy = Convert.ToInt32(AuditLogTable.Tables[0].Rows[i]["CreatedBy"]); objAuditLog.CreatedOn = Convert.ToDateTime(AuditLogTable.Tables[0].Rows[i]["CreatedOn"]); objAuditLog.UpdatedBy = Convert.ToInt32(AuditLogTable.Tables[0].Rows[i]["UpdatedBy"]); objAuditLog.UpdatedOn = Convert.ToDateTime(AuditLogTable.Tables[0].Rows[i]["UpdatedOn"]); objAuditLog.PageName = Convert.ToString(AuditLogTable.Tables[0].Rows[i]["PageName"]); objAuditLog.IsActive = Convert.ToBoolean(AuditLogTable.Tables[0].Rows[i]["IsActive"]); } } } } catch (Exception ex) { log.Error("getAuditLogDetailsByGuid \n Message: " + ex.Message + "\n Source: " + ex.Source + "\n StackTrace: " + ex.StackTrace); ExceptionLog.WriteLog(COMMONDATA + " @ getAuditLogDetailsByGuid ", ex.Message + " \n " + ex.StackTrace); } return objAuditLog; }
public int CreateAuditLog(AuditLog audit_log) { return(channel.CreateAuditLog(audit_log)); }
public Task <int> CreateAuditLogAsync(AuditLog audit_log) { return(channel.CreateAuditLogAsync(audit_log)); }
public void WriteEntries(AuditLog auditLogToSave) { foreach(var a in auditLogToSave) _auditLog.Add(a); }
public static void writeEmailLog(EmailLog EL,AuditLog AL) { using (POCDBContext context = new POCDBContext()) { context.spInsertEmailLog(AL.userid, AL.eventtypeid, AL.source, AL.logmessage, EL.emailaddress, EL.emailstatus); } }