public async Task <IActionResult> PutDatabaseLog([FromRoute] int id, [FromBody] DatabaseLog databaseLog) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != databaseLog.DatabaseLogId) { return(BadRequest()); } _context.Entry(databaseLog).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!DatabaseLogExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public questStatus Update(DbMgrTransaction trans, Quest.Functional.MasterPricing.Database database) { // Initialize questStatus status = null; bool bCreateTransaction = trans == null; // Perform update in this transaction. status = update((MasterPricingEntities)trans.DbContext, database); if (bLogging) { DatabaseLog databaseLog = new DatabaseLog(); databaseLog.Name = database.Name == null ? "(null)" : database.Name; databaseLog.Event = "UPDATE"; databaseLog.Data = status.ToString(); DatabaseLogId databaseLogId = null; _dbDatabaseLogsMgr.Create(databaseLog, out databaseLogId); } if (!questStatusDef.IsSuccess(status)) { RollbackTransaction(trans); return(status); } return(new questStatus(Severity.Success)); }
public override void OnException(ExceptionContext context) { var user = context.HttpContext.User.Identity.Name ?? GlobalConstants.Anonymous; var exceptionMethod = context.Exception.TargetSite; var trace = context.Exception.StackTrace; var exception = context.Exception.GetType().Name; var time = DateTime.UtcNow.ToLongDateString(); string message = $"Occurence: {time} User: {user} Path:{exceptionMethod} Trace: {trace}"; var log = new DatabaseLog { Content = message, Handled = false, LogType = exception }; this.Context.Logs.Add(log); this.Context.SaveChanges(); context.ExceptionHandled = true; context.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Home" }, { "action", "Error" }, { "area", "" } }); }
//Handling exception...^^ public T ToOrDefault <T>(DataRow row, string columnName) where T : IConvertible { try { return((T)Convert.ChangeType(row[columnName], typeof(T), CultureInfo.InvariantCulture)); } catch (InvalidCastException ex) { DatabaseLog.Write(ex, "Invalid cast (ColumName {0} : {1})", columnName, row[columnName]); } catch (FormatException ex) { DatabaseLog.Write(ex, "Invalid Format (ColumName {0} : {1})", columnName, row[columnName]); } catch (OverflowException ex) { DatabaseLog.Write(ex, "Overflowed (ColumName {0} : {1})", columnName, row[columnName]); } catch (ArgumentException ex) { DatabaseLog.Write(ex, "Invalid Argument (ColumName {0} : {1})", columnName, row[columnName]); } return(default(T)); }
public LogManager Creator(LogType logTipi) { LogManager lm = null; switch (logTipi) { case LogType.DatabaseLog: lm = new DatabaseLog(); break; case LogType.MailLog: lm = new MailLog(); break; case LogType.TxtLog: lm = new TxtLog(); break; case LogType.XmlLog: lm = new XmlLog(); break; default: return(null); } return(lm); }
private bool CreateSnapshot(string snapshot) { if (snapshot.ToLower() == "service") { Log("Not allowed to create Service snapshot.", true); return(false); } bool result = true; if (mTesting == false) { Log("Creating snapshot " + snapshot, true); StopHeartbeatTimer(); PowerCLI powerCLI = PowerCLI.Instance(mNetworkCredentials); result = powerCLI.CreateSnapshot(mData.VMName, snapshot, mLogFile); if (result == false) { DatabaseLog.Insert("CreateSnapshot failed on VM " + mData.VMName, "There might be an issue with PowerCLI. Please check the logs.", 1); } StartHeartbeatTimer(); } return(result); }
public static async Task <List <MediaMetadata> > GetAllMetadatasAsync(this MediaMetaDatabaseContext context) { List <MediaMetaJson> metaJsons = null; using (new DisposableLogger( DatabaseLog.QueryBegin, (sw) => DatabaseLog.QueryEnd(sw, metaJsons?.Count ?? 0) )) { // Get all MediaMetaJsons from database using this LINQ query. metaJsons = await context.MediaMetaJsons .Include(j => j.Labels) .ToListAsync(); } var metas = new List <MediaMetadata>(); using (new DisposableLogger( DatabaseLog.DeserializationBegin, (sw) => DatabaseLog.DeserializationEnd(sw, metas?.Count ?? 0) )) { // Deserialize the JSON data in each MediaMetaJson object into a MediaMetadata object and add it to metas. foreach (var metaJson in metaJsons) { var meta = await Task.Run(() => JsonConvert.DeserializeObject <MediaMetadata>(metaJson.Json)); meta.Labels = new ObservableCollection <Label>(metaJson.Labels); metas.Add(meta); } } return(metas); }
private questStatus delete(MasterPricingEntities dbContext, Quest.Functional.MasterPricing.DatabaseId databaseId) { // Initialize questStatus status = null; try { // Read the record. Quest.Services.Dbio.MasterPricing.Databases _database = null; status = read(dbContext, databaseId, out _database); if (!questStatusDef.IsSuccess(status)) { if (bLogging) { DatabaseLog databaseLog = new DatabaseLog(); databaseLog.Name = "Database.Id=" + databaseId.Id; databaseLog.Event = "DELETE"; databaseLog.Data = status.ToString(); DatabaseLogId databaseLogId = null; _dbDatabaseLogsMgr.Create(databaseLog, out databaseLogId); } return(status); } // Delete the record. dbContext.Databases.Remove(_database); dbContext.SaveChanges(); } catch (DbEntityValidationException ex) { var errorMessages = ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage); String fullErrorMessage = string.Join("; ", errorMessages); String exceptionMessage = string.Concat(ex.Message, fullErrorMessage); status = new questStatus(Severity.Fatal, String.Format("EXCEPTION: {0}.{1}: {2}", this.GetType().Name, MethodBase.GetCurrentMethod().Name, exceptionMessage)); LogException(ex, status); return(status); } catch (System.Exception ex) { status = new questStatus(Severity.Fatal, String.Format("EXCEPTION: {0}.{1}: {2}", this.GetType().Name, MethodBase.GetCurrentMethod().Name, ex.InnerException != null ? ex.InnerException.Message : ex.Message)); LogException(ex, status); return(status); } status = new questStatus(Severity.Success, "Database successfully deleted. Database.Id=" + databaseId.Id); if (bLogging) { DatabaseLog databaseLog = new DatabaseLog(); databaseLog.Name = "Database.Id=" + databaseId.Id; databaseLog.Event = "DELETE"; databaseLog.Data = status.ToString(); DatabaseLogId databaseLogId = null; _dbDatabaseLogsMgr.Create(databaseLog, out databaseLogId); } return(status); }
/*================================================================================================================================== * Public Methods *=================================================================================================================================*/ public questStatus Create(Quest.Functional.MasterPricing.Database database, out Quest.Functional.MasterPricing.DatabaseId databaseId) { // Initialize questStatus status = null; databaseId = null; // Data rules. // Create the database using (MasterPricingEntities dbContext = new MasterPricingEntities()) { status = create(dbContext, database, out databaseId); if (bLogging) { DatabaseLog databaseLog = new DatabaseLog(); databaseLog.Name = database.Name == null ? "(null)" : database.Name; databaseLog.Event = "CREATE"; databaseLog.Data = status.ToString(); DatabaseLogId databaseLogId = null; _dbDatabaseLogsMgr.Create(databaseLog, out databaseLogId); } if (!questStatusDef.IsSuccess(status)) { return(status); } } return(new questStatus(Severity.Success)); }
/*================================================================================================================================== * Public Methods *=================================================================================================================================*/ #region Logging /*---------------------------------------------------------------------------------------------------------------------------------- * Logging *---------------------------------------------------------------------------------------------------------------------------------*/ public questStatus LogDatabaseEvent(DatabaseLog databaseLog) { // TODO: REFACTOR USING DbLogsMgr // Initialize questStatus status = null; // Check if logging on. if (!this._logSetting.bLogDatabases) { return(new questStatus(Severity.Warning, "Database Logging OFF")); } // Log event DatabaseLogId databaseLogId = null; status = _dbDatabaseLogsMgr.Create(databaseLog, out databaseLogId); if (!questStatusDef.IsSuccess(status)) { return(status); } databaseLog.Id = databaseLogId.Id; return(new questStatus(Severity.Success)); }
/// <summary> /// Deep load all DatabaseLog children. /// </summary> private void Step_03_DeepLoad_Generated() { using (TransactionManager tm = CreateTransaction()) { int count = -1; mock = CreateMockInstance(tm); mockCollection = DataRepository.DatabaseLogProvider.GetPaged(tm, 0, 10, out count); DataRepository.DatabaseLogProvider.DeepLoading += new EntityProviderBaseCore <DatabaseLog, DatabaseLogKey> .DeepLoadingEventHandler( delegate(object sender, DeepSessionEventArgs e) { if (e.DeepSession.Count > 3) { e.Cancel = true; } } ); if (mockCollection.Count > 0) { DataRepository.DatabaseLogProvider.DeepLoad(tm, mockCollection[0]); System.Console.WriteLine("DatabaseLog instance correctly deep loaded at 1 level."); mockCollection.Add(mock); // DataRepository.DatabaseLogProvider.DeepSave(tm, mockCollection); } //normally one would commit here //tm.Commit(); //IDisposable will Rollback Transaction since it's left uncommitted } }
/// <summary> /// 数据库查询 /// </summary> /// <param name="sql"></param> /// <returns>结果集</returns> public static DataTable Select(string sql) { MySqlConnection Conn = dbConn; DataTable dtResult = null; MySqlCommand Cmd = null; MySqlDataAdapter Adapt = null; DataSet Ds = null; for (int i = 0; i <= ConnTimes; i++) { try { Cmd = new MySqlCommand(sql, Conn); Cmd.CommandType = CommandType.Text; Adapt = new MySqlDataAdapter(Cmd); Ds = new DataSet(); Adapt.Fill(Ds); dtResult = Ds.Tables[0]; break; } catch (MySqlException e) { string LogCont = "错误信息:" + e.Message.Trim() + ",错误语句:" + sql + ",错误时间:" + System.DateTime.Now.ToString().Trim() + "\r\n"; DatabaseLog.WriteLog(LogCont); if (MessageBox.Show("当前数据库连接失败,您是否尝试重新连接?\r\n 点击“是”继续连接;点击“否”退出系统。", "", MessageBoxButtons.YesNo) == DialogResult.No) { Environment.Exit(0); } else { if (i >= ConnTimes) { MessageBox.Show("已经超过最大连接次数,点击确定后退出!"); Environment.Exit(0); } else { Connect(); } } } finally { if (Cmd != null) { Cmd.Dispose(); } if (Adapt != null) { Adapt.Dispose(); } if (Ds != null) { Ds.Dispose(); } } } return(dtResult); }
public async Task <IActionResult> Edit(int id, [Bind("DatabaseLogId,PostTime,DatabaseUser,Event,Schema,Object,Tsql,XmlEvent")] DatabaseLog databaseLog) { if (id != databaseLog.DatabaseLogId) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(databaseLog); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!DatabaseLogExists(databaseLog.DatabaseLogId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(databaseLog)); }
/// <summary> /// Test Find using the Query class /// </summary> private void Step_30_TestFindByQuery_Generated() { using (TransactionManager tm = CreateTransaction()) { //Insert Mock Instance DatabaseLog mock = CreateMockInstance(tm); bool result = DataRepository.DatabaseLogProvider.Insert(tm, mock); Assert.IsTrue(result, "Could Not Test FindByQuery, Insert Failed"); DatabaseLogQuery query = new DatabaseLogQuery(); query.AppendEquals(DatabaseLogColumn.DatabaseLogId, mock.DatabaseLogId.ToString()); query.AppendEquals(DatabaseLogColumn.PostTime, mock.PostTime.ToString()); query.AppendEquals(DatabaseLogColumn.DatabaseUser, mock.DatabaseUser.ToString()); query.AppendEquals(DatabaseLogColumn.SafeNameEvent, mock.SafeNameEvent.ToString()); if (mock.Schema != null) { query.AppendEquals(DatabaseLogColumn.Schema, mock.Schema.ToString()); } if (mock.SafeNameObject != null) { query.AppendEquals(DatabaseLogColumn.SafeNameObject, mock.SafeNameObject.ToString()); } query.AppendEquals(DatabaseLogColumn.Tsql, mock.Tsql.ToString()); TList <DatabaseLog> results = DataRepository.DatabaseLogProvider.Find(tm, query); Assert.IsTrue(results.Count == 1, "Find is not working correctly. Failed to find the mock instance"); } }
public IHttpActionResult AddDatabaseByStudent(DatabaseLog db) { try { FileInfo file = new FileInfo(db.DatabasePath); var script = file.OpenText().ReadToEnd(); var sqlqueries = script.Split(new[] { "GO" }, StringSplitOptions.RemoveEmptyEntries); sqlqueries[1] = "CREATE DATABASE [" + "user" + db.UserName + "]"; sqlqueries[2] = "use [" + "user" + db.UserName + "]"; string connectionString = @"Data Source=MALIKKALEEM\SQLEXPRESS01;Initial Catalog=fyp;Integrated Security=True;User ID=sa;Password=l23"; using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); using (SqlCommand cmd = new SqlCommand("query", con)) { foreach (var query in sqlqueries) { cmd.CommandText = query; cmd.ExecuteNonQuery(); } con.Close(); } } return(Ok()); } catch (Exception ex) { return(BadRequest(ex.ToString())); } }
public SQLResult Select(string sql, params object[] parameters) { using (var pClient = GetClient()) { var sqlString = new StringBuilder(); // Fix for floating point problems on some languages sqlString.AppendFormat(CultureInfo.GetCultureInfo("en-US").NumberFormat, sql, parameters); var sqlCommand = new SqlCommand(sqlString.ToString()); try { sqlCommand.Parameters.AddRange(parameters); using (var sqlData = pClient.ExecuteReader(sqlCommand)) { using (var retData = new SQLResult()) { retData.Load(sqlData); retData.Count = retData.Rows.Count; return(retData); } } } catch (SqlException ex) { DatabaseLog.Write(ex, $"Error With Query {sqlCommand.CommandText}"); return(null); } } }
private bool Initialize(string snapshot) { bool result = true; if (mTesting == false) { mBusy = true; // Refresh data in case the VM name has changed..... mData = VMInstanceData.SelectByIP(mData.IPAddress); // Stop the heartbeat timer because rolling it back might cause it to actually miss a heartbeat. StopHeartbeatTimer(); PowerCLI powerCLI = PowerCLI.Instance(mNetworkCredentials); result = powerCLI.RollbackVM(mData.VMName, snapshot, mLogFile); if (result == false) { DatabaseLog.Insert("Rollback failed on VM " + mData.VMName, "There might be an issue with PowerCLI. Please check the logs.", 1); } StartHeartbeatTimer(); mBusy = false; } return(result); }
///<summary> /// Update the Typed DatabaseLog Entity with modified mock values. ///</summary> static public void UpdateMockInstance(TransactionManager tm, DatabaseLog mock) { DatabaseLogTest.UpdateMockInstance_Generated(tm, mock); // make any alterations necessary // (i.e. for DB check constraints, special test cases, etc.) SetSpecialTestData(mock); }
///<summary> /// Update the Typed DatabaseLog Entity with modified mock values. ///</summary> static public void UpdateMockInstance_Generated(TransactionManager tm, DatabaseLog mock) { mock.PostTime = TestUtility.Instance.RandomDateTime(); mock.DatabaseUser = TestUtility.Instance.RandomString(63, false);; mock.SafeNameEvent = TestUtility.Instance.RandomString(63, false);; mock.Schema = TestUtility.Instance.RandomString(63, false);; mock.SafeNameObject = TestUtility.Instance.RandomString(63, false);; mock.Tsql = TestUtility.Instance.RandomString(2, false);; mock.XmlEvent = "<test></test>"; }
/// <summary> /// Check the foreign key dal methods. /// </summary> private void Step_10_FK_Generated() { using (TransactionManager tm = CreateTransaction()) { DatabaseLog entity = CreateMockInstance(tm); bool result = DataRepository.DatabaseLogProvider.Insert(tm, entity); Assert.IsTrue(result, "Could Not Test FK, Insert Failed"); } }
/// <summary> /// Called when released from using() scope - does not actually dispose, just marks as available /// </summary> public void Dispose() { ResetCommand(); Available = true; UpdateLastActivity(); if (ServerMainDebug.DebugSql) { DatabaseLog.Write(DatabaseLogLevel.Debug, "(Sql)Released client " + Id + " for availability."); } }
public static SQLResult Select(DatabaseType pType, string sql, params object[] parameters) { if (DbManagerList.TryGetValue(pType, out var pManager)) { return(pManager.Select(sql, parameters)); } DatabaseLog.Write(DatabaseLogLevel.DatabaseClientError, "Unknown Manager {0}", pType); return(null); }
public static void RunSQL(DatabaseType pType, string sql, params object[] parameter) { if (DbManagerList.TryGetValue(pType, out var pManager)) { pManager.RunSQL(pType, sql, parameter); return; } DatabaseLog.Write(DatabaseLogLevel.DatabaseClientError, "Unknown Manager {0}", pType); }
public async Task <IActionResult> Create([Bind("DatabaseLogId,PostTime,DatabaseUser,Event,Schema,Object,Tsql,XmlEvent")] DatabaseLog databaseLog) { if (ModelState.IsValid) { _context.Add(databaseLog); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(databaseLog)); }
/// <summary> /// Test methods exposed by the EntityHelper class. /// </summary> private void Step_20_TestEntityHelper_Generated() { using (TransactionManager tm = CreateTransaction()) { mock = CreateMockInstance(tm); DatabaseLog entity = mock.Copy() as DatabaseLog; entity = (DatabaseLog)mock.Clone(); Assert.IsTrue(DatabaseLog.ValueEquals(entity, mock), "Clone is not working"); } }
public static void DeleteAllMetadatas(this MediaMetaDatabaseContext context) { var count = context.MediaMetaJsons.Count(); // Time and log deletion. using (new DisposableLogger(DatabaseLog.DeleteBegin, (sw) => DatabaseLog.DeleteEnd(sw, count))) { context.MediaMetaJsons.RemoveRange(context.MediaMetaJsons); context.SaveChanges(); } }
public static void DisposeManager(DatabaseType pType) { if (DbManagerList.TryGetValue(pType, out var pManager)) { pManager.Dispose(); } else { DatabaseLog.Write(DatabaseLogLevel.DatabaseClientError, "Failed to Dispose {0} DB Monitor, Unknown Manager", pType); } }
///<summary> /// Returns a Typed DatabaseLog Entity with mock values. ///</summary> static public DatabaseLog CreateMockInstance(TransactionManager tm) { // get the default mock instance DatabaseLog mock = DatabaseLogTest.CreateMockInstance_Generated(tm); // make any alterations necessary // (i.e. for DB check constraints, special test cases, etc.) SetSpecialTestData(mock); // return the modified object return(mock); }
// PUT api/awbuildversion/5 public void Put(DatabaseLog value) { var GetActionType = Request.Headers.Where(x => x.Key.Equals("ActionType")).FirstOrDefault(); if (GetActionType.Key != null) { if (GetActionType.Value.ToList()[0].Equals("DELETE")) adventureWorks_BC.DatabaseLogDelete(value); if (GetActionType.Value.ToList()[0].Equals("UPDATE")) adventureWorks_BC.DatabaseLogUpdate(value); } }
public static DataTable Select(string sql) { OleDbConnection conn = dbConn; DataTable dtResult = null; OleDbDataAdapter adapt = null; DataSet ds = null; for (int i = 0; i <= ConnTimes; i++) { try { adapt = new OleDbDataAdapter(sql, conn); ds = new DataSet(); adapt.Fill(ds); dtResult = ds.Tables[0]; break; } catch (SqlException e) { string LogCont = "错误信息:" + e.Message.Trim() + ",错误语句:" + sql + ",错误时间:" + System.DateTime.Now.ToString().Trim() + "\r\n"; DatabaseLog.WriteLog(LogCont); if (MessageBox.Show("当前数据库连接失败,您是否尝试重新连接?\r\n 点击“是”继续连接;点击“否”退出系统。", "", MessageBoxButtons.YesNo) == DialogResult.No) { Environment.Exit(0); } else { if (i >= ConnTimes) { MessageBox.Show("已经超过最大连接次数,点击确定后退出!"); Environment.Exit(0); } else { Database.Connect(); } } } finally { if (adapt != null) { adapt.Dispose(); } if (ds != null) { ds.Dispose(); } } } return(dtResult); }
public async Task <IActionResult> PostDatabaseLog([FromBody] DatabaseLog databaseLog) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _context.DatabaseLog.Add(databaseLog); await _context.SaveChangesAsync(); return(CreatedAtAction("GetDatabaseLog", new { id = databaseLog.DatabaseLogId }, databaseLog)); }
/// <summary> /// Create a new DatabaseLog object. /// </summary> /// <param name="databaseLogID">Initial value of DatabaseLogID.</param> /// <param name="postTime">Initial value of PostTime.</param> /// <param name="databaseUser">Initial value of DatabaseUser.</param> /// <param name="event">Initial value of Event.</param> /// <param name="tSQL">Initial value of TSQL.</param> /// <param name="xmlEvent">Initial value of XmlEvent.</param> public static DatabaseLog CreateDatabaseLog(int databaseLogID, global::System.DateTime postTime, string databaseUser, string @event, string tSQL, string xmlEvent) { DatabaseLog databaseLog = new DatabaseLog(); databaseLog.DatabaseLogID = databaseLogID; databaseLog.PostTime = postTime; databaseLog.DatabaseUser = databaseUser; databaseLog.Event = @event; databaseLog.TSQL = tSQL; databaseLog.XmlEvent = xmlEvent; return databaseLog; }
/// <summary> /// There are no comments for DatabaseLog in the schema. /// </summary> public void AddToDatabaseLog(DatabaseLog databaseLog) { base.AddObject("DatabaseLog", databaseLog); }
// POST api/awbuildversion public void Post(DatabaseLog value) { adventureWorks_BC.DatabaseLogAdd(value); }