/// <summary> /// Add a new UserID / ConnectionID mapping /// </summary> public int InsertUserConnection(string userID, string connectionID) { int result = 0; string cmd = "INSERT INTO UserConnections(UserID_FK, ConnectionID) VALUES(@UserID_FK, @ConnectionID)"; SqlParameter useridparam = new SqlParameter("@UserID_FK", userID); SqlParameter connectidparam = new SqlParameter("@ConnectionID", connectionID); try { //- check if connection is already mapped string existingUser = GetUserByConnectionID(connectionID); if (string.IsNullOrEmpty(existingUser)) { result = DatabaseHelper.ExecuteNonQuery(cmd, _connectionString, useridparam, connectidparam); } } catch (Exception ex) { LogMessageModel logmessage = new LogMessageModel(LogStatus.Error, string.Format("Login exception occurred within DatabaseManager.InsertUserConnection: {0}", ex.Message), -1); ExceptionManager.Instance.InsertLogMessage(logmessage); result = -1; } return(result); }
/// <summary> /// GET the current Signalr connection id associated with a specified user's device /// </summary> /// <param name="userid">ID of the user</param> /// <param name="deviceid">ID for the device the user is accessing</param> /// <returns>The Signalr connection id for that user on that device</returns> public string GetUserConnectionByDevice(string userid, string deviceid) { string connectionid = ""; string cmd = "SELECT ConnectionID FROM UserConnections WHERE UserID_FK = @UserID_FK and DeviceID = @DeviceID"; try { DataSet ds = DatabaseHelper.ExecuteQuery(cmd, _connectionString, new SqlParameter("@UserID_FK", userid), new SqlParameter("@DeviceID", deviceid)); if (ds != null && ds.Tables[0].Rows.Count > 0) { connectionid = ds.Tables[0].Rows[0]["ConnectionID"].ToString(); } } catch (Exception ex) { LogMessageModel logmessage = new LogMessageModel(LogStatus.Error, string.Format("Login exception occurred within DatabaseManager.GetUserConnectionByDevice: {0}", ex.Message), -1); ExceptionManager.Instance.InsertLogMessage(logmessage); } return(connectionid); }
/// <summary> /// Updates an existing User relationship /// </summary> /// <param name="sourceuserid">Requesting User ID</param> /// <param name="targetuserid">Requested User ID</param> public Task <int> UpdateUserRelationshipRequesAsync(string sourceuserid, string targetuserid, bool isactive) { Task <int> requesttask = new Task <int>(() => { int result = 0; string cmd = "UPDATE UserRelationships SET IsActive = @IsActive, DateActivated = @DateActivated "; cmd += "WHERE (Source_UserID = @Source_UserID and Target_UserID = @Target_UserID) or (Source_UserID = @Target_UserID and Target_UserID = @Source_UserID);"; SqlParameter sourceparam = new SqlParameter("@Source_UserID", sourceuserid); SqlParameter targetparam = new SqlParameter("@Target_UserID", targetuserid); SqlParameter isactiveparam = new SqlParameter("@IsActive", isactive); SqlParameter dateactivated = new SqlParameter("@DateActivated", DateTime.UtcNow); try { result = DatabaseHelper.ExecuteNonQuery(cmd, _connectionString, sourceparam, targetparam, isactiveparam, dateactivated); } catch (Exception ex) { result = -1; LogMessageModel logmessage = new LogMessageModel(LogStatus.Error, string.Format("Login exception occurred within DatabaseManager.UpdateUserRelationshipRequesAsync: {0}", ex.Message), -1); ExceptionManager.Instance.InsertLogMessage(logmessage); } return(result); }); return(requesttask); }
/// <summary> /// Get all connection id's belonging to the specified user /// </summary> public List <string> GetUserConnectionIDs(string userID) { List <string> ids = new List <string>(); string cmd = "SELECT * FROM UserConnections WHERE UserID_FK = @UserID_FK"; try { DataSet ds = DatabaseHelper.ExecuteQuery(cmd, _connectionString, new SqlParameter("@UserID_FK", userID)); if (ds != null && ds.Tables[0].Rows.Count > 0) { DataTable table = ds.Tables[0]; //- iterate through results foreach (DataRow row in table.Rows) { ids.Add(row["ConnectionID"].ToString()); } } } catch (Exception ex) { LogMessageModel logmessage = new LogMessageModel(LogStatus.Error, string.Format("Login exception occurred within DatabaseManager.GetUserConnectionIDs: {0}", ex.Message), -1); ExceptionManager.Instance.InsertLogMessage(logmessage); } return(ids); }
/// <summary> /// Get user associated with the provided UserID /// </summary> public UserModel GetUserByUserID(string userID) { UserModel user = null; string cmd = "SELECT * FROM Users WHERE UserID = @UserID"; try { DataSet ds = DatabaseHelper.ExecuteQuery(cmd, _connectionString, new SqlParameter("@UserID", userID)); if (ds != null && ds.Tables[0].Rows.Count > 0) { DataRow row = ds.Tables[0].Rows[0]; user = new UserModel(); user.CreateDate = DateTime.Parse(row["CreateDate"].ToString()); user.LastModified = DateTime.Parse(row["LastModified"].ToString()); user.FirstName = row["FirstName"].ToString(); user.LastName = row["LastName"].ToString(); user.UserID = row["UserID"].ToString(); user.GlobalID = row["GlobalID"].ToString(); user.UserLoginType = (LoginType)int.Parse(row["IsFacebookLogin"].ToString()); user.PasswordHash = row["Password"].ToString(); user.IsActivated = bool.Parse(row["IsActivated"].ToString()); } } catch (Exception ex) { LogMessageModel logmessage = new LogMessageModel(LogStatus.Error, string.Format("Login exception occurred within DatabaseManager.GetUserByUserID: {0}", ex.Message), -1); ExceptionManager.Instance.InsertLogMessage(logmessage); } return(user); }
/// <summary> /// Get all device id's bleonging to this user /// </summary> /// <param name="userID">ID of the user the device id are associated with</param> public List <string> GetUserDeviceIDs(string userID) { List <string> deviceIDs = new List <string>(); string cmd = "SELECT DeviceID FROM UserConnections WHERE UserID_FK = @UserID_FK"; try { DataSet ds = DatabaseHelper.ExecuteQuery(cmd, _connectionString, new SqlParameter("@UserID_FK", userID)); if (ds != null && ds.Tables[0].Rows.Count > 0) { string device = ds.Tables[0].Rows[0]["DeviceID"].ToString(); deviceIDs.Add(device); } } catch (Exception ex) { LogMessageModel logmessage = new LogMessageModel(LogStatus.Error, string.Format("Login exception occurred within DatabaseManager.GetUserDeviceIDs: {0}", ex.Message), -1); ExceptionManager.Instance.InsertLogMessage(logmessage); } return(deviceIDs); }
/// <summary> /// /// </summary> /// <param name="log"></param> /// <param name="debug"></param> public static void myDebug(LogModel log, JObject debug) { if (GrobalConfig.IsLog) { LogMessageModel logMessage = new LogMessageModel(); logMessage.OperationTime = DateTime.Now; logMessage.Url = HttpContext.Current.Request.RawUrl; logMessage.Class = log.GetType().ToString(); logMessage.Ip = WebHelperUtils.Ip; logMessage.Host = WebHelperUtils.Host; logMessage.Browser = WebHelperUtils.Browser; try { logMessage.UserName = UserUtils.Provider.Current().Account + "(" + UserUtils.Provider.Current().UserName + ")"; } catch (Exception excep) { logMessage.UserName = excep.ToString(); } if (debug != null) { foreach (JProperty jp in debug.Properties()) { logMessage.Content += "\t" + jp.Name + " : " + jp.Value + "\r\n"; } } string strMessage = LogFormatModel.DebugFormat(logMessage); log.Debug(strMessage); } }
/// <summary> /// log4net 自定义错误日志格式 /// </summary> /// <param name="log"></param> /// <param name="exception"></param> public static void myError(LogModel log, Exception exception) { if (GrobalConfig.IsLog) { Exception Error = exception; LogMessageModel logMessage = new LogMessageModel(); logMessage.OperationTime = DateTime.Now; logMessage.Url = HttpContext.Current.Request.RawUrl; logMessage.Class = log.GetType().ToString(); logMessage.Ip = WebHelperUtils.Ip; logMessage.Host = WebHelperUtils.Host; logMessage.Browser = WebHelperUtils.Browser; try { logMessage.UserName = UserUtils.Provider.Current().Account + "(" + UserUtils.Provider.Current().UserName + ")"; } catch (Exception excep) { logMessage.UserName = excep.ToString(); } if (Error.InnerException == null) { logMessage.ExceptionInfo = Error.Message; } else { logMessage.ExceptionInfo = Error.InnerException.Message; } logMessage.ExceptionSource = Error.Source; logMessage.ExceptionRemark = Error.StackTrace; string strMessage = LogFormatModel.ExceptionFormat(logMessage); log.Error(strMessage); } }
/// <summary> /// Updates the signalr connection for a specific user on a specific device /// </summary> public int UpdateUserDeviceConnection(string userid, string deviceid, string connectionid) { int result = 0; string cmd = "UPDATE UserConnections SET ConnectionID = @ConnectionID WHERE UserID_FK = @UserID_FK and DeviceID = @DeviceID"; try { result = DatabaseHelper.ExecuteNonQuery(cmd, _connectionString, new SqlParameter("@ConnectionID", connectionid), new SqlParameter("@UserID_FK", userid), new SqlParameter("@DeviceID", deviceid)); } catch (Exception ex) { LogMessageModel logmessage = new LogMessageModel(LogStatus.Error, string.Format("Login exception occurred within DatabaseManager.UpdateUserDeviceConnection: {0}", ex.Message), -1); ExceptionManager.Instance.InsertLogMessage(logmessage); result = -1; } return(0); }
/// <summary> /// Save event message data using postgreSQL function. /// </summary> /// <param name="model"></param> /// <returns>eventid</returns> public Guid SaveLogMessage(LogMessageModel model) { var query = "select * from public.func_saveevents(" + model.EventCategoryId + ",'" + model.Message + "','" + model.Summary + "','" + model.Errorcode + "','" + model.Attachment + "','" + model.Serverdetail + "','" + model.Source + "','" + model.Tag1 + "','" + model.Tag2 + "'," + "null" + ") "; var logMessage = Get <LogMessageModel>(query).FirstOrDefault(); return(logMessage.EventId); }
protected virtual void OnLogReceived(LogMessageModel message) { var e = new LogReceivedEventArgs(message); var handler = this.LogReceived; if (handler != null) { handler(this, e); } }
protected virtual void OnLogReceived(LogMessageModel message) { var e = new LogReceivedEventArgs(message); var handler = this.LogReceived; if (handler != null) { handler(this, e); } }
public void InsertLogMessage(LogMessageModel message) { string cmd = "INSERT INTO Logs (Status, Message, Code, DateCreated) VALUES(@Status, @Message, @Code, @DateCreated)"; DatabaseHelper.ExecuteNonQuery(cmd, _connectionString, new SqlParameter("@Status", message.Status), new SqlParameter("@Message", message.Message), new SqlParameter("@Code", message.Code), new SqlParameter("@DateCreated", message.DateCreated)); }
public SignupResultModel SignupStandardUser(UserModel user) { SignupResultModel model = new SignupResultModel(); string cmd = "INSERT INTO USERS(GlobalID, UserID, LoginType, Password, FirstName, LastName, CreateDate, IsActivated)"; cmd += "VALUES(@GlobalID, @UserID, @LoginType, @Password, @FirstName, @LastName, @CreateDate, @IsActivated)"; SqlParameter globalid = new SqlParameter("@GlobalID", user.GlobalID); SqlParameter userid = new SqlParameter("@UserID", user.UserID); SqlParameter userlogintype = new SqlParameter("@LoginType", user.UserLoginType); SqlParameter password = new SqlParameter("@Password", user.PasswordHash); SqlParameter fname = new SqlParameter("@FirstName", user.FirstName); SqlParameter lname = new SqlParameter("@LastName", user.LastName); SqlParameter createdate = new SqlParameter("@CreateDate", user.CreateDate); SqlParameter isactive = new SqlParameter("@IsActivated", user.IsActivated); try { //- check if user exists bool doesExist = CheckUserExists(user.UserID); if (doesExist) { model.ResultStatus = SignupResultType.UserExists; model.Message = "The user id already exists"; return(model); } // - insert new user into database int queryresult = DatabaseHelper.ExecuteNonQuery(cmd, _connectionString, globalid, userid, userlogintype, password, fname, lname, createdate, isactive); if (queryresult < 0) { model.ResultStatus = SignupResultType.UnexpectedException; model.Message = "The database was unable to add the user record"; } else { model.ResultStatus = SignupResultType.Success; model.Message = "User account successfully added"; } } catch (Exception ex) { LogMessageModel message = new LogMessageModel(LogStatus.Error, string.Format("An error occurred during user signup within DatabaseManager.SignupStandardUser: {0}", ex.Message), -1); model.ResultStatus = SignupResultType.UnexpectedException; model.Message = string.Format("An exception occurred while attempted to add the user account: {0}", ex.Message); } return(model); }
public async Task PostReturnsLogMessageForValidMessages() { //Arrange var fakeMessages = new LogMessageModel() { Messages = new List <Message>() { new Message { Title = "Test message summary", Text = "Exceptiion occured at ..." } }.ToArray() }; var fakeLogMessageResponse = new LogMessageResponse { Records = new List <RecordResponse>() { new RecordResponse { Id = Guid.NewGuid().ToString(), Field = new Field() { Id = "recTPWgTQaKlETabD", Message = "Test message summary", Summary = "Exceptiion occured at ...", ReceivedAt = DateTime.UtcNow }, CreatedTime = DateTime.UtcNow } }.ToArray() }; var mockLogMessageManager = new Mock <ILogMessageManager>(); mockLogMessageManager.Setup(x => x.SendLogMessageAsync(It.IsAny <Message[]>())).Returns(Task.FromResult(fakeLogMessageResponse)); var mockLogger = new Mock <ILogger <MessageController> >(); var controller = new MessageController(mockLogMessageManager.Object, mockLogger.Object); //Act var result = await controller.Post(fakeMessages); var okResult = result as OkObjectResult; //Assert Assert.IsInstanceOf(typeof(LogMessageResponse), okResult.Value); Assert.IsNotNull(okResult.Value); var response = okResult.Value as LogMessageResponse; Assert.AreEqual(fakeLogMessageResponse.Records.Length, response.Records.Length); Assert.AreEqual(200, okResult.StatusCode); }
private void readLogLines() { try { logMessages = LogMessageModel.ParseAllMessages(logFilePath); } catch (Exception ex) { MessageBox.Show(String.Format("Could not load {0}, the file may not exist", logFilePath), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); log.Error(ex); this.Close(); } }
public ResponseModel SaveLogMessage(LogMessageDto model) { //auto mapping LogMessageModel logMessage = mapper.Map <LogMessageModel>(model); ResponseModel response = new ResponseModel(); // replace single quotes with double logMessage.Message = CommonClass.ReplaceSingleQuotes(logMessage.Message); logMessage.Source = CommonClass.ReplaceSingleQuotes(logMessage.Source); logMessage.Serverdetail = CommonClass.ReplaceSingleQuotes(logMessage.Serverdetail); logMessage.Summary = CommonClass.ReplaceSingleQuotes(logMessage.Summary); logMessage.Tag1 = CommonClass.ReplaceSingleQuotes(logMessage.Tag1); logMessage.Tag2 = CommonClass.ReplaceSingleQuotes(logMessage.Tag2); logMessage.EventCategoryId = CommonClass.GetCategoryId(model.Category); if (logMessage.EventCategoryId == 0) { response.Message = "input category not defined in system."; response.StatusCode = "400"; return(response); } // Getting attached file var attachedFile = model.AttachedFile; // Saving attached file on server if (attachedFile != null) { //modify file name with data var fileName = Path.GetFileNameWithoutExtension(attachedFile.FileName); var extension = Path.GetExtension(attachedFile.FileName); fileName = fileName + '_' + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + extension; logMessage.Attachment = fileName; //saving data into database logMessagesRepository.SaveLogMessage(logMessage); response.Message = "success"; response.StatusCode = "200"; //file saving to s3 bucket. CommonClass.UploadFileToS3(attachedFile, fileName, awsAccessKey, awsSecreteKey, bucketName); } else { //saving data into database logMessagesRepository.SaveLogMessage(logMessage); response.Message = "success"; response.StatusCode = "200"; } return(response); }
public void AddMessage(Guid appId, Guid activityId, string message, DateTime datetime) { if (datetime == DateTime.MinValue) { datetime = DateTime.Now; } var m = new LogMessageModel() { AppId = appId, ActivityId = activityId, DateTime = datetime, LogMessage = message }; messages.Add(m); messagesSubject.OnNext(m); }
public override void Write(string message, LogLevel logLevel) { var logMessage = new LogMessageModel { Message = message, LogLevel = logLevel.ToString(), TimeStamp = DateTimeOffset.Now, ThreadId = Environment.CurrentManagedThreadId }; _elasticsearchService.IndexDocument(logMessage); base.Write(message, logLevel); }
/// <summary> /// Gets a user's relationships /// </summary> /// <param name="userid">Identifier for the user to get UserRelationships for</param> /// <param name="isactive">0 - gets all pending UserRelationships; 1 - gets all active relationships</param> /// <returns>List of UserModels belonging to users that this user relates to </returns> public Task <List <UserModel> > GetUserRelationshipsAsync(string userid, DateTime datecreated, bool isactive) { Task <List <UserModel> > usertask = new Task <List <UserModel> >(() => { List <UserModel> users = new List <UserModel>(); try { string cmd = "SELECT * FROM UserRelationships WHERE (Source_UserID = @UserID or Target_UserID = @UserID) and IsActive = @IsActive and "; cmd += "DateCreated > '@DateCreated'"; SqlParameter userparam = new SqlParameter("@UserID", userid); SqlParameter createparam = new SqlParameter("@DateCreated", datecreated); SqlParameter isactiveparam = new SqlParameter("@IsActive", isactive); DataSet resultSet = DatabaseHelper.ExecuteQuery(cmd, _connectionString, userparam, createparam, isactiveparam); //- Create UserModel's from the other user in the relationship if (resultSet != null && resultSet.Tables[0].Rows.Count > 0) { foreach (DataRow row in resultSet.Tables[0].Rows) { UserModel user = new UserModel(); if (row["Source_UserID"].ToString() == userid) { user = GetUserByUserID(row["Target_UserID"].ToString()); } else { user = GetUserByUserID(row["Source_UserID"].ToString()); } users.Add(user); } } } catch (Exception ex) { LogMessageModel logmessage = new LogMessageModel(LogStatus.Error, string.Format("Login exception occurred within DatabaseManager.GetActiveUserRelationshipAsync: {0}", ex.Message), -1); ExceptionManager.Instance.InsertLogMessage(logmessage); } return(users); }); return(usertask); }
/// <summary> /// Inserts a new relationship request from one user to another /// </summary> /// <param name="sourceuserid">Requesting User ID</param> /// <param name="targetuserid">Requested User ID</param> public Task <int> InsertUserRelationshipRequestAsync(string sourceuserid, string targetuserid) { Task <int> requesttask = new Task <int>(() => { int result = 0; string cmd = "INSERT INTO UserRelationships(Source_UserID, Target_UserID, IsActive, DateCreated) "; cmd += "VALUES(@Source_UserID, @Target_UsesrID, 0, @DateCreated);"; SqlParameter sourceparam = new SqlParameter("@Source_UserID", sourceuserid); SqlParameter targetparam = new SqlParameter("@Target_UserID", targetuserid); SqlParameter datecreated = new SqlParameter("@DateCreated", DateTime.UtcNow); try { //- check if target user exists and is active bool targetexists = CheckUserExists(targetuserid); bool targetactive = CheckIfUserActive(targetuserid); if (targetexists && targetactive) { result = DatabaseHelper.ExecuteNonQuery(cmd, _connectionString, sourceparam, targetparam, datecreated); } else if (!targetexists) { throw new Exception(string.Format("Error: Could not create relationship request. Target user '{0}' does not exist", targetuserid)); } else { throw new Exception(string.Format("Error: Could not create relationship request. Target user '{0}' is not active", targetuserid)); } } catch (Exception ex) { result = -1; LogMessageModel logmessage = new LogMessageModel(LogStatus.Error, string.Format("Login exception occurred within DatabaseManager.InsertUserRelationshipRequesAsync: {0}", ex.Message), -1); ExceptionManager.Instance.InsertLogMessage(logmessage); } return(result); }); return(requesttask); }
/// <summary> /// Writes logging event to the log target. /// classes. /// </summary> /// <param name="logEvent">Logging event to be written out. /// </param> protected override void Write(LogEventInfo logEvent) { var colorrule = this.RowColorRules.FirstOrDefault(x => true.Equals((bool)x.Condition.Evaluate(logEvent))); if (colorrule == null) { colorrule = DefaultColorRule; } var messageString = GetMessage(logEvent); var message = new LogMessageModel(messageString, logEvent.Level, logEvent.TimeStamp) { FontStyle = colorrule.FontStyle, FontWeight = colorrule.FontWeight, BackgroundColor = colorrule.BackgroundColor, ForegroundColor = colorrule.ForegroundColor }; this.OnLogReceived(message); }
public LoginResultModel AuthenticateStandardUser(string userID, string passwordHash) { LoginResultModel result = new LoginResultModel(); SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("@UserID", userID), new SqlParameter("@Password", passwordHash) }; string cmd = "SELECT * FROM Users WHERE UserID = @UserID and Password = @Password"; try { DataSet resultSet = DatabaseHelper.ExecuteQuery(cmd, _connectionString, parameters); //- Determine if user exists within database if (resultSet != null && resultSet.Tables[0].Rows.Count > 0) { DataTable resultTable = resultSet.Tables[0]; result.Message = "User successfully authenticated"; result.ResultStatus = LoginResultType.Success; result.ConnectionIDs = GetUserConnectionIDs(userID); } else { result.Message = "User not found"; result.ResultStatus = LoginResultType.UserNotFound; } } catch (Exception ex) { result.Message = ex.Message; result.ResultStatus = LoginResultType.UnexpectedException; LogMessageModel logmessage = new LogMessageModel(LogStatus.Error, string.Format("Login exception occurred within DatabaseManager.AuthenticateStandardUser: {0}", ex.Message), -1); ExceptionManager.Instance.InsertLogMessage(logmessage); } return(result); }
public async Task <IActionResult> Post([FromBody] LogMessageModel model) { try { var response = await _logMessageManager.SendLogMessageAsync(model.Messages); return(Ok(response)); } catch (ApplicationException ex) { _logger.LogError($"Could not post Logs: {ex.Message}"); return(BadRequest(ex.Message)); } catch (Exception ex) { _logger.LogError(ex.Message); return(BadRequest(ex.Message)); } }
/// <summary> /// Writes logging event to the log target. /// classes. /// </summary> /// <param name="logEvent">Logging event to be written out. /// </param> protected override void Write(LogEventInfo logEvent) { var colorrule = this.RowColorRules.FirstOrDefault(x => true.Equals((bool)x.Condition.Evaluate(logEvent))); if (colorrule == null) { colorrule = DefaultColorRule; } var messageString = GetMessage(logEvent); var message = new LogMessageModel(messageString, logEvent.Level, logEvent.TimeStamp) { FontStyle = colorrule.FontStyle, FontWeight = colorrule.FontWeight, BackgroundColor = colorrule.BackgroundColor, ForegroundColor = colorrule.ForegroundColor }; this.OnLogReceived(message); }
/// <summary> /// Get all active users /// </summary> public List <UserModel> GetAllActiveUsers() { List <UserModel> activeusers = new List <UserModel>(); string cmd = "SELECT * FROM Users WHERE IsActivated = 1"; try { DataSet ds = DatabaseHelper.ExecuteQuery(cmd, _connectionString); if (ds != null && ds.Tables[0].Rows.Count > 0) { DataTable table = ds.Tables[0]; //- iterate through results foreach (DataRow row in table.Rows) { UserModel user = new UserModel(); user.CreateDate = DateTime.Parse(row["CreateDate"].ToString()); user.FirstName = row["FirstName"].ToString(); user.LastName = row["LastName"].ToString(); user.UserID = row["UserID"].ToString(); user.GlobalID = row["GlobalID"].ToString(); user.UserLoginType = (LoginType)int.Parse(row["LoginType"].ToString()); user.PasswordHash = row["Password"].ToString(); user.IsActivated = true; activeusers.Add(user); } } } catch (Exception ex) { LogMessageModel logmessage = new LogMessageModel(LogStatus.Error, string.Format("Login exception occurred within DatabaseManager.GetUserConnectionIDs: {0}", ex.Message), -1); ExceptionManager.Instance.InsertLogMessage(logmessage); } return(activeusers); }
/// <summary> /// Activate User record within the database /// </summary> public int ActivateUser(string userid) { int result = 0; string cmd = "UPDATE USERS SET IsActivated = 1 WHERE UserID = @UserID"; try { result = DatabaseHelper.ExecuteNonQuery(cmd, _connectionString, new SqlParameter("@UserID", userid)); } catch (Exception ex) { LogMessageModel message = new LogMessageModel(LogStatus.Error, string.Format("An error occurred during user activation within DatabaseManager.ActivateUser: {0}", ex.Message), -1); ExceptionManager.Instance.InsertLogMessage(message); result = -1; } return(result); }
/// <summary> /// 实际的调用方法 /// </summary> /// <typeparam name="TState"></typeparam> /// <param name="logLevel"></param> /// <param name="eventId"></param> /// <param name="state"></param> /// <param name="exception"></param> /// <param name="formatter"></param> public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { if (!IsEnabled(logLevel)) { return; } string msg = formatter(state, exception); LogMessageModel logMessageModel = new LogMessageModel() { LogMsg = (exception == null) ? msg : new LogExceptionModel(exception, msg).ToString(), LogTime = DateTime.Now.ToString("o"), LogLevel = Enum.GetName(typeof(LogLevel), logLevel), LogId = Guid.NewGuid().ToString(), LogAttr = eventId.Name + eventId.Id, LogCategory = this.categoryName }; string strPublishMessage = logMessageModel.ToLogstashMessage(); this._RabbitMQLoggerProvider.PublishMessage(strPublishMessage, this.envModel.APP_BUILD_NAME); }
/// <summary> /// Gets user associated with the Connection /// </summary> public string GetUserByConnectionID(string connectionID) { string userid = ""; string cmd = "SELECT * FROM UserConnections WHERE Connection = @ConnectionID"; try { DataSet ds = DatabaseHelper.ExecuteQuery(cmd, _connectionString, new SqlParameter("@ConnectionID", connectionID)); if (ds != null && ds.Tables[0].Rows.Count > 0) { userid = ds.Tables[0].Rows[0]["ConnectionID"].ToString(); } } catch (Exception ex) { LogMessageModel logmessage = new LogMessageModel(LogStatus.Error, string.Format("Login exception occurred within DatabaseManager.GetUserByConnectionID: {0}", ex.Message), -1); ExceptionManager.Instance.InsertLogMessage(logmessage); } return(userid); }
private void addMessage(LogMessageModel message) { if ((int)message.Level > (int)ViewModel.LogLevel.CurrentItem) { return; } String text = message.Text.TrimEnd(trimChars); text = text.Replace("\r\n", "\n"); text = text.Replace("\n", "\r\t"); if (logTextBox.Document.LineCount == LogViewModel.maxLinesInLog) { int length = logTextBox.Document.GetOffset(2, 0); logTextBox.Document.Remove(0, length); } int offset = logTextBox.Document.GetOffset(logTextBox.Document.LineCount, 0); logTextBox.Document.Insert(offset, text); logTextBox.ScrollToEnd(); }
public async Task PostReturnsBadRequestForInvalidMessages() { //Arrange var mockLogMessageManager = new Mock <ILogMessageManager>(); mockLogMessageManager.Setup(x => x.SendLogMessageAsync(It.IsAny <Message[]>())).Throws(new InvalidOperationException("Invalid message to send")); var mockLogger = new Mock <ILogger <MessageController> >(); var controller = new MessageController(mockLogMessageManager.Object, mockLogger.Object); var fakeMessages = new LogMessageModel() { Messages = Array.Empty <Message>() }; //Act var result = await controller.Post(fakeMessages); var okResult = result as BadRequestObjectResult; //Assert Assert.IsInstanceOf(typeof(BadRequestObjectResult), result); Assert.AreEqual("Invalid message to send", okResult.Value); Assert.AreEqual(400, okResult.StatusCode); }
/// <summary> /// Initializes a new instance of the <see cref="T:System.EventArgs" /> class. /// </summary> public LogReceivedEventArgs(LogMessageModel message) { Message = message; }
public AzureTableStorageListenerEntity(LogMessageModel logMessage) { this.PartitionKey = logMessage.Timestamp.ToString("yyyyMMdd", CultureInfo.InvariantCulture); this.RowKey = logMessage.Timestamp.Ticks.ToString(); this.LogMessageJSON = logMessage.SerializeToJson(); }
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) { if (this.TableClient() != null) { //if (data is LogEntry && this.Formatter != null) if (data is LogEntry) { LogMessageModel logMessage = new LogMessageModel(data as LogEntry); AzureTableStorageListenerEntity azureLogEntity = new AzureTableStorageListenerEntity(logMessage); if (ApplicationConfiguration.IsDebugMode) { this.TraceDataSingleOperation(logMessage.Category, azureLogEntity); } else { this.TraceDataBatchOperation(logMessage.Category, azureLogEntity); } } else { //this.WriteLine(data.ToString()); } } else { } }
/// <summary> /// Initializes a new instance of the <see cref="T:System.EventArgs" /> class. /// </summary> public LogReceivedEventArgs(LogMessageModel message) { Message = message; }