public bool DeleteAudit(Audit audit) { if (audit == null) return false; _unitOfWork.AuditRepository.Delete(audit); _unitOfWork.Save(); return true; }
public void DefaultConstructor_NoParams_SetsTimestamp() { //Arrange, Act Audit a = new Audit(string.Empty); //Assert Assert.IsNotNull(a.Timestamp); }
IAuditItem IAuditContext.CreateNew() { var a = new Audit(); Audits.Add(a); a.IPAddress = IPAddress; a.Username = UserName; return a; }
public void BlankAuditShouldFailValidation() { var audit = new Audit(); var isValid = audit.IsValid(); Assert.AreEqual(false, isValid); }
public static Audit Audit(int counter) { var rtValue = new Audit(); rtValue.ObjectName = "ObjectName" + counter; rtValue.AuditActionTypeId = "C"; //AuditActionType.Create; rtValue.Username = "******" + counter; //rtValue.SetIdTo(SpecificGuid.GetGuid(counter)); return rtValue; }
public void LogSuccess(LoginRequest request, Audit audit) { _repository.Update(audit); var history = _session.Load<LoginFailureHistory>(request.UserName); if (history != null) { _session.Delete(history); } }
partial void Audits_Validate(Audit entity, EntitySetValidationResultsBuilder results) { if (entity.DateCompleted != null & entity.DateStarted != null) { if (entity.DateCompleted < entity.DateStarted) { results.AddEntityError("An audit cannot be completed before it has started"); } } }
public void DefaultConstructor_Category_SetsCategory() { //Arrange const string category = "System"; //Act Audit a = new Audit(category); //Assert Assert.AreEqual(category, a.Category); }
public static Audit Audit(int? counter, bool populateAllFields = false) { var rtValue = new Audit(); rtValue.ObjectName = "ObjectName" + counter.Extra(); rtValue.SetActionCode(AuditActionType.Create); rtValue.Username = "******" + counter.Extra(); rtValue.AuditDate = DateTime.Now; if (populateAllFields) { rtValue.ObjectId = "x".RepeatTimes(50); } return rtValue; }
public void LogFailure(LoginRequest request, Audit audit) { _repository.Update(audit); var history = _session.Load<LoginFailureHistory>(request.UserName) ?? new LoginFailureHistory { Id = request.UserName }; history.Attempts = request.NumberOfTries; history.LockedOutTime = request.LockedOutUntil; _session.Store(history); }
public static Audit Audit(int? counter, bool loadAll = true) { var rtValue = new Audit(); rtValue.ObjectName = "ObjectName" + counter.Extra(); rtValue.SetActionCode(AuditActionType.Create); rtValue.Username = "******" + counter.Extra(); rtValue.AuditDate = DateTime.UtcNow.ToPacificTime().Date; if(loadAll) { rtValue.ObjectId = "ObjectId" + counter.Extra(); } return rtValue; }
/// <summary> /// Execute method to write transaction to the database. /// </summary> public void Execute() { if ( Audits != null && Audits.Count > 0 ) { var auditService = new AuditService(); foreach ( var auditDto in Audits ) { var audit = new Audit(); auditDto.CopyToModel( audit ); auditService.Add( audit, audit.PersonId ); auditService.Save( audit, audit.PersonId ); } } }
private ListViewGroup GetItemGroup( Audit.Severity severity ) { switch( severity ) { case x42view.Audit.Severity.Warning: return lvMessages.Groups["grpWarnings"]; case x42view.Audit.Severity.Error: return lvMessages.Groups["grpErrors"]; case x42view.Audit.Severity.Info: return lvMessages.Groups["grpInfo"]; } return null; }
public void CanNotSaveAuditWithoutSettingActionCode() { var audit = new Audit { AuditDate = DateTime.Now, ObjectName = "User", Username = "******" }; using (var ts = new TransactionScope()) { _auditRepository.EnsurePersistent(audit); ts.CommitTransaction(); } }
public void AuditObjectModification(object entity, object id, AuditActionType auditActionType) { if (entity is Audit) return; var audit = new Audit { AuditDate = DateTime.UtcNow.ToPacificTime(), ObjectName = entity.GetType().Name, ObjectId = id == null ? null : id.ToString(), Username = string.IsNullOrEmpty(Principal.Identity.Name) ? "NoUser" : Principal.Identity.Name }; audit.SetActionCode(auditActionType); AuditRepository.EnsurePersistent(audit, false /*Do not force save*/, false /*Do not flush changes since we are in the middle of other actions*/); }
public void Initialize() { using (var ctx = TestCommon.CreateClientContext()) { var site = ctx.Site; audit = site.Audit; ctx.Load(audit, af => af.AuditFlags); ctx.Load(site, s => s.AuditLogTrimmingRetention, s => s.TrimAuditLog); ctx.ExecuteQueryRetry(); auditLogTrimmingRetention = site.AuditLogTrimmingRetention; trimAuditLog = site.TrimAuditLog; // set audit flags for test site.Audit.AuditFlags = AuditMaskType.All; site.Audit.Update(); ctx.ExecuteQueryRetry(); } }
public void CanSaveAuditWithoutObjectId() { var audit = new Audit { AuditDate = DateTime.Now, ObjectName = "User", Username = "******" }; audit.SetActionCode(AuditActionType.Update); using (var ts = new TransactionScope()) { _auditRepository.EnsurePersistent(audit); ts.CommitTransaction(); } Assert.AreEqual(false, audit.IsTransient()); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { //Stores the Request in an Accessible object var request = filterContext.HttpContext.Request; //Generate an audit Audit audit = new Audit() { AuditID = Guid.NewGuid(), IPAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? request.UserHostAddress, URLAccessed = request.RawUrl, TimeAccessed = DateTime.UtcNow, UserName = (request.IsAuthenticated) ? filterContext.HttpContext.User.Identity.Name : "Anonymous", }; //Stores the Audit in the Database ApplicationDbContext db = new ApplicationDbContext(); db.AuditRecords.Add(audit); db.SaveChanges(); base.OnActionExecuting(filterContext); }
public RenderAudit(Audit a) { AuditID = a.AuditID; AuditTypeID = Convert.ToInt32(a.AuditTypeID); UserID = Convert.ToInt32(a.UserID); AdminID = Convert.ToInt32(a.AdminID); Notes = Convert.ToString(a.Created); }
private void btnSave_Click(object sender, EventArgs e) { if (txtTitle.Text.Trim() == "") { MessageBox.Show("Please insert a Title!"); return; } if (txtAuditNumber.Text.Trim() == "") { MessageBox.Show("Please insert an Audit Number!"); return; } if (txtIASentNumber.Text.Trim() == "") { MessageBox.Show("Please insert a IA Sent Number!"); return; } if (cbCompanies.Text.Trim() == "") { MessageBox.Show("Please choose a Company!"); return; } if (cbAuditTypes.Text.Trim() == "") { MessageBox.Show("Please choose an Audit Type!"); return; } if (cbAuditor1.Text.Trim() == "") { MessageBox.Show("Please choose an Auditor 1!"); return; } newAuditRecord = new Audit() { AuditNumber = txtAuditNumber.Text, Auditor1 = getComboboxItem <Users>(cbAuditor1), Auditor1ID = getComboboxItem <Users>(cbAuditor1).Id, Company = getComboboxItem <Companies>(cbCompanies), CompanyId = getComboboxItem <Companies>(cbCompanies).Id, AuditType = getComboboxItem <AuditTypes>(cbAuditTypes), AuditTypeId = getComboboxItem <AuditTypes>(cbAuditTypes).Id, IASentNumber = txtIASentNumber.Text, Title = txtTitle.Text, Year = dtpYear.Value.Year, ReportDt = dtpReportDate.Value.Date, IsCompleted = false, Id = AuditUpdId, //only on update RevNo = oldAuditRecord.RevNo, AttCnt = oldAuditRecord.AttCnt }; if (cbAuditor2.SelectedIndex > -1) { newAuditRecord.Auditor2 = getComboboxItem <Users>(cbAuditor2); newAuditRecord.Auditor2ID = getComboboxItem <Users>(cbAuditor2).Id; } else { newAuditRecord.Auditor2 = new Users(); } if (cbSupervisor.SelectedIndex > -1) { newAuditRecord.Supervisor = getComboboxItem <Users>(cbSupervisor); newAuditRecord.SupervisorID = getComboboxItem <Users>(cbSupervisor).Id; } else { newAuditRecord.Supervisor = new Users(); } if (cbRating.SelectedIndex > -1) { newAuditRecord.AuditRating = getComboboxItem <AuditRating>(cbRating); newAuditRecord.AuditRatingId = getComboboxItem <AuditRating>(cbRating).Id; } else { newAuditRecord.AuditRating = new AuditRating(); } if (isInsert) //insert { if (InsertIntoTable_Audit(newAuditRecord)) { MessageBox.Show("New Audit inserted successfully!"); success = true; Close(); } else { MessageBox.Show("The New Audit has not been inserted!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else //update { if (Audit.isEqual(oldAuditRecord, newAuditRecord) == false) { if (UpdateTable_Audit(newAuditRecord)) { bool successful = true; newAuditRecord.RevNo = newAuditRecord.RevNo + 1; success = true; if (oldAuditRecord.AttCnt > 0) { if (InsertIntoTable_Att(newAuditRecord.Id, oldAuditRecord.RevNo, UserInfo.userDetails.Id) == false) { successful = false; } } if (successful) { MessageBox.Show("Audit updated successfully!"); } else { MessageBox.Show("Audit updated. Error while inserting attachments."); } Close(); } else { MessageBox.Show("The Audit has not been updated!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { Close(); } } }
private bool InsertIntoTable_Audit(Audit audit) //INSERT [dbo].[Audit] { bool ret = false; SqlConnection sqlConn = new SqlConnection(SqlDBInfo.connectionString); string InsSt = "INSERT INTO [dbo].[Audit] ([Year],[CompanyID],[AuditTypeID],[Title],[ReportDt] ," + "[Auditor1ID],[Auditor2ID],[SupervisorID],[IsCompleted],[AuditNumber],[IASentNumber],[InsUserID],[InsDt],[UpdUserID],[UpdDt], [RevNo], [AuditRatingId]) VALUES " + "(@Year, @CompanyID, @AuditTypeID, " + "encryptByPassPhrase(@passPhrase, convert(varchar(500), @Title)), " + "@ReportDt, @Auditor1ID, @Auditor2ID, @SupervisorID, @IsCompleted, @AuditNumber, @IASentNumber, @InsUserID, getDate(), @InsUserID, getDate(), 1 ,@AuditRatingId) "; try { sqlConn.Open(); SqlCommand cmd = new SqlCommand(InsSt, sqlConn); cmd.Parameters.AddWithValue("@passPhrase", SqlDBInfo.passPhrase); cmd.Parameters.AddWithValue("@Year", audit.Year); cmd.Parameters.AddWithValue("@CompanyID", audit.CompanyId); cmd.Parameters.AddWithValue("@AuditTypeID", audit.AuditTypeId); cmd.Parameters.AddWithValue("@Title", audit.Title); cmd.Parameters.AddWithValue("@ReportDt", audit.ReportDt.Date); cmd.Parameters.AddWithValue("@Auditor1ID", audit.Auditor1ID); if (audit.Auditor2ID == null) { cmd.Parameters.AddWithValue("@Auditor2ID", DBNull.Value); } else { cmd.Parameters.AddWithValue("@Auditor2ID", audit.Auditor2ID); } if (audit.SupervisorID == null) { cmd.Parameters.AddWithValue("@SupervisorID", DBNull.Value); } else { cmd.Parameters.AddWithValue("@SupervisorID", audit.SupervisorID); } if (audit.AuditRatingId == null) { cmd.Parameters.AddWithValue("@AuditRatingId", DBNull.Value); } else { cmd.Parameters.AddWithValue("@AuditRatingId", audit.AuditRatingId); } cmd.Parameters.AddWithValue("@IsCompleted", audit.IsCompleted); cmd.Parameters.AddWithValue("@AuditNumber", audit.AuditNumber); cmd.Parameters.AddWithValue("@IASentNumber", audit.IASentNumber); //cmd.Parameters.AddWithValue("@InsUserID", user.Id); cmd.Parameters.AddWithValue("@InsUserID", UserInfo.userDetails.Id); cmd.CommandType = CommandType.Text; int rowsAffected = cmd.ExecuteNonQuery(); if (rowsAffected > 0) { ret = true; } } catch (Exception ex) { MessageBox.Show("The following error occurred: " + ex.Message); } sqlConn.Close(); return(ret); }
/// <summary> /// Instantiates a new DTO object from the entity /// </summary> /// <param name="audit"></param> public AuditDto( Audit audit ) { CopyFromModel( audit ); }
public override int SaveChanges() { try { if (ChangeTracker.HasChanges()) { foreach (var entry in ChangeTracker.Entries()) { try { var root = (Schema.Table)entry.Entity; var now = DateTime.Now; switch (entry.State) { case EntityState.Added: { root.Created_at = now; root.Created_by = TaoDataBase.GetIdAccount(); root.Updated_at = null; root.Updated_by = null; root.DelFlag = false; break; } case EntityState.Modified: { root.Updated_at = now; root.Updated_by = TaoDataBase.GetIdAccount(); break; } } } catch { } } var audit = new Audit(); audit.PreSaveChanges(this); var rowAffecteds = base.SaveChanges(); audit.PostSaveChanges(); if (audit.Configuration.AutoSavePreAction != null) { audit.Configuration.AutoSavePreAction(this, audit); } return(base.SaveChanges()); } return(0); } catch (DbUpdateException ex) { throw ex; } catch (Exception ex) { throw ex; } }
public void AddAudit(Audit audit) { audit.Employee = this; _audits.Add(audit); }
public static void Main(string[] args) { /* setting language */ //Console.OutputEncoding = System.Text.Encoding.UTF8; /* initializing item class variavle */ //Item item1 = new Item(); /* printing information about item */ //item1.Print(); /* initializing publisher class variable */ Publisher pub1 = new Publisher("Наука и жизнь", "*****@*****.**", 1234, new DateTime(2014, 12, 14)); /* initializing book class instance */ Book b2 = new Book("Толстой Л.Н.", "Война и мир", pub1, 1234, 2013, 101, true); /* taking the book and printing information */ b2.TakeItem(); b2.Print(); /* running audit */ Audit.RunAudit(); /* initializing maganize class variable */ Magazine mag1 = new Magazine("О природе", 5, "Земля и мы", 2014, 1235, true); /* initializing publisher class varaible */ Publisher pub2 = new Publisher("Слабоумие и отвага", "*****@*****.**", 234, new DateTime(2015, 11, 11)); /* initializing book class instance */ Book b3 = new Book("Дж. Селинджер", "Над пропастью во ржи", pub2, 1236, 2014, 101, true); /* taking magazine item and printing information */ mag1.TakeItem(); mag1.Print(); mag1.Subs(); mag1.Print(); /* initializing item class variable */ Console.WriteLine("\n Тестирование полиморфизма"); Item it; /* assigning book variable to item variable */ it = b2; it.TakeItem(); // taking item it.Return(); // returning item back it.Print(); // printing information about item /* reassigning item to magazine */ it = mag1; it.TakeItem(); it.Return(); it.Print(); /* creating list of links to Item class */ System.Collections.Generic.List <Item> itlist = new System.Collections.Generic.List <Item>(); /* adding items to item list */ itlist.AddRange(new Item[] { b2, b3, mag1 }); /* sorting list */ itlist.Sort(); /* printing sorted items */ Console.WriteLine("\nСортировка по инвентарному номеру"); foreach (Item x in itlist) { x.Print(); } /* to keep console awake */ Console.Read(); }
public bool EditAudit(Audit audit) { _unitOfWork.AuditRepository.Edit(audit); _unitOfWork.Save(); return true; }
public static Audit CreateAudit(int ID, string auditCode, string auditDescription, global::System.DateTime schduledDate, int auditType_Audit, int auditStatus_Audit, byte[] rowVersion) { Audit audit = new Audit(); audit.Id = ID; audit.AuditCode = auditCode; audit.AuditDescription = auditDescription; audit.SchduledDate = schduledDate; audit.AuditType_Audit = auditType_Audit; audit.AuditStatus_Audit = auditStatus_Audit; audit.RowVersion = rowVersion; return audit; }
public bool AddAudit(Audit audit) { _unitOfWork.AuditRepository.Add(audit); _unitOfWork.Save(); return true; }
/// <summary> /// Saves new Audit. /// </summary> /// <returns>Id of new audit</returns> public int AddAndSave() { Audit newAudit = new Audit(); newAudit.Name = this.Name; newAudit.AuditStartDate = DateTime.Now; newAudit.AuditEndDate = null; newAudit.AuditUserId = InternalUserId; newAudit.ExtractId = this.ExtractId; _unitOfWork.Audits.Add(newAudit); _unitOfWork.Save(); return (newAudit.AuditId); }
public static VerejnaZakazkaSearchData _Search( VerejnaZakazkaSearchData search, AggregationContainerDescriptor <VerejnaZakazka> anyAggregation, ElasticClient client) { if (string.IsNullOrEmpty(search.Q) && (search.CPV == null || search.CPV.Length == 0)) { return(null); } if (client == null) { client = ES.Manager.GetESClient_VZ(); } AggregationContainerDescriptor <VerejnaZakazka> baseAggrDesc = null; baseAggrDesc = anyAggregation == null ? null //new AggregationContainerDescriptor<VerejnaZakazka>().Sum("sumKc", m => m.Field(f => f.Castka)) : anyAggregation; Func <AggregationContainerDescriptor <VerejnaZakazka>, AggregationContainerDescriptor <VerejnaZakazka> > aggrFunc = (aggr) => { return(baseAggrDesc); }; string queryString = search.Q; Nest.ISearchResponse <VerejnaZakazka> res = null; if (search.CPV != null && search.CPV.Length > 0) { string cpvs = search.CPV.Select(c => c + "*").Aggregate((f, s) => f + " OR " + s); if (!string.IsNullOrEmpty(queryString)) { queryString = queryString + " AND (cPV:(" + cpvs + "))"; } else { queryString = "cPV:(" + cpvs + ")"; } } int page = search.Page - 1; if (page < 0) { page = 0; } try { res = client .Search <VerejnaZakazka>(a => a .Size(search.PageSize) .From(search.PageSize * page) .Aggregations(aggrFunc) .Query(qq => qq.QueryString(qs => qs .Query(queryString) .DefaultOperator(Nest.Operator.And) ) ) .Sort(ss => GetSort(search.Order)) .Aggregations(aggrFunc) .TrackTotalHits(page * search.PageSize == 0 ? true : (bool?)null) ); } catch (Exception e) { Audit.Add(Audit.Operations.Search, "", "", "VerejnaZakazka", "error", search.Q, null); if (res != null && res.ServerError != null) { ES.Manager.LogQueryError <VerejnaZakazka>(res, "Exception, Orig query:" + search.OrigQuery + " query:" + search.Q + "\n\n res:" + search.ElasticResults.ToString() , ex: e); } else { HlidacStatu.Util.Consts.Logger.Error("", e); } throw; } Audit.Add(Audit.Operations.Search, "", "", "VerejnaZakazka", res.IsValid ? "valid" : "invalid", search.Q, null); search.IsValid = res.IsValid; search.ElasticResults = res; search.Total = res.Total; return(search); }
public Data.Audit GetAudit() { Data.Audit ret = new Audit(); ret.Success = true; ret.ComputingTimeInMs = Convert.ToInt32(processEnd.Subtract(processStart).TotalMilliseconds); ret.SplitsExceedsFieldSize = new List <int>(); ret.CarsMissingInAnySplit = new List <int>(); ret.NotExpectedCarsRegistred = new List <int>(); ret.IROrderInconsistencySplits = new List <int>(); ret.Cars = 0; ret.Splits = 0; List <int> allcars = (from r in EntryList select r.driver_id).ToList(); foreach (var split in Splits) { ret.Cars += split.TotalCarsCount; ret.Splits++; foreach (var car in split.AllCars) { int car_id = car.driver_id; if (allcars.Contains(car_id)) { allcars.Remove(car_id); } else { ret.NotExpectedCarsRegistred.Add(car_id); ret.Success = false; } } if (split.TotalCarsCount > FieldSize) { ret.SplitsExceedsFieldSize.Add(split.Number); ret.Success = false; } foreach (int classIndex in split.GetClassesIndex()) { double minIR = (from r in split.GetClassCars(classIndex) select r.rating).Min(); var nextSplits = (from r in Splits where r.Number >= split.Number + 1 select r).ToList(); var nextCars = new List <Data.Line>(); foreach (var nextSplit in nextSplits) { var cars = nextSplit.GetClassCars(classIndex); if (cars != null) { nextCars.AddRange(cars); } } var higherIRs = (from r in nextCars where r.rating > minIR + 1 select r).Count(); if (higherIRs > 0) { ret.IROrderInconsistencySplits.Add(split.Number); } } } if (allcars.Count > 0) { ret.CarsMissingInAnySplit.AddRange(allcars); ret.Success = false; } int splitsHavingDiffClassesSof = (from r in Splits where r.ClassesSofDiff > 0 select r.ClassesSofDiff).Count(); if (splitsHavingDiffClassesSof > 0) { ret.AverageSplitClassesSofDifference = Convert.ToInt32(Math.Round((from r in Splits where r.ClassesSofDiff > 0 select r.ClassesSofDiff).Average())); } ret.MinSplitSizePercent = 0; if (Splits != null && Splits.Count > 0) { double splitAvgSize = 0; double splitMinSize = 0; splitAvgSize = (from r in Splits select r.TotalCarsCount).Average(); splitMinSize = (from r in Splits select r.TotalCarsCount).Min(); ret.MinSplitSizePercent = splitMinSize / splitAvgSize; } return(ret); }
Boolean ImportFile(string strFilePath1) { string _yrmo = Session["yrmo"].ToString(); //ddlYrmo.SelectedItem.Text; string logFilePath = Server.MapPath("~/uploads/") + "YEB_WWRET_" + _yrmo + ".xls"; bool importStat = false; string filterexp = ""; ImportYEBData iObj = new ImportYEBData(); HRAExcelImport tObj = new HRAExcelImport(); HRAParseData pObj = new HRAParseData(); ImportYEBData.Rollback(source + pilotind, _yrmo); DataTable dtWWret; DataSet ds = new DataSet(); ds.Clear(); ds = tObj.getExcelData(strFilePath1, "WWRetTable"); //testing Cigna Admin fee bill 6-8-2009 //ds = tObj.getCignaAdminFeeBillData(strFilePath1, "CignaAdminFeeTable"); //tObj.ConfirmPutnamYRMO(strFilePath1, _yrmo); ////ds.Tables.Add(tObj.ConvertRangeXLS(_filepath, dt, "SSN", 0)); ///_counter = pObj.parsePutnamPartData(ds, _filepath, _source, _qy); ///end testing/// dtWWret = ds.Tables["WWRetTable"]; if (dtWWret.Rows.Count > 0) { if (pilotind == "PI") { filterexp = "(HealthStatusCode not in ('RT','VT','RFB','RFG','RFI','RFO','RFP','RFS')) AND " + "EligGroupID <> 0 AND ((Med_TierID) not in (1,2,3,4,5,6)) AND ((Den_TierID) not in (1,2,3,4,5,6)) and ((Vis_TierID) not in (1,2,3,4,5,6)) AND " + "((Med_OptionID <> 100) OR (Den_OptionID <>100) OR (Vis_OptionID <> 100)) AND (pilotflag='True') AND EEID >0"; //"(Med_OptionID <> '100' and Den_OptionID <>'100' and Vis_OptionID <> '100') AND (pilotflag='True') AND EEID >0"; DataRow[] foundrows = dtWWret.Select(filterexp); _counter = foundrows.Length; //foreach (DataRow dr in foundrows) { //insert the row in the YEB Detail table iObj.insertWWRetData(foundrows, usryrmo, pilotind, source, TypeCD); } } else if (pilotind == "NP") { filterexp = "(HealthStatusCode not in ('RT','VT','RFB','RFG','RFI','RFO','RFP','RFS')) AND " + "EligGroupID <> 0 AND ((Med_TierID) not in (1,2,3,4,5,6)) AND ((Den_TierID) not in (1,2,3,4,5,6)) and ((Vis_TierID) not in (1,2,3,4,5,6)) AND " + "((Med_OptionID <> 100) OR (Den_OptionID <>100) OR (Vis_OptionID <> 100)) AND (pilotflag='False') AND EEID >0"; //"(Med_OptionID <> '100' AND Den_OptionID <>'100' AND Vis_OptionID <> '100') AND (pilotflag='False') AND EEID >0"; DataRow[] foundrows = dtWWret.Select(filterexp); _counter = foundrows.Length; //foreach (DataRow dr in foundrows) { //insert the row in the YEB Detail table iObj.insertWWRetData(foundrows, usryrmo, pilotind, source, TypeCD); } } } if (File.Exists(logFilePath)) { File.Delete(logFilePath); } importStat = true; Session["taskId"] = Convert.ToInt32(Session["taskId"]) + 1; Audit.auditUserTaskI(Session.SessionID, Session["mid"].ToString(), Session["taskId"].ToString(), "YEB", "ImportSourceFile", "YEB_WWRET", "WW Import", usryrmo, _counter); return(importStat); }
/// <summary> /// To the model. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static Audit ToModel( this AuditDto value ) { Audit result = new Audit(); value.CopyToModel( result ); return result; }
public async Task StartAsync( CancellationToken cancellationToken) { _appLifetime.ApplicationStarted.Register(OnStarted); _appLifetime.ApplicationStopping.Register(OnStopping); _appLifetime.ApplicationStopped.Register(OnStopped); using var scope = _serviceProvider.CreateScope(); var serverBuilder = scope.ServiceProvider.GetRequiredService <IServerBuilder>(); var options = serverBuilder.GetOptionsBuilder(_interceptor, _messageInterceptor); Server = serverBuilder.GetServer(); await Server.StartAsync(options.Build()); Server.StartedHandler = new MqttServerStartedHandlerDelegate(e => { Console.WriteLine("Mqtt Broker start " + e); }); Server.StoppedHandler = new MqttServerStoppedHandlerDelegate(e => { Console.WriteLine("Mqtt Broker stop " + e); }); Server.ClientSubscribedTopicHandler = new MqttServerClientSubscribedHandlerDelegate(e => { var vehicleId = e.TopicFilter.Topic .Replace("platooning/", "").Replace("/#", ""); _logger.LogInformation("Client subscribed " + e.ClientId + " topic " + e.TopicFilter.Topic + "Vehicle Id " + vehicleId); try { var audit = new Audit { ClientId = e.ClientId, Type = "Sub", Topic = e.TopicFilter.Topic, Payload = JsonConvert.SerializeObject(e.TopicFilter, Formatting.Indented) }; _repo.AddAudit(audit); var sub = _repo.GetSubscribeByTopic(e.ClientId, e.TopicFilter.Topic, e.TopicFilter.QualityOfServiceLevel.ToString()); if (sub != null) { _logger.LogInformation($"There is a subcribe like ClientID {e.ClientId}."); return; } var subClient = new Subscribe { Topic = e.TopicFilter.Topic, Enable = true, ClientId = e.ClientId, QoS = e.TopicFilter.QualityOfServiceLevel.ToString() }; _repo.AddSubscribe(subClient); } catch (Exception exception) { var log = new Log { Exception = exception.StackTrace }; _repo.AddLogAsync(log); _logger.LogError("Error = MqttServerClientSubscribedHandlerDelegate ", exception.StackTrace); } finally { _repo.SaveChangesAsync(cancellationToken); } }); Server.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate(e => { try { var clientId = e.ClientId; var topicFilter = e.TopicFilter; _logger.LogInformation($"[{DateTime.Now}] Client '{clientId}' un-subscribed to {topicFilter}."); try { var sub = _repo.GetSubscribeById(e.ClientId).Where(s => s.Topic == topicFilter); var subscribes = sub as List <Subscribe> ?? sub.ToList(); if (subscribes.All(a => a.Topic != topicFilter)) { return; } subscribes .ForEach(a => a.Enable = false); } catch (Exception exception) { var log = new Log { Exception = exception.StackTrace }; _repo.AddLogAsync(log); _logger.LogError("Error = MqttServerClientSubscribedHandlerDelegate ", exception.StackTrace); Console.WriteLine(exception); } } catch (Exception ex) { Console.WriteLine($"[{DateTime.Now}] Client get error " + ex.Message); } finally { _repo.SaveChangesAsync(cancellationToken); } }); Server.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e => { try { var payload = Functions.GetPayload(e.ApplicationMessage.Payload); var payloadser = JsonConvert.SerializeObject(payload, Formatting.Indented); var tree = e.ApplicationMessage.Topic.Split('/'); var audit = new Audit { ClientId = e.ClientId, Type = "Pub", Topic = e.ApplicationMessage.Topic, Payload = payloadser }; _repo.AddAudit(audit); if (e.ClientId == null) { var log = new Log { Exception = new string("Broker publish message itself " + payloadser + " " + e.ClientId) }; _repo.AddLogAsync(log); //_repo.SaveChangesAsync(cancellationToken); return; } if (!tree.First().Contains("platooning")) { var log = new Log { Exception = new string("Mqtt broker just only response with starting \"platoon\" " + payloadser + " " + e.ClientId) }; _repo.AddLogAsync(log); //_repo.SaveChangesAsync(cancellationToken); return; } if (payload.PlatoonDissolveStatus) { if (_repo.GetPlatoon().Any(a => a.ClientId == e.ClientId && a.IsLead)) { Console.WriteLine( $"[{DateTime.Now}] This is lead Vehicle PlatoonDissolveStatus is true all platoon infor must be deleted" + " Client Id " + e.ClientId + " payload " + payload); var platoonlist = _repo.GetPlatoon().Where(a => a.IsFollower); var platoonlistArray = platoonlist as Platoon[] ?? platoonlist.ToArray(); foreach (var platoon in platoonlistArray) { Server.UnsubscribeAsync(platoon.ClientId, "platooning/broadcast/" + platoon.PlatoonRealId); Server.UnsubscribeAsync(platoon.ClientId, "platooning/" + platoon.ClientId); } _repo.DeletePlatoonRange(platoonlistArray); } else { Console.WriteLine( $"[{DateTime.Now}] This is following Vehicle PlatoonDissolveStatus is true all platoon infor must be deleted" + " Client Id " + e.ClientId + " payload " + payload); var followingVehicle = _repo.GetPlatoon().FirstOrDefault(a => a.IsFollower && a.ClientId == e.ClientId); Server.UnsubscribeAsync(followingVehicle.ClientId, "platooning/" + followingVehicle.ClientId); _repo.DeletePlatoon(followingVehicle); } } if (payload.Maneuver == Maneuver.CreatePlatoon) { if (tree.Length != 4) { var log = new Log { Exception = new string("For creating platoon, topic must 4 length 1. \"platooning\" " + " 2. \"message\" " + " 3. \"leadvehicleID\" " + " 4. \"platoonID\" " + " payload " + payloadser + " " + " client ID " + e.ClientId + " topic " + e.ApplicationMessage.Topic) }; _repo.AddLogAsync(log); //_repo.SaveChangesAsync(cancellationToken); return; } var platoonId = tree[3]; var platoonList = _repo.GetPlatoon().ToList(); var leadVehicleId = tree[2]; var leadVehicle = _repo.GetSubscribeById(leadVehicleId); var pla = platoonList .FirstOrDefault(f => f.Enable && f.PlatoonRealId == platoonId); if (leadVehicle != null && pla == null) { var platoon = new Platoon() { Enable = true, ClientId = e.ClientId, IsLead = true, VechicleId = tree[2], PlatoonRealId = tree[3] }; _repo.AddPlatoon(platoon); Console.WriteLine($"[{DateTime.Now}] Creating new Platoon Client Id " + e.ClientId + " platooning Id" + platoon.PlatoonRealId + " payload " + payloadser); } else { Console.WriteLine($"[{DateTime.Now}] Platoon is already created Client Id " + e.ClientId + " platooning Id" + platoonId + " payload " + payloadser); } } else if (payload.Maneuver == Maneuver.JoinRequest) { if (tree.Length != 3) { var log = new Log { Exception = new string("For joining platoon, topic must 3 length 1. \"platooning\" " + " 2. \"message\" " + " 3. \"followingVehicleId\" " + " 4. \"#\" " + " payload " + payloadser + " " + " client ID " + e.ClientId + " topic " + e.ApplicationMessage.Topic) }; _repo.AddLogAsync(log); //_repo.SaveChangesAsync(); return; } var isFollowing = _repo.GetPlatoon() .FirstOrDefault(f => f.IsFollower && f.VechicleId == tree[2] && f.Enable); if (isFollowing != null) { return; } var platoonLead = _repo.GetPlatoon().FirstOrDefault(f => f.IsLead && f.Enable); if (platoonLead != null) { var platoon = new Platoon() { Enable = false, ClientId = e.ClientId, IsLead = false, IsFollower = true, VechicleId = tree[2], PlatoonRealId = platoonLead.PlatoonRealId }; _repo.AddPlatoon(platoon); Console.WriteLine($"[{DateTime.Now}] Join Platoon Client Id " + e.ClientId + " platooning Id" + platoon.PlatoonRealId + " payload " + payloadser); var message = new BitArray(_dataLenght); message.Set(0, false); message.Set(1, false); message.Set(2, true); Server.PublishAsync("platooning/" + platoonLead.ClientId + "/" + tree[2], Encoding.ASCII.GetString(Functions.BitArrayToByteArray(message))); } } else if (payload.Maneuver == Maneuver.JoinAccepted) { Console.WriteLine($"[{DateTime.Now}] Join accepted Client Id " + e.ClientId + " payload " + payloadser); var followvehicleId = tree[1]; var leadVehicle = tree[2]; var plattonId = tree[3]; var allplatoon = _repo.GetPlatoon(); if (allplatoon != null) { var enumerable = allplatoon as Platoon[] ?? allplatoon.ToArray(); var platoonfollow = enumerable.FirstOrDefault(f => f.IsFollower && f.ClientId == followvehicleId); if (platoonfollow != null) { platoonfollow.Enable = true; platoonfollow.PlatoonRealId = plattonId; _repo.UpdatePlatoon(platoonfollow); } else { var platoonlead = enumerable .FirstOrDefault(f => f.IsLead && f.Enable && f.ClientId == leadVehicle); if (platoonlead != null) { var platoon = new Platoon() { Enable = true, ClientId = e.ClientId, IsLead = false, IsFollower = true, VechicleId = followvehicleId, PlatoonRealId = platoonlead.PlatoonRealId }; _repo.AddPlatoon(platoon); } } } } else if (payload.Maneuver == Maneuver.JoinRejected) { Console.WriteLine($"[{DateTime.Now}] Join rejected Client Id " + e.ClientId + " payload " + payloadser); var platoonfollow = _repo.GetPlatoon() .FirstOrDefault(f => f.IsFollower && f.ClientId == tree[1]); if (platoonfollow != null) { _repo.DeletePlatoon(platoonfollow); } } else { var log = new Log { Exception = new string("Unknown Maneuver " + payloadser + " " + e.ClientId) }; _repo.AddLogAsync(log); } } catch (Exception exception) { Console.WriteLine(exception); var log = new Log { Exception = exception.StackTrace }; _repo.AddLogAsync(log); } finally { _repo.SaveChangesAsync(cancellationToken); } OnDataReceived(e.ApplicationMessage.Payload); }); }
public AuditedComment(Audit audit) { AsAudit = audit; AddCommentToAudit(AsAudit); }
protected override void Seed(AuditContext context) { base.Seed(context); int numberOfObject = 9; int numberOfSubObject = 8; Random random = new Random(); for (int i = 1; i <= numberOfObject; i++) { #region List <Category> categories = new List <Category>(); for (int j = 1; j <= numberOfSubObject; j++) { int k = (i - 1) * 10 + j; Category category = new Category() { Id = k, Name = "Category " + k, CreatedAt = DateTime.Now, UpdateAt = DateTime.Now }; categories.Add(category); } context.Categories.AddRange(categories); #endregion #region Auditer auditer = new Auditer() { Id = i, FirstName = "Даниил" + i, LastName = "Кирьяков " + i, Login = "******" + i, Password = BCrypt.Net.BCrypt.HashPassword("JTZgxPY9Dt2C", BCrypt.Net.BCrypt.GenerateSalt(), false, BCrypt.Net.HashType.SHA256), CreatedAt = DateTime.Now.ToString("dd/MM/yyyy HH:mm"), UpdateAt = DateTime.Now.ToString("dd/MM/yyyy HH:mm") }; context.Auditers.Add(auditer); #endregion #region Audit audit = new Audit() { Id = i, Name = "Audit " + i, AuditedCompanyName = "Company " + i, CreatedAt = DateTime.Now.ToString("dd/MM/yyyy HH:mm"), UpdateAt = DateTime.Now.ToString("dd/MM/yyyy HH:mm") }; audit.Auditer = auditer; //auditer.Audits.Add(audit); context.Audits.Add(audit); #endregion #region List <Answer> answers = new List <Answer>(); for (int j = 1; j <= numberOfSubObject; j++) { int k = (i - 1) * 10 + j; Answer answer = new Answer() { Id = k, Score = k, RecommandationToApply = "Recommandation To Apply" + k, RiskIncurred = "Risk Incurred", Comment = "Comment " + k, FaillureNumber = k, CreatedAt = DateTime.Now, UpdateAt = DateTime.Now }; answer.Audit = audit; answers.Add(answer); context.Answers.Add(answer); } #endregion #region List <Question> questions = new List <Question>(); for (int j = 1; j <= numberOfSubObject; j++) { int k = (i - 1) * 10 + j; Question question = new Question() { Id = k, Intitled = "Intitled " + k, Details = "Details " + k, Coefficient = random.Next(1, 5), Scale = 10, Recommandation = "Recommandation" + k, Risk = "Risk " + k, CreatedAt = DateTime.Now, UpdateAt = DateTime.Now, }; question.Category = categories.ElementAt(j - 1); question.Answers = new ObservableCollection <Answer>(); question.Answers.Add(answers.ElementAt(j - 1)); questions.Add(question); } audit.Questions = new ObservableCollection <Question>(questions); //category.Questions = questions; #endregion } context.SaveChanges(); }
public virtual string AddData(Registration reg, string user) { if (reg.jsonSchema == null) { throw new DataSetException(this.datasetId, ApiResponseStatus.DatasetJsonSchemaMissing); } Registration oldReg = null; oldReg = DataSet.CachedDatasets.Get(reg.datasetId)?.Registration(); if (oldReg == null) { Audit.Add <Registration>(Audit.Operations.Create, user, reg, null); } else { Audit.Add <Registration>(Audit.Operations.Update, user, reg, oldReg); } var addDataResult = base.AddData(reg, reg.datasetId, reg.createdBy); DataSet.CachedDatasets.Delete(reg.datasetId); //check orderList if (reg.orderList?.Length > 0) { //get mapping var ds = CachedDatasets.Get(addDataResult); var txtProps = ds.GetTextMappingList(); var allProps = ds.GetMappingList(); if (allProps.Where(m => !DataSet.DefaultDatasetProperties.Keys.Contains(m)).Count() > 0) //0=mapping not available , (no record in db) { bool changedOrderList = false; //find missing and remove it List <int> toRemove = new List <int>(); for (int i = 0; i < reg.orderList.GetLength(0); i++) { string oProp = reg.orderList[i, 1] .Replace(DataSearchResult.OrderAsc, "") .Replace(DataSearchResult.OrderDesc, "") .Replace(DataSearchResult.OrderAscUrl, "") .Replace(DataSearchResult.OrderDescUrl, "") .Trim(); if (oProp.EndsWith(".keyword")) { oProp = System.Text.RegularExpressions.Regex.Replace(oProp, "\\.keyword$", ""); } if (allProps.Contains(oProp) == false) { //neni na seznamu properties, pridej do seznamu k smazani toRemove.Add(i); } } if (toRemove.Count > 0) { foreach (var i in toRemove.OrderByDescending(n => n)) { reg.orderList = HlidacStatu.Util.ArrayTools.TrimArray <string>(i, null, reg.orderList); changedOrderList = true; } } for (int i = 0; i < reg.orderList.GetLength(0); i++) { string oProp = reg.orderList[i, 1] .Replace(DataSearchResult.OrderAsc, "") .Replace(DataSearchResult.OrderAscUrl, "") .Replace(DataSearchResult.OrderDesc, "") .Replace(DataSearchResult.OrderDescUrl, "") .Trim(); if (txtProps.Contains(oProp)) { //pridej keyword na konec reg.orderList[i, 1] = reg.orderList[i, 1].Replace(oProp, oProp + ".keyword"); changedOrderList = true; } } if (changedOrderList) { addDataResult = base.AddData(reg, reg.datasetId, reg.createdBy); } } } DataSet.CachedDatasets.Set(reg.datasetId, null); return(addDataResult); }
protected void btnDeleted_Click(object sender, EventArgs e) { try { Audit audit = new Audit(); string notes = null; db = new LinqToSqlDataContext(); foreach (GridViewRow row in gvProducts.Rows) { if (!String.IsNullOrEmpty((row.FindControl("ProductId") as Label).Text)) { Int32 productId = Convert.ToInt32((row.FindControl("ProductId") as Label).Text); Boolean isDeleted = (row.FindControl("chkDelete") as CheckBox).Checked; Decimal objtxtPrice = -1; DateTime?objtxtExpiryDate = null; Int32 objlblProuctId = Convert.ToInt32((row.FindControl("ProductId") as Label).Text); // get product id if ((row.FindControl("txtPrice") as TextBox).Text.Trim() != "") { objtxtPrice = Convert.ToDecimal((row.FindControl("txtPrice") as TextBox).Text); // get entered Price } if ((row.FindControl("txtExpiryDate") as TextBox).Text.Trim() != "") { objtxtExpiryDate = DateTime.Parse((row.FindControl("txtExpiryDate") as TextBox).Text); // get selected expiry date } if (isDeleted == true && objtxtPrice > -1 && objtxtExpiryDate != null) { var productPrice = (from p in db.ARC_Product_Price_Maps where p.ProductId == productId && p.ARCId == Convert.ToInt32(ddlArc.SelectedValue.ToString()) && p.IsDeleted == false select p).Single(); productPrice.IsDeleted = true; productPrice.ModifiedOn = DateTime.Now; productPrice.ModifiedBy = Session[enumSessions.User_Id.ToString()].ToString(); db.SubmitChanges(); string script = "alertify.alert('" + ltrProdPriceDeleted.Text + "');"; ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", script, true); } notes += "Product: " + objlblProuctId + ", Price: " + objtxtPrice + ", Date: " + objtxtExpiryDate + ", "; } } BindProducts(Convert.ToInt32(ddlArc.SelectedValue.ToString())); // bind grid after delete ARC price audit.Notes = "Deleted - ARC: " + ddlArc.SelectedItem.ToString() + ", " + notes; audit.UserName = Session[enumSessions.User_Name.ToString()].ToString(); audit.ChangeID = Convert.ToInt32(enumAudit.Manage_ARC_Product_Price); audit.CreatedOn = DateTime.Now; if (Request.ServerVariables["LOGON_USER"] != null) { audit.WindowsUser = Request.ServerVariables["LOGON_USER"]; } audit.IPAddress = Request.UserHostAddress; db.Audits.InsertOnSubmit(audit); db.SubmitChanges(); } catch (Exception objException) { db = new CSLOrderingARCBAL.LinqToSqlDataContext(); db.USP_SaveErrorDetails(Request.Url.ToString(), "btnDeleted_Click", Convert.ToString(objException.Message), Convert.ToString(objException.InnerException), Convert.ToString(objException.StackTrace), "", HttpContext.Current.Request.UserHostAddress, false, Convert.ToString(HttpContext.Current.Session[enumSessions.User_Id.ToString()])); } finally { if (db != null) { db.Dispose(); } } }
private bool UpdateTable_Audit(Audit audit) { bool ret = false; SqlConnection sqlConn = new SqlConnection(SqlDBInfo.connectionString); string InsSt = "UPDATE [dbo].[Audit] SET [Year] = @Year, [CompanyID] = @CompanyID, [AuditTypeID] = @AuditTypeID, " + "[Title] = encryptByPassPhrase(@passPhrase, convert(varchar(500), @Title))," + "[ReportDt] = @ReportDt, " + "[Auditor1ID] = @Auditor1ID, [Auditor2ID] = @Auditor2ID, [SupervisorID] = @SupervisorID, [IsCompleted] = @IsCompleted, [AuditNumber] = @AuditNumber, " + "[IASentNumber] = @IASentNumber, [UpdUserID] = @UpdUserID, [UpdDt] = getDate(), [RevNo] = RevNo+1, [UseUpdTrigger] = 1, [AuditRatingId]= @AuditRatingId " + "WHERE id=@id"; try { sqlConn.Open(); SqlCommand cmd = new SqlCommand(InsSt, sqlConn); cmd.Parameters.AddWithValue("@passPhrase", SqlDBInfo.passPhrase); cmd.Parameters.AddWithValue("@id", audit.Id); cmd.Parameters.AddWithValue("@Year", audit.Year); cmd.Parameters.AddWithValue("@CompanyID", audit.CompanyId); cmd.Parameters.AddWithValue("@AuditTypeID", audit.AuditTypeId); cmd.Parameters.AddWithValue("@Title", audit.Title); cmd.Parameters.AddWithValue("@ReportDt", audit.ReportDt.Date); cmd.Parameters.AddWithValue("@Auditor1ID", audit.Auditor1ID); if (audit.Auditor2ID == null) { cmd.Parameters.AddWithValue("@Auditor2ID", DBNull.Value); } else { cmd.Parameters.AddWithValue("@Auditor2ID", audit.Auditor2ID); } if (audit.SupervisorID == null) { cmd.Parameters.AddWithValue("@SupervisorID", DBNull.Value); } else { cmd.Parameters.AddWithValue("@SupervisorID", audit.SupervisorID); } if (audit.AuditRatingId == null) { cmd.Parameters.AddWithValue("@AuditRatingId", DBNull.Value); } else { cmd.Parameters.AddWithValue("@AuditRatingID", audit.AuditRatingId); } cmd.Parameters.AddWithValue("@IsCompleted", audit.IsCompleted); cmd.Parameters.AddWithValue("@AuditNumber", audit.AuditNumber); cmd.Parameters.AddWithValue("@IASentNumber", audit.IASentNumber); //cmd.Parameters.AddWithValue("@InsUserID", user.Id); cmd.Parameters.AddWithValue("@UpdUserID", UserInfo.userDetails.Id); cmd.CommandType = CommandType.Text; int rowsAffected = cmd.ExecuteNonQuery(); if (rowsAffected > 0) { ret = true; } } catch (Exception ex) { MessageBox.Show("The following error occurred: " + ex.Message); } sqlConn.Close(); return(ret); }
public override int SaveChanges() { var audit = new Audit(); audit.CreatedBy = Principal?.Name;
private static void AddModifiedAuditingData(Audit entity, string userId) { entity.ModifiedDateTime = DateTimeOffset.UtcNow; entity.ModifiedBy = userId; }
public void AddToAudits(Audit audit) { base.AddObject("Audits", audit); }
protected void btnSave_Click(object sender, EventArgs e) { Page.Validate(); if (Page.IsValid) { try { //creating user if (ddlARC.SelectedValue == "-1") { string script = "alertify.alert('" + ltrSelectARC.Text + "');"; ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", script, true); MaintainScrollPositionOnPostBack = false; return; } var checkedroles = (from ListItem item in Chkboxroles.Items where item.Selected select item.Value).ToList(); if (!checkedroles.Any()) { string script = "alertify.alert('" + ltrSelectRole.Text + "');"; ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", script, true); MaintainScrollPositionOnPostBack = false; return; } string username = ""; if (Session[enumSessions.UserIdToUpdate.ToString()] == null) { txtuname.Enabled = true; if (!string.IsNullOrEmpty(txtpwd.Text.ToString().Trim()) && !string.IsNullOrEmpty(Txtuemail.Text.ToString().Trim()) && !string.IsNullOrEmpty(txtuname.Text.ToString().Trim())) { username = txtuname.Text.ToString().Trim(); string password = txtpwd.Text.ToString().Trim(); string Emailid = Txtuemail.Text.ToString().Trim(); string question = ddlSecurityQuestion.SelectedValue; string answer = txtAnswer.Text.ToString().Trim(); MembershipCreateStatus res; MembershipUser usr = Membership.CreateUser(username, password, Emailid, question, answer, ChkBoxIsapproved.Checked, out res); if (usr == null) { string script = "alertify.alert('" + res.ToString() + "');"; ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", script, true); return; } else { Session[enumSessions.UserIdToUpdate.ToString()] = new Guid(usr.ProviderUserKey.ToString()); string script = "alertify.alert('User " + txtuname.Text + " created successfully.');"; ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", script, true); MaintainScrollPositionOnPostBack = false; } } } //updating user else { if (!string.IsNullOrEmpty(Txtuemail.Text.ToString().Trim()) && !string.IsNullOrEmpty(txtuname.Text.ToString().Trim())) { txtuname.Enabled = false; username = txtuname.Text.ToString().Trim(); string password = txtpwd.Text.ToString().Trim(); string Emailid = Txtuemail.Text.ToString().Trim(); string question = ddlSecurityQuestion.SelectedValue; string answer = txtAnswer.Text.ToString().Trim(); MembershipUser user; user = Membership.GetUser(new Guid(Session[enumSessions.UserIdToUpdate.ToString()].ToString())); db = new LinqToSqlDataContext(); if (ChkBoxIsBlocked.Checked == false) { user.UnlockUser(); } var usrDtls = db.USP_GetUserDetailsByUserId(Session[enumSessions.UserIdToUpdate.ToString()].ToString()).FirstOrDefault(); // string cur_pwd = user.GetPassword(usrDtls.PasswordAnswer); // user.ChangePasswordQuestionAndAnswer(cur_pwd, question, answer); if (!string.IsNullOrEmpty(txtpwd.Text.ToString())) { user.ChangePassword(Membership.Provider.ResetPassword(username, usrDtls.PasswordAnswer), txtpwd.Text); // user.ChangePassword(cur_pwd, txtpwd.Text.ToString().Trim()); } user.Email = Emailid.Trim(); Boolean approved = true; if (ChkBoxIsapproved.Checked) { approved = true; } else { approved = false; } user.IsApproved = approved; Membership.UpdateUser(user); //deleting old existing roles of this user string[] adminroles = (from a in db.ApplicationSettings where a.KeyName == enumApplicationSetting.WebsiteAdminRoles.ToString() select a.KeyValue).SingleOrDefault().Split(','); var Rls = Roles.GetAllRoles().Except(adminroles).ToList(); foreach (string Urole in Rls) { if (Roles.IsUserInRole(txtuname.Text.ToString(), Urole)) { Roles.RemoveUserFromRole(txtuname.Text.ToString(), Urole); } } //deleting old existing arcs of this user db = new LinqToSqlDataContext(); var delarc = db.ARC_User_Maps.Where(item => item.UserId == new Guid(Session[enumSessions.UserIdToUpdate.ToString()].ToString())); db.ARC_User_Maps.DeleteAllOnSubmit(delarc); db.SubmitChanges(); string script = "alertify.alert('User " + txtuname.Text + " updated successfully.');"; ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", script, true); MaintainScrollPositionOnPostBack = false; } } string roleslist = string.Empty; //inserting checked roles for (int i = 0; i <= Chkboxroles.Items.Count - 1; i++) { if (Chkboxroles.Items[i].Selected == true) { Roles.AddUserToRole(txtuname.Text.ToString(), Chkboxroles.Items[i].Value.ToString()); roleslist += Chkboxroles.Items[i].Value.ToString() + ","; } } //inserting checked arcs of this user ARC_User_Map acm; if (ddlARC.SelectedValue != "-1" && ddlARC.SelectedValue != null) { db = new LinqToSqlDataContext(); acm = new ARC_User_Map(); acm.UserId = new Guid(Session[enumSessions.UserIdToUpdate.ToString()].ToString()); acm.ARCId = Convert.ToInt32(ddlARC.SelectedValue); db.ARC_User_Maps.InsertOnSubmit(acm); db.SubmitChanges(); int orderId = (from o in db.Orders where o.UserId == acm.UserId && o.ARCId != acm.ARCId && o.OrderStatusId == 1 select o.OrderId).SingleOrDefault(); if (orderId > 0) { db.USP_DeleteOrderwithDetails(orderId); } } pnluserdetails.Visible = false; pnluserlist.Visible = true; Audit audit = new Audit(); audit.UserName = Session[enumSessions.User_Name.ToString()].ToString(); audit.ChangeID = Convert.ToInt32(enumAudit.Manage_User); audit.CreatedOn = DateTime.Now; audit.Notes = "UserName: "******", Email: " + Txtuemail.Text + ", ARC: " + ddlARC.SelectedItem + ", IsApproved: " + ChkBoxIsapproved.Checked + ", IsBlocked:" + ChkBoxIsBlocked.Checked + ", Roles:" + roleslist; if (Request.ServerVariables["LOGON_USER"] != null) { audit.WindowsUser = Request.ServerVariables["LOGON_USER"]; } audit.IPAddress = Request.UserHostAddress; db.Audits.InsertOnSubmit(audit); db.SubmitChanges(); LoadData(); MaintainScrollPositionOnPostBack = false; } catch (Exception objException) { if (objException.Message.Trim() == "The E-mail supplied is invalid.") { string script = "alertify.alert('" + ltrEmailExists.Text + "');"; ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", script, true); } db = new CSLOrderingARCBAL.LinqToSqlDataContext(); db.USP_SaveErrorDetails(Request.Url.ToString(), "btnSave_Click", Convert.ToString(objException.Message), Convert.ToString(objException.InnerException), Convert.ToString(objException.StackTrace), "", HttpContext.Current.Request.UserHostAddress, false, Convert.ToString(HttpContext.Current.Session[enumSessions.User_Id.ToString()])); } } else { string script = "alertify.alert('" + ltrFill.Text + "');"; ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", script, true); MaintainScrollPositionOnPostBack = false; } }
public void WriteFieldOmitted(BondDataType dataType, ushort id, Metadata metadata) { // Simple doesn't support omitting fields so instead we write the default value Audit.ArgRule(!metadata.default_value.nothing, "Field set to nothing can't be serialized."); switch (dataType) { case BondDataType.BT_BOOL: WriteBool(0 != metadata.default_value.uint_value); break; case BondDataType.BT_UINT8: WriteUInt8((byte)metadata.default_value.uint_value); break; case BondDataType.BT_UINT16: WriteUInt16((UInt16)metadata.default_value.uint_value); break; case BondDataType.BT_UINT32: WriteUInt32((UInt32)metadata.default_value.uint_value); break; case BondDataType.BT_UINT64: WriteUInt64(metadata.default_value.uint_value); break; case BondDataType.BT_FLOAT: WriteFloat((float)metadata.default_value.double_value); break; case BondDataType.BT_DOUBLE: WriteDouble(metadata.default_value.double_value); break; case BondDataType.BT_STRING: WriteString(metadata.default_value.string_value); break; case BondDataType.BT_LIST: case BondDataType.BT_SET: case BondDataType.BT_MAP: WriteContainerBegin(0, dataType); break; case BondDataType.BT_INT8: WriteInt8((sbyte)metadata.default_value.int_value); break; case BondDataType.BT_INT16: WriteInt16((Int16)metadata.default_value.int_value); break; case BondDataType.BT_INT32: WriteInt32((Int32)metadata.default_value.int_value); break; case BondDataType.BT_INT64: WriteInt64(metadata.default_value.int_value); break; case BondDataType.BT_WSTRING: WriteWString(metadata.default_value.wstring_value); break; default: Throw.InvalidBondDataType(dataType); break; } }
public static VerejnaZakazkaSearchData SimpleSearch( VerejnaZakazkaSearchData search, AggregationContainerDescriptor <VerejnaZakazka> anyAggregation = null, bool logError = true, bool fixQuery = true, ElasticClient client = null, bool withHighlighting = false) { if (client == null) { client = HlidacStatu.Lib.ES.Manager.GetESClient_VZ(); } string query = search.Q ?? ""; int page = search.Page - 1; if (page < 0) { page = 0; } AggregationContainerDescriptor <VerejnaZakazka> baseAggrDesc = null; baseAggrDesc = anyAggregation == null ? null //new AggregationContainerDescriptor<VerejnaZakazka>().Sum("sumKc", m => m.Field(f => f.Castka)) : anyAggregation; Func <AggregationContainerDescriptor <VerejnaZakazka>, AggregationContainerDescriptor <VerejnaZakazka> > aggrFunc = (aggr) => { return(baseAggrDesc); }; Devmasters.DT.StopWatchEx sw = new Devmasters.DT.StopWatchEx(); sw.Start(); if (fixQuery) { search.OrigQuery = query; query = Lib.Searching.Tools.FixInvalidQuery(query, queryShorcuts, queryOperators); } search.Q = query; ISearchResponse <VerejnaZakazka> res = null; try { res = client .Search <VerejnaZakazka>(s => s .Size(search.PageSize) .Source(so => so.Excludes(ex => ex.Field("dokumenty.plainText"))) .From(page * search.PageSize) .Query(q => GetSimpleQuery(search)) .Sort(ss => GetSort(search.Order)) .Aggregations(aggrFunc) .Highlight(h => Lib.Searching.Tools.GetHighlight <VerejnaZakazka>(withHighlighting)) .TrackTotalHits(search.ExactNumOfResults || page * search.PageSize == 0 ? true : (bool?)null) ); if (withHighlighting && res.Shards != null && res.Shards.Failed > 0) //if some error, do it again without highlighting { res = client .Search <VerejnaZakazka>(s => s .Size(search.PageSize) .Source(so => so.Excludes(ex => ex.Field("dokumenty.plainText"))) .From(page * search.PageSize) .Query(q => GetSimpleQuery(search)) .Sort(ss => GetSort(search.Order)) .Aggregations(aggrFunc) .Highlight(h => Lib.Searching.Tools.GetHighlight <VerejnaZakazka>(false)) .TrackTotalHits(search.ExactNumOfResults || page * search.PageSize == 0 ? true : (bool?)null) ); } } catch (Exception e) { Audit.Add(Audit.Operations.Search, "", "", "VerejnaZakazka", "error", search.Q, null); if (res != null && res.ServerError != null) { Lib.ES.Manager.LogQueryError <VerejnaZakazka>(res, "Exception, Orig query:" + search.OrigQuery + " query:" + search.Q + "\n\n res:" + search.ElasticResults.ToString() , ex: e); } else { HlidacStatu.Util.Consts.Logger.Error("", e); } throw; } sw.Stop(); Audit.Add(Audit.Operations.Search, "", "", "VerejnaZakazka", res.IsValid ? "valid" : "invalid", search.Q, null); if (res.IsValid == false && logError) { Lib.ES.Manager.LogQueryError <VerejnaZakazka>(res, "Exception, Orig query:" + search.OrigQuery + " query:" + search.Q + "\n\n res:" + search.ElasticResults?.ToString() ); } search.Total = res?.Total ?? 0; search.IsValid = res?.IsValid ?? false; search.ElasticResults = res; search.ElapsedTime = sw.Elapsed; return(search); }
public void Run() { try { /**** Common vars shared between different snippets: modify the following input according to your testing server *****/ Guid objectId = new Guid("8e3b3738-2f5f-494d-bde1-fac15da28c86"); Guid id1 = objectId; Guid id2 = new Guid("01e025e8-0fb3-59da-a9b8-2f238c6f011c"); // Common objects are mocked to do not waste precious roundtrip time on each snippet List <Command> commands = new List <Command> { new Command { CommandId = "Adjust" }, new Command { CommandId = "OperatorOverride" }, new Command(), new Command(), new Command { CommandId = "Release" } }; MetasysObject building = new MetasysObject { Id = new Guid("2f321415-35d9-5c48-b643-60c5132cc001") }; MetasysObject sampleEquipment = new MetasysObject { Id = new Guid("0e8c034b-1586-5ed9-8455-dd33e99c2c7e") }; MetasysObject device = new MetasysObject { Id = new Guid("21c605fb-4755-5d65-8e9f-4fc8283b0366") }; AlarmFilter alarmFilter = new AlarmFilter { StartTime = new DateTime(2020, 06, 01), EndTime = new DateTime(2020, 07, 10), ExcludeAcknowledged = true }; Alarm alarm = new Alarm { Id = new Guid("f1a17676-f421-4649-80a5-b13935ae7404") }; AuditFilter auditFilter = new AuditFilter { StartTime = new DateTime(2020, 06, 01), EndTime = new DateTime(2020, 06, 24), OriginApplications = OriginApplicationsEnum.SystemSecurity | OriginApplicationsEnum.AuditTrails, ActionTypes = ActionTypeEnum.Subsystem | ActionTypeEnum.Command }; Audit audit = new Audit { Id = new Guid("f798591b-e6d6-441f-8f7b-596fc2e6c003") }; Audit auditForAnnotation = new Audit { Id = new Guid("f179a59c-ce36-47e1-afa6-f873b80259ed") }; /********************************************************************************************************************/ var option = ""; while (option != "99") { PrintMenu(); Console.Write("\r\nSelect an option: "); option = Console.ReadLine(); Console.WriteLine(); switch (option) { case "1": TryLogin_Refresh(); break; case "2": GetObjectIdentifier(); break; case "3": ReadProperty(objectId); break; case "4": ReadPropertyMultiple(id1, id2); break; case "5": WriteProperty(); break; case "6": WritePropertyMultiple(id1, id2); break; case "7": GetCommands(objectId); break; case "8": SendCommands(objectId, commands); break; case "9": GetNetworkDeviceTypes_GetNetworkDevices(); break; case "10": GetObjects(); break; case "11": Localize(); break; case "12": GetSpaces(); break; case "13": GetSpaceTypes(); break; case "14": GetEquipment(); break; case "15": GetSpaceEquipment_GetSpaceChildren(building); break; case "16": GetEquipmentPoints(sampleEquipment); break; case "17": GetAlarms(); break; case "18": GetSingleAlarm_GetAlarmsForAnObject_GetAlarmsForNetworkDevice(alarm, objectId, alarmFilter, device); break; case "19": GetAlarmsAnnotation(alarm); break; case "20": GetTrendedAttributes_GetSamples(); break; case "21": GetAudits(); break; case "22": GetSingleAudit_GetAuditsForAnObject(audit, objectId, auditFilter); break; case "23": GetAuditsAnnotation(audit); break; case "24": DiscardSingleAudit(audit); break; case "25": ChangeApiVersion(); break; case "26": ChangeHostname(); break; case "27": AddAuditAnnotation(auditForAnnotation); break; case "28": AddAuditAnnotationMultiple(); break; case "29": DiscardAuditMultiple(); break; case "30": GetServerTime(); break; case "99": return; // Exit from JSON output demo } Console.WriteLine(); Console.WriteLine("Press Enter to return to the JSON output menu..."); Console.ReadLine(); Console.WriteLine(); } } catch (Exception exception) { log.Logger.Error(string.Format("{0}", exception.Message)); Console.WriteLine("\n \nAn Error occurred. Press Enter to return to Main Menu"); Console.ReadLine(); } }
public static ISearchResponse <object> _searchData(DataSet ds, string queryString, int page, int pageSize, string sort = null, bool excludeBigProperties = true, bool withHighlighting = false, bool exactNumOfResults = false) { SortDescriptor <object> sortD = new SortDescriptor <object>(); if (sort == "0") { sort = null; } if (!string.IsNullOrEmpty(sort)) { if (sort.EndsWith(DataSearchResult.OrderDesc) || sort.ToLower().EndsWith(DataSearchResult.OrderDescUrl)) { sort = sort.Replace(DataSearchResult.OrderDesc, "").Replace(DataSearchResult.OrderDescUrl, "").Trim(); sortD = sortD.Field(sort, SortOrder.Descending); } else { sort = sort.Replace(DataSearchResult.OrderAsc, "").Replace(DataSearchResult.OrderAscUrl, "").Trim(); sortD = sortD.Field(sort, SortOrder.Ascending); } } Nest.ElasticClient client = Lib.ES.Manager.GetESClient(ds.DatasetId, idxType: ES.Manager.IndexType.DataSource); QueryContainer qc = GetSimpleQuery(ds, queryString); //QueryContainer qc = null; //if (queryString == null) // qc = new QueryContainerDescriptor<object>().MatchNone(); //else if (string.IsNullOrEmpty(queryString)) // qc = new QueryContainerDescriptor<object>().MatchAll(); //else //{ // qc = new QueryContainerDescriptor<object>() // .QueryString(qs => qs // .Query(queryString) // .DefaultOperator(Operator.And) // ); //} page = page - 1; if (page < 0) { page = 0; } if (page * pageSize > Lib.Data.Smlouva.Search.MaxResultWindow) { page = (Lib.Data.Smlouva.Search.MaxResultWindow / pageSize) - 1; } //exclude big properties from result var maps = excludeBigProperties ? ds.GetMappingList("DocumentPlainText").ToArray() : new string[] { }; var res = client .Search <object>(s => s .Size(pageSize) .Source(ss => ss.Excludes(ex => ex.Fields(maps))) .From(page * pageSize) .Query(q => qc) .Sort(ss => sortD) .Highlight(h => Lib.Searching.Tools.GetHighlight <Object>(withHighlighting)) .TrackTotalHits(exactNumOfResults ? true : (bool?)null) ); //fix Highlighting for large texts if (withHighlighting && res.Shards != null && res.Shards.Failed > 0) //if some error, do it again without highlighting { res = client .Search <object>(s => s .Size(pageSize) .Source(ss => ss.Excludes(ex => ex.Fields(maps))) .From(page * pageSize) .Query(q => qc) .Sort(ss => sortD) .Highlight(h => Lib.Searching.Tools.GetHighlight <Object>(false)) .TrackTotalHits(exactNumOfResults ? true : (bool?)null) ); } Audit.Add(Audit.Operations.Search, "", "", "Dataset." + ds.DatasetId, res.IsValid ? "valid" : "invalid", queryString, null); return(res); }
/// <summary> /// Initializes a new instance of the <see cref="ContextItem" /> class. /// </summary> /// <param name="entity">The entity.</param> /// <param name="dbEntityEntry">The database entity entry.</param> public ContextItem( IEntity entity, DbEntityEntry dbEntityEntry ) { Entity = entity; DbEntityEntry = dbEntityEntry; Audit = new Audit(); switch ( dbEntityEntry.State ) { case EntityState.Added: { Audit.AuditType = AuditType.Add; break; } case EntityState.Deleted: { Audit.AuditType = AuditType.Delete; break; } case EntityState.Modified: { Audit.AuditType = AuditType.Modify; break; } } }
public override IAudit ToModel() { var client = new Client { Id = CarrierId }; var requestedByUser = new User { Id = RequestedBy }; var agent = new Agent { Name = AgentName, Company = AgentCompany, Phone = AgentPhone, Email = AgentEmail, Address = new Address { Line1 = AgentAddress, Line2 = AgentAddress2, City = AgentCity, State = AgentState, Zipcode = AgentZip } }; var policy = new Policy { Agent = agent, Client = client, Address = new Address { Line1 = PolicyAddress, Line2 = PolicyAddress2, City = PolicyCity, State = PolicyState, Zipcode = PolicyZip }, EffectiveStart = PolicyStart, EffectiveEnd = PolicyEnd, PolicyNumber = PolicyNumber, Email = PolicyEmail, Phone = PolicyPhone, InsuredName = InsuredName, CompanyName = CompanyName }; var model = new Audit { Id = AuditId, AssignmentNumber = AuditId, RequestedBy = requestedByUser, RequestedOn = RequestDate, Policy = policy, DueDate = DueDate, AuditType = (AuditTypeEnum)AuditType, AuditFrequency = (AuditFrequencyEnum)AuditFreq, AuditPeriod = AuditPeriod, ByLocation = ByLocation, //Split = Split, AuditStatus = (AuditStatuses)AuditStatus, //PercentComplete = PercentComplete, //InvoiceID = InvoiceID, //CompleteDate = CompleteDate, //MasterAuditID = MasterAuditID, //AuditPeriod = AuditPeriod, //HasChild = HasChild, //PHPercentComplete = PHPercentComplete, //PHCompletedBy = PHCompletedBy, //PHCompletedByPhone = PHCompletedByPhone, //PHComments = PHComments, CheckedForQualityControl = IsQcChecked, //QCTimeStamp = QCTimeStamp, //IsQCComplete = IsQCComplete, //IsLastChild = IsLastChild, //IsRolledUp = IsRolledUp, //PHStartDate = PHStartDate, //QCCompleteDate = QCCompleteDate, //TotalHoursWorked = TotalHoursWorked, AuditMethod = OrderType == "e-Audit" ? AuditMethods.eAudit : AuditMethods.ShareAudit, AuditorId = AssignedToID, //HasActivity = HasActivity, //TotalHoursPaid = TotalHoursPaid, //IsBillable = IsBillable, AssignedOn = AssignedDate, //RecordsReceived = RecordsReceived, //RecordsComplete = RecordsComplete, //SpecialInstructions = SpecialInstructions, //IsReorder = IsReorder, //IsReopen = IsReopen, //IsDispute = IsDispute, //OriginalAuditID = OriginalAuditID, //ReorderedToAuditID = ReorderedToAuditID, //PHBestTimeToContact = PHBestTimeToContact, //PHDateOfBirth = PHDateOfBirth, //CarrierOrderNumber = CarrierOrderNumber, //QCReviewerID = QCReviewerID }; // Audit Frequency maybe in the Special Instructions due to incompetency model.AuditFrequency = GetAuditFrequency(model); model.AuditExposureBasis = GetExposureBasis(); return(model); }
//设置审核状态 private void SetAuditStatus(Audit status) { switch (status) { case Audit.All: for (int i = 0; i < this.spgviewAuditControl.Rows.Count; i++) { ((Label)this.spgviewAuditControl.Rows[i].FindControl("LBItem")).Text = "<font color = red>已通过</font>"; ViewState[i.ToString()] = "<font color = red>已通过</font>"; } btnSend.Enabled = true; ViewState["AuditCount"] = this.spgviewAuditControl.Rows.Count; ViewState["AuditFailedCount"] = 0; break; case Audit.None: for (int i = 0; i < this.spgviewAuditControl.Rows.Count; i++) { ((Label)this.spgviewAuditControl.Rows[i].FindControl("LBItem")).Text = "未通过"; ViewState[i.ToString()] = "未通过"; } ViewState["AuditCount"] = 0; ViewState["AuditFailedCount"] = 0; btnSend.Enabled = true; break; case Audit.Normal: int iWaitforAuditCount = 0; int iAuditFailedCount = 0; for (int i = 0; i < this.spgviewAuditControl.Rows.Count; i++) { string strAudit = ViewState[i.ToString()].ToString(); ((Label)this.spgviewAuditControl.Rows[i].FindControl("LBItem")).Text = strAudit; if (strAudit == "待审核") { iWaitforAuditCount++; } if (strAudit == "未通过") { iAuditFailedCount++; } } ViewState["AuditCount"] = spgviewAuditControl.Rows.Count - iWaitforAuditCount - iAuditFailedCount; ViewState["AuditFailedCount"] = iAuditFailedCount; if (iWaitforAuditCount != 0) { btnSend.Enabled = false; } break; case Audit.Init: for (int i = 0; i < this.spgviewAuditControl.Rows.Count; i++) { ((Label)this.spgviewAuditControl.Rows[i].FindControl("LBItem")).Text = "待审核"; ViewState[i.ToString()] = "待审核"; } ViewState["AuditCount"] = 0; ViewState["AuditFailedCount"] = 0; break; } }
public int GetRomsFromZipFile(string filename) { int total = 0; string SHA1; Rom matchedRom; try { using ZipArchive archive = ZipFile.Open(filename, ZipArchiveMode.Read); foreach (ZipArchiveEntry entry in archive.Entries) { using Stream stream = entry.Open(); using MemoryStream memoryStream = new(); int count; do { byte[] buffer = new byte[1024]; count = stream.Read(buffer, 0, 1024); memoryStream.Write(buffer, 0, count); } while (stream.CanRead && count > 0); // TODO Some roms in DB have no SHA1 this is a substantial bug SHA1 = Audit.GetHash(memoryStream, HashOption.SHA1, (int)HeaderLength); matchedRom = Roms.FirstOrDefault(x => SHA1.Equals(x.SHA1, StringComparison.OrdinalIgnoreCase)); if (matchedRom == null && HeaderLength > 0) { SHA1 = Audit.GetHash(memoryStream, HashOption.SHA1, 0); matchedRom = Roms.FirstOrDefault(x => SHA1.Equals(x.SHA1, StringComparison.OrdinalIgnoreCase)); } // Have found a match so do this stuff with it if (matchedRom != null) { // Check that the release has no filename, or the file doesn't yet exist if (string.IsNullOrEmpty(matchedRom.FileName) || !File.Exists(matchedRom.FilePath)) { string extension = Path.GetExtension(entry.Name); matchedRom.StoreFileName(extension); if (File.Exists(matchedRom.FilePath)) { File.Move(matchedRom.FilePath, FileLocation.RomsBackup + matchedRom.FileName); } if (matchedRom.Platform_ID == CONSTANTS.Platform_ID.Lynx) { //TODO: This looks pretty shady string tempFile = "lnxtmp.lyx"; string tempFile2 = "lnxtmp.lnx"; string tempPath = Path.GetDirectoryName(FileLocation.HandyConverter) + @"\" + tempFile; string tempPath2 = Path.GetDirectoryName(FileLocation.HandyConverter) + @"\" + tempFile2; File.Delete(tempPath); File.Delete(tempPath2); entry.ExtractToFile(tempPath); Handy.ConvertLynx(tempFile); File.Move(tempPath, matchedRom.FilePath); } else { entry.ExtractToFile(matchedRom.FilePath); } total += 1; } } } } catch (Exception) { } return(total); }
public Audit Add(Audit newAudit) { return(RepositoryBase <Audit> .Add(newAudit)); }
public bool EditAudit(Audit audit) { _unitOfWork.AuditRepository.Edit(audit); _unitOfWork.Save(); return(true); }
public void Update(Audit newAudit) { RepositoryBase <Audit> .Update(newAudit); }
protected void btnSave_Click(object sender, EventArgs e) { if (Page.IsValid) { try { Audit audit = new Audit(); string notes = null; if (ddlArc.SelectedIndex > 0) { if (gvProducts.Rows.Count > 0) { int retrun = -1; foreach (GridViewRow row in gvProducts.Rows) { Decimal objtxtPrice = -1; DateTime?objtxtExpiryDate = null; Int32 objlblProuctId = Convert.ToInt32((row.FindControl("ProductId") as Label).Text); // get product id if ((row.FindControl("txtPrice") as TextBox).Text.Trim() != "") { objtxtPrice = Convert.ToDecimal((row.FindControl("txtPrice") as TextBox).Text); // get entered Price } if ((row.FindControl("txtExpiryDate") as TextBox).Text.Trim() != "") { objtxtExpiryDate = DateTime.Parse((row.FindControl("txtExpiryDate") as TextBox).Text); // get selected expiry date } if (objtxtPrice > -1 && objtxtExpiryDate != null) { db = new LinqToSqlDataContext(); retrun = db.USP_SaveARCProductPrice(Convert.ToInt32(ddlArc.SelectedValue), objlblProuctId, objtxtPrice, objtxtExpiryDate, Convert.ToString(Session[enumSessions.User_Id.ToString()])); // pass all values to save } notes += "Product: " + objlblProuctId + ", Price: " + objtxtPrice + ", Date: " + objtxtExpiryDate + ", "; } if (retrun == 0) { string script = "alertify.alert('" + ltrProdPriceUpdate.Text + "');"; ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", script, true); } else { string script = "alertify.alert('" + ltrEntered.Text + "');"; ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", script, true); } BindProducts(Convert.ToInt32(ddlArc.SelectedValue.ToString())); // Bind updated price/date with Gridview } else { string script = "alertify.alert('" + ltrNoProdMap.Text + "');"; ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", script, true); } } else { string script = "alertify.alert('" + ltrSelectARC.Text + "');"; ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", script, true); } audit.Notes = "ARC: " + ddlArc.SelectedItem.ToString() + ", " + notes; audit.UserName = Session[enumSessions.User_Name.ToString()].ToString(); audit.ChangeID = Convert.ToInt32(enumAudit.Manage_ARC_Product_Price); audit.CreatedOn = DateTime.Now; if (Request.ServerVariables["LOGON_USER"] != null) { audit.WindowsUser = Request.ServerVariables["LOGON_USER"]; } audit.IPAddress = Request.UserHostAddress; db.Audits.InsertOnSubmit(audit); db.SubmitChanges(); } catch (Exception objException) { db = new CSLOrderingARCBAL.LinqToSqlDataContext(); db.USP_SaveErrorDetails(Request.Url.ToString(), "btnSave_Click", Convert.ToString(objException.Message), Convert.ToString(objException.InnerException), Convert.ToString(objException.StackTrace), "", HttpContext.Current.Request.UserHostAddress, false, Convert.ToString(HttpContext.Current.Session[enumSessions.User_Id.ToString()])); } finally { if (db != null) { db.Dispose(); } } } }
public Audit Create(Audit error) { return(RepositoryBase <Audit> .Add(error)); }
/// <summary> /// Purpose: Grabs all audits /// Accepts: Nothing /// Returns: List<Audit> /// </summary> public List<Audit> GetAllAudits() { List<Audit> audits = new List<Audit>(); try { AuditData data = new AuditData(); List<QSRDataObjects.Audit> dataAudits = data.GetAllAudits(); foreach (QSRDataObjects.Audit a in dataAudits) { Audit audit = new Audit(); audit.AuditID = a.AuditID; audit.AuditTypeID = Convert.ToInt32(a.AuditTypeID); audit.UserID = Convert.ToInt32(a.UserID); audit.AdminID = Convert.ToInt32(a.AdminID); audit.Notes = a.Notes; audit.Created = a.Created; audits.Add(audit); } } catch (Exception ex) { ErrorRoutine(ex, "Audit", "GetAllAudits"); } return audits; }
private void LoadLogsintoElastic(Guid executionId, Guid resourceId, string auditType, string detail, LogLevel eventLevel) { var dependency = new Depends(Depends.ContainerType.AnonymousElasticsearch); var hostName = "http://" + dependency.Container.IP; var port = dependency.Container.Port; var loggerSource = new SerilogElasticsearchSource { Port = port, HostName = hostName, SearchIndex = "warewolftestlogs" }; var uri = new Uri(hostName + ":" + port); var logger = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.Sink(new ElasticsearchSink(new ElasticsearchSinkOptions(uri) { AutoRegisterTemplate = true, IndexDecider = (e, o) => loggerSource.SearchIndex, })) .CreateLogger(); var mockSeriLogConfig = new Mock <ISeriLogConfig>(); mockSeriLogConfig.SetupGet(o => o.Logger).Returns(logger); var mockDataObject = new Mock <IDSFDataObject>(); using (var loggerConnection = loggerSource.NewConnection(mockSeriLogConfig.Object)) { var loggerPublisher = loggerConnection.NewPublisher(); if (eventLevel == LogLevel.Error) { mockDataObject = SetupDataObjectWithAssignedInputsAndError(executionId, resourceId); } else { mockDataObject = SetupDataObjectWithAssignedInputs(executionId, resourceId); } var auditLog = new Audit(mockDataObject.Object, auditType, detail, null, null); //-------------------------Act---------------------------------- switch (eventLevel) { case LogLevel.Debug: loggerPublisher.Debug(GlobalConstants.WarewolfLogsTemplate, auditLog); break; case LogLevel.Warn: loggerPublisher.Warn(GlobalConstants.WarewolfLogsTemplate, auditLog); break; case LogLevel.Fatal: loggerPublisher.Fatal(GlobalConstants.WarewolfLogsTemplate, auditLog); break; case LogLevel.Error: loggerPublisher.Error(GlobalConstants.WarewolfLogsTemplate, auditLog); break; default: loggerPublisher.Info(GlobalConstants.WarewolfLogsTemplate, auditLog); break; } } Task.Delay(225).Wait(); }
public ModelScorePageHandler( DataBrowser owner, Uri url, Audit.ModelScore obj ) : base(owner, url, obj) { }
public void CreateRecord(Audit record) { Create(record); }