protected override void _OnEvent(object sender, NpgsqlNotificationEventArgs npgsqlNotificationEventArgs) { var notifyObject = JSON.ToObject <EventTriggerNotification>(npgsqlNotificationEventArgs.AdditionalInformation); if (notifyObject.Schema != _connectionBuilder.GetConnection().SchemaName) { return; } var notify = false; foreach (var s in _actionsToListen) { if (Wildcard.IsMatch(notifyObject.Action, s)) { notify = true; break; } } if (notify) { _notificationSubject.OnNext(notifyObject); } }
private void OnNotification(object sender, NpgsqlNotificationEventArgs e) { var context = GlobalHost.ConnectionManager.GetHubContext <TicketsHub>(); string actionName = e.AdditionalInformation.ToString(); string actionType = ""; if (actionName.Contains("DELETE")) { actionType = "Delete"; } if (actionName.Contains("UPDATE")) { actionType = "Update"; } if (actionName.Contains("INSERT")) { actionType = "Insert"; } // Now broadcast the tickets and actiontype (SignalR) context.Clients.All.addMessage(this.GetTicketsList(), actionType); //// NotificationEventHandler pp = new NotificationEventHandler(OnNotification); // conn.Notification -= OnNotification; // pp; // OnNotification; //conn.Close(); //close connection for this event }
private void OnNotification(object sender, NpgsqlNotificationEventArgs e) { if (NotificationEvent != null) { DBNotification _notification = DBNotification.Factory(this, e); NotificationEvent.Invoke(_notification); } }
private static void OnListener(object sender, NpgsqlNotificationEventArgs e) { if (listeners != null) { ListenerEventArgs ev = new ListenerEventArgs(e.Condition); listeners(sender, ev); } }
private async void PostgresNotificationReceived(object sender, NpgsqlNotificationEventArgs e) { if (string.IsNullOrEmpty(e.Payload)) { return; } await _hubContext.Clients.All.SendAsync("ReceiveMessage", e.Payload); }
private void LogNotificationHelper(object sender, NpgsqlNotificationEventArgs e) { //Deserialize Payload Data var dataPayload = JsonConvert.DeserializeObject <tbllogInfo>(e.Payload); Console.WriteLine("{0}", dataPayload.table + " :: " + dataPayload.action + " :: " + dataPayload.data.logdetails); //Notify Client using SignalR }
private void OnNotification(object sender, NpgsqlNotificationEventArgs e) { TriggeredFunctionData input = new TriggeredFunctionData { TriggerValue = e.AdditionalInformation }; _executor.TryExecuteAsync(input, CancellationToken.None).RunSynchronously(); }
/// <summary> /// Event on DB notification on listened channels occurs /// </summary> /// <param name="sender">Sender of event</param> /// <param name="args">Event arguments</param> private void OnNotification(object sender, NpgsqlNotificationEventArgs args) { try { switch (args.Channel) { case PgSqlDbConnect.CHANNEL_GENESIS_REQUEST: { if (string.IsNullOrEmpty(args.Payload)) { throw new ArgumentException("Payload is empty"); } string filePath = Path.Combine(_config["GenesisOutputDir"], args.Payload + ".sql"); FileHelper.DirectoryEnsure(filePath); string exePath = _config["PgDumpPath"]; string argsText = $"{_config["GenesisArgs"]} --file=\"{filePath}\" {_dbName}"; Log.Info($"RUN {exePath} {argsText}"); Process pgsql = Process.Start(exePath, argsText); pgsql?.WaitForExit(); using (PgSqlDbConnect connect2 = new PgSqlDbConnect(_connectionString)) { connect2.Open(); connect2.Execute($"SELECT pg_notify('{PgSqlDbConnect.CHANNEL_GENESIS_RESPOND}', '{filePath}'::TEXT);"); } break; } case PgSqlDbConnect.CHANNEL_GENESIS_DELETE: { File.Delete(args.Payload); break; } case PgSqlDbConnect.CHANNEL_BACKUP_REQUEST: { string exePath = _config["PgDumpAllPath"]; string filePath = Path.Combine(_config["BackupOutputDir"], _config["BackupFilePrefix"] + DateTimeHelper.Now.ToString(DateTimeHelper.FORMAT_FULL).Replace(".", "_").Replace(":", "_").Replace(" ", "_") + ".pgbak"); string argsText = $"{_config["BackupArgs"]} --file=\"{filePath}\""; Log.Info($"RUN {exePath} {argsText}"); Process pgsql = Process.Start(exePath, argsText); pgsql?.WaitForExit(); break; } } } catch (Exception ex) { Log.Error(ex, $"{args.Channel} [{args.Payload}]"); } }
private void HandleTaskUpdateReceived(object sender, NpgsqlNotificationEventArgs e) { IncrementListenerTaskNotificationCount(); EventHandler <NewTaskPostedEventArgs> eventHandler = NewTaskPosted; if (eventHandler != null) { eventHandler(this, new NewTaskPostedEventArgs()); } }
private void SendToAll(object obj, NpgsqlNotificationEventArgs e) { if (long.TryParse(e.Payload, out var id)) { var _ = SendToAll(id); return; } var doc = JsonDocument.Parse(e.Payload); SendToAll(doc); }
private static JToken ClearDatesFromPayload(NpgsqlNotificationEventArgs e) { var x = JToken.Parse(e.Payload); x.SelectToken("old_data.created_at").Parent.Remove(); x.SelectToken("old_data.updated_at").Parent.Remove(); x.SelectToken("old_data.mobile_template").Parent.Remove(); x.SelectToken("new_data.created_at").Parent.Remove(); x.SelectToken("new_data.updated_at").Parent.Remove(); x.SelectToken("new_data.mobile_template").Parent.Remove(); return(x); }
public static DBNotification Factory(DBConnection _connection, NpgsqlNotificationEventArgs e) { //DBNotification _notification = new DBNotification(); //_notification.Notification = e.AdditionalInformation; //_notification.IsCorrupted = (_notification.Init() == false); //_notification.IsNotifiedByMe = (e.PID == _connection.PID); DBNotification _notification = null; MemoryStream _ms = new MemoryStream(Encoding.UTF8.GetBytes(e.AdditionalInformation)); DataContractJsonSerializer _serializer = new DataContractJsonSerializer(typeof(DBNotification)); _notification = (DBNotification)_serializer.ReadObject(_ms); _ms.Close(); _notification.IsSentBySelf = (e.PID == _connection.PID); return(_notification); }
private void Connection_Notification(object sender, NpgsqlNotificationEventArgs e) { try { var q = System.Text.Json.JsonSerializer.Deserialize(e.Payload, typeof(NotiModel)); if (q is NotiModel notiModel) { rabbitMQBase.Publish(Encoding.UTF8.GetBytes(e.Payload), notiModel.BotId.ToString()); } } catch (Exception ex) { rabbitMQBase.listeningChannel.Dispose(); rabbitMQBase.listeningConnection.Dispose(); rabbitMQBase.Connect(); } }
private void _onNotification(object sender, NpgsqlNotificationEventArgs e) { if (e.Condition != "kroeg") { return; } var data = JsonConvert.DeserializeObject <_notifyObject>(e.AdditionalInformation); if (_actions.ContainsKey(data.Path)) { foreach (var action in _actions[data.Path]) { action(data.Value); } } }
private void Connection_Notification(object sender, NpgsqlNotificationEventArgs e) { try { if (e.Condition == "events" || e.Condition == "aggregate_roots") { TraceSource.TraceEvent(TraceEventType.Verbose, 5137, "Postgres notification: {0} with {1}", e.Condition, e.AdditionalInformation); var firstSeparator = e.AdditionalInformation.IndexOf(':'); var name = e.AdditionalInformation.Substring(0, firstSeparator); var secondSeparator = e.AdditionalInformation.Substring(firstSeparator + 1).IndexOf(':'); var op = e.AdditionalInformation.Substring(firstSeparator + 1, secondSeparator).Trim(); var array = e.AdditionalInformation.Substring(firstSeparator + secondSeparator + 2).Trim(); if (array.Length > 0) { var uris = StringConverter.ParseCollection(Reader.Reuse(array), 0, false).ToArray(); switch (op) { case "Update": Subject.OnNext(new NotifyInfo(name, NotifyInfo.OperationEnum.Update, NotifyInfo.SourceEnum.Database, uris)); break; case "Change": Subject.OnNext(new NotifyInfo(name, NotifyInfo.OperationEnum.Change, NotifyInfo.SourceEnum.Database, uris)); break; case "Delete": Subject.OnNext(new NotifyInfo(name, NotifyInfo.OperationEnum.Delete, NotifyInfo.SourceEnum.Database, uris)); break; default: Subject.OnNext(new NotifyInfo(name, NotifyInfo.OperationEnum.Insert, NotifyInfo.SourceEnum.Database, uris)); break; } } } else if (e.Condition == "migration") { TraceSource.TraceEvent(TraceEventType.Information, 5155, "Postgres migration detected: {0} ", e.AdditionalInformation); SystemState.Notify(new SystemEvent("migration", e.AdditionalInformation)); } } catch (Exception ex) { TraceSource.TraceEvent(TraceEventType.Error, 5138, "{0}{1} {2}", e.Condition, e.AdditionalInformation, ex); } }
private void ReceiveEvent(object sender, NpgsqlNotificationEventArgs e) { this.logger.LogInformation($"Event received on channel {Channel}"); var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, IgnoreNullValues = true, WriteIndented = true, }; options.Converters.Add(new JsonStringEnumConverter()); BannerChangeEvent?changeEvent = JsonSerializer.Deserialize <BannerChangeEvent>(e.Payload, options); if (this.CommunicationService != null && changeEvent != null && changeEvent.Data != null) { DateTime utcnow = DateTime.UtcNow; RequestResult <Communication> cacheEntry = new RequestResult <Communication>(); if (changeEvent.Action == InsertAction || changeEvent.Action == UpdateAction) { Communication comm = changeEvent.Data; if (utcnow >= comm.EffectiveDateTime && utcnow <= comm.ExpiryDateTime) { cacheEntry.ResultStatus = Common.Constants.ResultType.Success; cacheEntry.ResourcePayload = comm; this.logger.LogInformation("Active Banner inserted or updated in DB"); this.CommunicationService.SetActiveBannerCache(cacheEntry); } } else if (changeEvent.Action == DeleteAction) { RequestResult <Communication> currentBanner = this.CommunicationService.GetActiveBanner(); if (currentBanner.ResourcePayload != null && currentBanner.ResourcePayload.Id == changeEvent.Data.Id) { cacheEntry.ResultStatus = Common.Constants.ResultType.Error; cacheEntry.ResultError = new RequestResultError() { ResultMessage = "Active Banner deleted from DB", ErrorCode = ErrorTranslator.InternalError(ErrorType.InvalidState) }; this.logger.LogInformation("Active Banner deleted from DB"); this.CommunicationService.SetActiveBannerCache(cacheEntry); } } } }
private void PostgresNotificationRecieved(object sender, NpgsqlNotificationEventArgs e) { string actionName = e.Payload.ToString(); string actionType = ""; if (actionName.Contains("DELETE")) { actionType = "Delete"; } if (actionName.Contains("UPDATE")) { actionType = "Update"; } if (actionName.Contains("INSERT")) { actionType = "Insert"; } _hubContext.Clients.All.SendAsync("ReceiveMessage", this.GetAlarmList()); }
private void OnNotification(object sender, NpgsqlNotificationEventArgs e) { var context = GlobalHost.ConnectionManager.GetHubContext <NotifHub>(); string actionName = e.AdditionalInformation.ToString(); string actionType = ""; if (actionName.Contains("DELETE")) { actionType = "Delete"; } if (actionName.Contains("UPDATE")) { actionType = "Update"; } if (actionName.Contains("INSERT")) { actionType = "Insert"; } context.Clients.All.addMessage(this.GetNotifList(), userid); }
private void Connection_Notification(object sender, NpgsqlNotificationEventArgs e) { try { if (e.Condition == "events" || e.Condition == "aggregate_roots") { var firstSeparator = e.AdditionalInformation.IndexOf(':'); var name = e.AdditionalInformation.Substring(0, firstSeparator); var secondSeparator = e.AdditionalInformation.Substring(firstSeparator + 1).IndexOf(':'); var op = e.AdditionalInformation.Substring(firstSeparator + 1, secondSeparator).Trim(); var array = e.AdditionalInformation.Substring(firstSeparator + secondSeparator + 2).Trim(); if (array.Length > 0) { var uris = StringConverter.ParseCollection(new StringReader(array), 0, false).ToArray(); switch (op) { case "Update": Subject.OnNext(new NotifyInfo(name, NotifyInfo.OperationEnum.Update, uris)); break; case "Change": Subject.OnNext(new NotifyInfo(name, NotifyInfo.OperationEnum.Change, uris)); break; case "Delete": Subject.OnNext(new NotifyInfo(name, NotifyInfo.OperationEnum.Delete, uris)); break; default: Subject.OnNext(new NotifyInfo(name, NotifyInfo.OperationEnum.Insert, uris)); break; } } } } catch (Exception ex) { Logger.Error(e.Condition + e.AdditionalInformation + ex.ToString()); } }
private void PostgresNotificationReceived(object sender, NpgsqlNotificationEventArgs e) { var context = GlobalHost.ConnectionManager.GetHubContext <TicketsHub>(); string actionName = e.AdditionalInformation.ToString(); string actionType = ""; if (actionName.Contains("DELETE")) { actionType = "Delete"; } if (actionName.Contains("UPDATE")) { actionType = "Update"; } if (actionName.Contains("INSERT")) { actionType = "Insert"; } // Now show the tickets and actiontype (SignalR: call client function addMessage (see init.js)) context.Clients.All.addMessage(this.GetTicketsList(), actionType); }
/// <summary> /// Postgres notification event. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event arguments.</param> private void PostgresNotification(object sender, NpgsqlNotificationEventArgs e) { string info = e.AdditionalInformation; Console.WriteLine(@"Notification -->"); Console.WriteLine(@" DATA {0}", info); Console.WriteLine(@" CHANNEL {0}", e.Condition); Console.WriteLine(@" PID {0}", e.PID); this.labelNotifications.Dispatcher.Invoke(new Action(() => { labelNotifications.Text += "[" + DateTime.Now.ToString() + "] DATABASE Received: " + info + Environment.NewLine; })); if (PublishEvent(info)) { this.labelNotifications.Dispatcher.Invoke(new Action(() => { labelNotifications.Text += "[" + DateTime.Now.ToString() + "] Event Published! " + Environment.NewLine; })); } }
private void HandleNotification(object sender, NpgsqlNotificationEventArgs arguments) { var serializer = _memstateSettings.CreateSerializer(); try { var row = JsonConvert.DeserializeObject <Row>(arguments.AdditionalInformation); var command = (Command)serializer.Deserialize(row.Command); var record = new JournalRecord(row.Id, row.Written, command); if (_ready) { _handler(record); } else { lock (Lock) { if (_ready) { _handler(record); } else { _buffer.Enqueue(record); } } } } catch (Exception exception) { _log.LogError(exception, $"Exception occured in {GetType().Name}.HandleNotification"); } }
public static void NotifyDelegate(object o, NpgsqlNotificationEventArgs e) { switch (e.Channel) { case "arsenalum": { Debug.WriteLine($"MESSAGE FROM arsenalum: {e.Payload}"); Notify(e.Payload); } break; case "arsenalum_sse": { Debug.WriteLine($"MESSAGE FROM arsenalum_sse: {e.Payload}"); var request = JObject.Parse(e.Payload); if (Enum.TryParse <RequestTypes>(request.Value <string>("$type"), out var requestType)) { switch (requestType) { case RequestTypes.WRITING_TO_DATABASE_COMPLETED: { if (!Id64.TryParse(request["work_zone"]?.ToString(), out var workZone)) { return; } if (!Id64.TryParse(request["id"]?.ToString(), out var id)) { return; } Debug.WriteLine($"Values {workZone} {id}"); PlcClient.AddMSg(new MessageResponse(workZone, id)); } break; } } break; } } }
private void NotificationSupportHelper(Object sender, NpgsqlNotificationEventArgs args) { throw new InvalidOperationException(); }
private void OnNotification(object sender, NpgsqlNotificationEventArgs e) { throw new Exception(); }
private void _OnEvent(object sender, NpgsqlNotificationEventArgs npgsqlNotificationEventArgs) { var notifyObject = JSON.ToObject <NotificationObject>(npgsqlNotificationEventArgs.AdditionalInformation); var fqdn = $"{notifyObject.Schema}.{notifyObject.Table}"; var notify = false; foreach (var s in _listenOnTables) { var tablefqdn = $"{s.GetConnectionString().SchemaName}.{s.GetConnectionString().TableName}"; if (Wildcard.IsMatch(fqdn, tablefqdn)) { notify = true; break; } } if (!notify) { return; } var notifyObj = new TriggerNotification() { Pid = npgsqlNotificationEventArgs.PID, Condition = npgsqlNotificationEventArgs.Condition, Schema = notifyObject.Schema, Table = notifyObject.Table, Action = notifyObject.Action, EventData = notifyObject.Data }; //Dictionary<string, object> returnObject = null; //var table = GetTable(notifyObject.Table); //switch (notifyObject.Mode) //{ // case ListenMode.TableEntryPrimaryKeys: // returnObject = notifyObject.Data; // break; // case ListenMode.TableEntry: // if (notifyObject.Action == TriggerAction.Delete) { // returnObject = notifyObject.Data; // } else { // returnObject = table.QueryByPrimaryKey(notifyObject.Data).CloneTo<Dictionary<string, object>>(); // } // break; //} //var notifyObj = new TriggerNotification() //{ // Pid = npgsqlNotificationEventArgs.PID, // Condition = npgsqlNotificationEventArgs.Condition, // Schema = notifyObject.Schema, // Table = notifyObject.Table, // Action = notifyObject.Action, // EventData = returnObject //}; _tableNotificationSubject.OnNext(notifyObj); }
private void HandleNotification(object sender, NpgsqlNotificationEventArgs arguments) { _readWaiter.Set(); }
// handle notifications of a change in one of the monitored table private void _conn_Notification(object sender, NpgsqlNotificationEventArgs e) { JObject json = JObject.Parse(e.Payload); // get the name of the table that changed, if it's not the one this listener is watching, ignore it string table = (string)json["table"]; if (table.ToLower() != _table) { return; } // get the change type (update, delete, insert) string operation = (string)json["operation"]; DBNotification <T> notificationData = new DBNotification <T>(); notificationData.operation = operation; notificationData.table = (string)json["table"]; notificationData.schema = (string)json["schema"]; notificationData.Timestamp = (DateTime)json["timestamp"]; // get the key column name(s), and the key value(s) of the row that set off the trigger string key_columns = ((string)json["keycolumns"]).ToUpper(); string key_values = (string)json["keyvalues"]; string[] keycolsarray = key_columns.Split(","); string[] keyvalsarray = key_values.Split(","); PropertyInfo propInfo; if (operation == "DELETE") { notificationData.row = new T(); for (int i = 0; i < keycolsarray.Length; i++) { propInfo = notificationData.row.GetType().GetProperty(keycolsarray[i]); if (propInfo.PropertyType == typeof(Guid)) { propInfo.SetValue(notificationData.row, Guid.Parse(keyvalsarray[i])); } if (propInfo.PropertyType == typeof(Int32)) { propInfo.SetValue(notificationData.row, Int32.Parse(keyvalsarray[i])); } if (propInfo.PropertyType == typeof(string)) { propInfo.SetValue(notificationData.row, keyvalsarray[i]); } } } else { string where = " where "; for (int i = 0; i < keycolsarray.Length; i++) { if (i > 0) { where += " and "; } where += keycolsarray[i] + " = '" + keyvalsarray[i] + "'"; } // query for the row that changed or was inserted string query = "select row_to_json(t) from( select * from " + table + where + ") t;"; string jsonResult; using (NpgsqlConnection conn = new NpgsqlConnection(_connstring)) { conn.Open(); using (NpgsqlCommand command = conn.CreateCommand()) { command.CommandText = query; jsonResult = (string)command.ExecuteScalar(); } } // convert the row into an object of type T (very cool! I could use this elsewhere, like in DatabaseManager.LoadConfig() ) notificationData.row = JsonConvert.DeserializeObject <T>(jsonResult, new CustomJsonConvert()); } // raise an event to notify the app that the monitored table has changed, include the row data and operation type Notification?.Invoke(this, new PostgreSQLNotification(notificationData)); }
static void conn_Notification(object sender, NpgsqlNotificationEventArgs e) { Trace.WriteLine("conn_Notification"); }
protected override void _OnEvent(object sender, NpgsqlNotificationEventArgs npgsqlNotificationEventArgs) { var notifyObject = JSON.ToObject <NotificationObject>(npgsqlNotificationEventArgs.AdditionalInformation); var fqdn = $"{notifyObject.Schema}.{notifyObject.Table}"; var notify = false; foreach (var s in _listenOnTables) { if (Wildcard.IsMatch(fqdn, s)) { notify = true; break; } } if (!notify) { return; } Dictionary <string, object> returnObject = null; ObjectTable table; switch (_listenMode) { case ListenMode.TableEntryPrimaryKeys: returnObject = notifyObject.Data; break; case ListenMode.TableEntry: if (notifyObject.Action == TriggerAction.Delete) { returnObject = notifyObject.Data; } else { table = GetTable(notifyObject.Table); returnObject = table.QueryByPrimaryKey(notifyObject.Data).CloneTo <Dictionary <string, object> >(); } break; } var notifyObj = new TriggerNotification() { Pid = npgsqlNotificationEventArgs.PID, Condition = npgsqlNotificationEventArgs.Condition, Schema = notifyObject.Schema, Table = notifyObject.Table, Action = notifyObject.Action, EventData = returnObject }; //Console.WriteLine(Json.ToJson(notifyObj, true)); _tableNotificationSubject.OnNext(notifyObj); }