// methods private UpdateFlags BuildUpdateFlags(UpdateMessage message) { var flags = UpdateFlags.None; if (message.IsMulti) { flags |= UpdateFlags.Multi; } if (message.IsUpsert) { flags |= UpdateFlags.Upsert; } return flags; }
public override Status update (UpdateMessage updateMessage) { var title = new StringBuilder(updateMessage.message); title[0] = Char.ToUpper(title[0]); title.AppendFormat(" ({0}/{1})", updateMessage.iterationIndex + 1, updateMessage.iterationCount); form.BeginInvoke(new MethodInvoker(() => form.Text = title.ToString())); if (TaskbarManager.IsPlatformSupported) { TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal); TaskbarManager.Instance.SetProgressValue(updateMessage.iterationIndex + 1, updateMessage.iterationCount); } return form.CancelRequested ? IterationListener.Status.Cancel : IterationListener.Status.Ok; }
public void UpdateMessage(UpdateMessage msg) { using (var conn = new SqlConnection(SqlBase.ConnectionString)) { conn.Open(); using (var trans = conn.BeginTransaction()) { try { using (var cmd = new SqlCommand("MessageUpdate", conn, trans)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Id", msg.Id).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@ApplicationId", NullIfZero(msg.ApplicationId)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@From", msg.From).DbType = DbType.String; cmd.Parameters.AddWithValue("@Sender", msg.Sender).DbType = DbType.String; cmd.Parameters.AddWithValue("@Subject", msg.Subject).DbType = DbType.String; cmd.Parameters.AddWithValue("@Body", msg.Body).DbType = DbType.String; if (msg.Connection != null) { cmd.Parameters.AddWithValue("@Host", msg.Connection.Host).DbType = DbType.String; cmd.Parameters.AddWithValue("@Port", msg.Connection.Port).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@EnableSsl", msg.Connection.EnableSsl).DbType = DbType.Boolean; } cmd.ExecuteNonQuery(); } UpdateMessageToChild(msg, conn, trans); UpdateMessageCcChild(msg, conn, trans); UpdateMessageBccChild(msg, conn, trans); UpdateMessageReplyToChild(msg, conn, trans); // TODO: update other children trans.Commit(); } catch { trans.Rollback(); throw; } } } }
public HttpResult Put(UpdateMessage request) { // PUT does not support create if (request.Id <= 0) return new HttpResult(HttpStatusCode.NotFound, "Message was not found."); var ds = new DataStore(); ds.UpdateMessage(request); // Resend e-mail if requested if (request.ResendEmail) { var savedMesssage = ds.GetMessage(request.Id); var client = new EmailClient(); var emailResult = client.Send(savedMesssage); if (emailResult.Success) { ds.InsertMessageStatus(request.Id, 2); } else { ds.InsertMessageStatus(request.Id, 3, emailResult.Message, emailResult.SmtpException); return new HttpResult(HttpStatusCode.OK, "Message was updated, but e-mail failed to send."); } } return new HttpResult(HttpStatusCode.OK, "Message was updated."); }
private static Message Convert(string exchagenCode, UpdateCommand updateCommand) { XmlElement addElement = updateCommand.Content["Add"]; XmlElement modifyElement = updateCommand.Content["Modify"]; XmlElement deleteElement = updateCommand.Content["Delete"]; UpdateMessage updateMessage = new UpdateMessage() { ExchangeCode = exchagenCode }; if (addElement != null) updateMessage.AddSettingSets = CommandConvertor.ToSettingSet(addElement); if (deleteElement != null) updateMessage.DeletedSettings = CommandConvertor.ToSettingSet(deleteElement); if (modifyElement != null) { List<ExchangeUpdateData> exchangeUpdateDatas = new List<ExchangeUpdateData>(); exchangeUpdateDatas = CommandConvertor.ToExchangeUpdateDatas(modifyElement); updateMessage.ExchangeUpdateDatas = exchangeUpdateDatas.ToArray(); } return updateMessage; }
public Task SendTextMessageAsync(UpdateMessage message, string text, ParseMode parseMode = ParseMode.Default) { _botResponse.Response(text); return(Task.CompletedTask); }
public override Status update (UpdateMessage updateMessage) { try { if (_canceled) return Status.Cancel; if (updateMessage.iterationCount > 10) //prevent false low-number invocations { /*if (LogUpdate != null) LogUpdate(String.Format("Processing spectra {0} of {1}", updateMessage.iterationIndex + 1, updateMessage.iterationCount), _info);*/ if (PercentageUpdate != null) PercentageUpdate(updateMessage.iterationIndex + 1, updateMessage.iterationCount, _info); } return Status.Ok; } catch { return Status.Cancel; } }
private static bool IsBotCommand(this UpdateMessage updateMessage) { return(updateMessage.Message?.Entities != null && updateMessage.Message.Entities.Any(x => x.Type == "bot_command")); }
public void ProcessRealQueueMessages(int maxMessageCount) { var halfQueueSize = (int)(maxMessageCount / 2); var config = new AppConfiguration(); //clear normal queue var queue = new MessageQueue(config.NormalQueueName); queue.Purge(); var messageManager = new MsmqManager(config.NormalQueueName, config.PoisonQueueName); List <UpdateMessage> processMessages = new List <UpdateMessage>(); IListener listener = null; List <string> calledStoredProcedures = new List <string>(); //mock bd manager and stop processing of messages when half and all messages are read. Simulate start/pause/continue var dbManager = new Mock <IDatabaseManager>(); dbManager.Setup(x => x.GetImportSettings(It.IsAny <string>(), It.IsAny <int>())).Returns(new Dictionary <string, ImportTypeSettings>()); dbManager.Setup(x => x.Execute(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <SqlParameter[]>())).Callback((string connectionString, string spName, SqlParameter[] parameters) => { calledStoredProcedures.Add(spName); if (halfQueueSize == calledStoredProcedures.Count || maxMessageCount == calledStoredProcedures.Count) { listener.CanProcess = false; } }).Returns(1); dbManager.Setup(x => x.Execute(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>(), It.IsAny <SqlParameter[]>())).Callback((string connectionString, string spName, int timeout, SqlParameter[] parameters) => { calledStoredProcedures.Add(spName); if (halfQueueSize == calledStoredProcedures.Count || maxMessageCount == calledStoredProcedures.Count) { listener.CanProcess = false; } }).Returns(1); listener = new Listener(config, dbManager.Object, messageManager); Hashtable activeDatabases = new Hashtable(); Hashtable timestamps = new Hashtable(); for (int i = 0; i < maxMessageCount; i++) { var singleMessage = new UpdateMessage() { DatabaseID = 1, ExternalId = "1", DSN = "123", EntityTypeId = 20, Action = (int)MessageActionType.UpdatedProductNutrient, GroupID = 1, ProductID = i, ArrivedTime = DateTime.UtcNow }; messageManager.mqSend(singleMessage, MessagePriority.Normal); } //try process half messages listener.CanProcess = true; listener.ExecuteAsync(activeDatabases, timestamps); var items = queue.GetAllMessages(); items.Should().NotBeEmpty(); items.Length.Should().Be(maxMessageCount - halfQueueSize); calledStoredProcedures.Count.Should().Be(halfQueueSize); //try process another half listener.CanProcess = true; listener.ExecuteAsync(activeDatabases, timestamps); items = queue.GetAllMessages(); items.Should().BeEmpty(); calledStoredProcedures.Count.Should().Be(maxMessageCount); }
public void SendUpdate <TScope>(UpdateMessage update, string receivingSessionId) where TScope : Scope <object> { SessionManager.SendUpdateToClient(update, receivingSessionId); }
public static UpdateMessageType ParseMessageType(this UpdateMessage message) { if (message.Message != null) { var messageText = message.Message.Text; if (message.IsBotCommand()) { if (messageText.StartsWith(BotCommands.CreateOccasion, StringComparison.OrdinalIgnoreCase)) { return(UpdateMessageType.GetNewOccasionName); } if (messageText.StartsWith(BotCommands.DeleteOccasion, StringComparison.OrdinalIgnoreCase)) { return(UpdateMessageType.GetOccasionsForDelete); } if (messageText.StartsWith(BotCommands.StartPoll, StringComparison.OrdinalIgnoreCase)) { return(UpdateMessageType.GetOccasionsToStart); } if (messageText.StartsWith(BotCommands.StopPoll, StringComparison.OrdinalIgnoreCase)) { return(UpdateMessageType.StopActivePoll); } if (messageText.StartsWith(BotCommands.Stats, StringComparison.OrdinalIgnoreCase)) { return(UpdateMessageType.Stats); } } } var replyToMessage = message.Message?.ReplyToMessage; if (replyToMessage != null) { if (replyToMessage.From.IsBot) { if (replyToMessage.Text.Contains(Messages.NewOccasionName, StringComparison.OrdinalIgnoreCase)) { return(UpdateMessageType.CreateOccasion); } } } var callbackQuery = message.CallbackQuery; if (callbackQuery != null) { var callbackQueryData = callbackQuery.Data.Split(';'); if (callbackQueryData.Length == 2 && callbackQueryData[0] == BotCommands.DeleteOccasion) { return(UpdateMessageType.DeleteOccasion); } if (callbackQueryData.Length == 2 && callbackQueryData[0] == BotCommands.StartPoll) { return(UpdateMessageType.StartPoll); } } var pollAnswer = message.PollAnswer; if (pollAnswer != null) { return(UpdateMessageType.PollAnswered); } return(UpdateMessageType.Unknown); }
public TransportUpdateEventArgs(UpdateMessage message, SwimHost remote) { Message = message; Remote = remote; }
public APImanager(UpdateMessage mainCom) { MainComm = mainCom; WSOutput = MainComm; MQTToutput = MainComm; }
//private bool updateMutexActive = false; public override Status update(UpdateMessage updateMessage) { //if (updateMutexActive) // return IterationListener.Status.Ok; //updateMutexActive = true; var title = new StringBuilder(updateMessage.message); title[0] = Char.ToUpper(title[0]); title.AppendFormat(" ({0}/{1})", updateMessage.iterationIndex + 1, updateMessage.iterationCount); form.BeginInvoke(new MethodInvoker(() => { try { form.Text = title.ToString(); } catch (Exception e) { MessageBox.Show(e.ToString()); throw; } })); return IterationListener.Status.Ok; }
public override Status update(UpdateMessage updateMessage) { var result = merger.OnMergingProgress(null, updateMessage.iterationIndex, updateMessage.iterationCount); return result ? Status.Cancel : Status.Ok; }
private void Process(UpdateMessage updateMessage) { this._ExchangeDataManager.ProcessUpdateMessage(updateMessage); }
public async Task HandleAsync(UpdateMessage message) { await _botClient.SendTextMessageAsync(message, MessageCode.Hello); }
private void PersonUpdated(UpdateMessage <PersonWrapper> message) { DirectorId = message.Model.Id; Load(); }
/// <summary> /// update and make a tunal for output /// </summary> /// <param name="um"></param> public void ImplementDelegate(UpdateMessage um) { this.um = um; }
public override Status update (UpdateMessage updateMessage) { return form.update(updateMessage); }
/// <summary> /// Writes the message. /// </summary> /// <param name="message">The message.</param> public void WriteMessage(UpdateMessage message) { Ensure.IsNotNull(message, "message"); var messageDocument = new BsonDocument { { "opcode", "update" }, { "requestId", message.RequestId }, { "database", message.CollectionNamespace.DatabaseNamespace.DatabaseName }, { "collection", message.CollectionNamespace.CollectionName }, { "isMulti", true, message.IsMulti }, { "isUpsert", true, message.IsUpsert }, { "query", message.Query }, { "update", message.Update } }; var jsonWriter = CreateJsonWriter(); var messageContext = BsonSerializationContext.CreateRoot(jsonWriter); BsonDocumentSerializer.Instance.Serialize(messageContext, messageDocument); }
private void RecipeUpdated(UpdateMessage <RecipeWrapper> _) => Load();
internal void MessageClient_UpdateMessageNotifyReceived(UpdateMessage message) { App.MainFrameWindow.Dispatcher.BeginInvoke((Action)delegate() { this.ExchangeDataManager.ProcessUpdateMessage(message); }); }
public async Task HandleAsync(UpdateMessage message) { await _botClient.SendTextButtonsMenuAsync(message, ButtonStructure.TopMenuStructure); }
private void NotifyInstrumentUpdate(ExchangeMetadataType metadataType, Dictionary<string, string> fieldsAndValues, Guid[] instrumentIds) { ExchangeUpdateData[] exchangeUpdateDatas = new ExchangeUpdateData[instrumentIds.Length]; for (int i = 0; i < instrumentIds.Length; i++) { Dictionary<string, string> fieldsAndValues2 = new Dictionary<string, string>(fieldsAndValues); fieldsAndValues2.Add(ExchangeFieldSR.ID, instrumentIds[i].ToString()); exchangeUpdateDatas[i] = new ExchangeUpdateData() { ExchangeMetadataType = metadataType, FieldsAndValues = fieldsAndValues2, }; } UpdateMessage updateMessage = new UpdateMessage() { ExchangeCode = this.ExchangeCode, ExchangeUpdateDatas = exchangeUpdateDatas }; MainService.ClientManager.Dispatch(updateMessage); }
public void HandleUpdate(UpdateMessage message, UpdateHandlerInterface.HandleUpdateCallback response_callback) { OutgoingMessage response = new OutgoingMessage(message.message.chat.id, "Hello " + message.message.from.first_name); response_callback(response); }
private static void UpdateTaskFields(ClarizenUtils utils, string csvReadFile, string targetType) { try { using (var csv = new CsvParser(new StreamReader(csvReadFile))) { int rowIndex = 0; while (csv.ReadNextRecord()) { foreach (string field in csv.HeaderFields) { if (field.Equals("TASKID", StringComparison.InvariantCultureIgnoreCase)) continue; object newValue = ParseValue(csv.CurrentDic[field], field); var task = new GenericEntity { Id = new EntityId {TypeName = targetType, Value = csv.CurrentDic["TASKID"]} }; //Create a FieldValue representing the Manager field var managerField = new FieldValue {FieldName = field, Value = newValue}; //Set the field value to the external identifier of the new manager task.Values = new[] {managerField}; var updateMsg = new UpdateMessage {Entity = task}; //Update the entity Result result = utils.ExecuteQuery(new BaseMessage[] {updateMsg}); string dir = Path.GetDirectoryName(csvReadFile); if (dir == null) throw new ArgumentNullException("csvReadFile"); dir = Path.Combine(dir, "Handled"); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); string resultFileName = Path.Combine(dir, string.Format("{0}_Result_{1}.csv", Path.GetFileNameWithoutExtension( csvReadFile), rowIndex)); string combineText = result.Success ? "Success" : "Failure"; File.WriteAllText(resultFileName, combineText); string p = Path.GetDirectoryName(csvReadFile); string d = Path.GetFileName(csvReadFile); if (p != null) { if (d != null) { string destFileName = Path.Combine(Path.Combine(p, "Handled"), d); if (File.Exists(destFileName)) File.Delete(destFileName); File.Move(csvReadFile, destFileName); } } } rowIndex++; } } } catch (Exception ex) { Console.WriteLine(string.Format("File:{0}\r\n{1}\r\n", csvReadFile, ex)); } }
public override Status update(UpdateMessage updateMessage) { var result = merger.OnMergingProgress(null, updateMessage.iterationIndex, updateMessage.iterationCount); return(result ? Status.Cancel : Status.Ok); }
private void UpdateMessageToChild(UpdateMessage msg, SqlConnection conn, SqlTransaction trans) { // Get list of messages first to determine what items need inserting or deleting var messageToList = GetMessageToByMessageId(msg.Id, conn, trans).ToList(); // Delete To's foreach (var currentTo in messageToList.Where(currentTo => !msg.To.Any(t => t.Equals(currentTo)))) { using (var cmd = new SqlCommand("MessageToDelete", conn, trans)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@MessageId", msg.Id).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@To", currentTo).DbType = DbType.String; cmd.ExecuteNonQuery(); } } // Insert new To's foreach (var to in msg.To.Where(to => !messageToList.Any(t => t.Equals(to)))) { using (var cmd = new SqlCommand("MessageToInsert", conn, trans)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@MessageId", msg.Id).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@To", to).DbType = DbType.String; cmd.ExecuteNonQuery(); } } }
private void ProcessUpdateMessage(UpdateMessage originalMessage, Queue <RequestMessage> messageQueue, ConnectionId connectionId, UpdateMessageBinaryEncoder encoder, Stopwatch stopwatch) { var commandName = "update"; int requestId = originalMessage.RequestId; var operationId = EventContext.OperationId; var expectedResponseType = ExpectedResponseType.None; BsonValue upsertedId = null; int gleRequestId; WriteConcern writeConcern; if (TryGetWriteConcernFromGLE(messageQueue, out gleRequestId, out writeConcern)) { requestId = gleRequestId; expectedResponseType = ExpectedResponseType.GLE; } if (_startedEvent != null) { var decodedMessage = encoder.ReadMessage(RawBsonDocumentSerializer.Instance); try { if (_shouldTrackState) { // GLE result on older versions of the server didn't return // the upserted id when it wasn't an object id, so we'll // attempt to get it from the messages. if (!decodedMessage.Update.TryGetValue("_id", out upsertedId)) { decodedMessage.Query.TryGetValue("_id", out upsertedId); } } var entry = new BsonDocument { { "q", decodedMessage.Query }, { "u", decodedMessage.Update }, { "upsert", decodedMessage.IsUpsert }, { "multi", decodedMessage.IsMulti } }; var command = new BsonDocument { { commandName, decodedMessage.CollectionNamespace.CollectionName }, { "updates", new BsonArray(new [] { entry }) } }; if (writeConcern == null) { command["writeConcern"] = WriteConcern.Unacknowledged.ToBsonDocument(); } else if (!writeConcern.IsServerDefault) { command["writeConcern"] = writeConcern.ToBsonDocument(); } var @event = new CommandStartedEvent( commandName, command, decodedMessage.CollectionNamespace.DatabaseNamespace, operationId, requestId, connectionId); _startedEvent(@event); } finally { var disposable = decodedMessage.Query as IDisposable; if (disposable != null) { disposable.Dispose(); } disposable = decodedMessage.Update as IDisposable; if (disposable != null) { disposable.Dispose(); } } } if (_shouldTrackState) { _state.TryAdd(requestId, new CommandState { CommandName = commandName, OperationId = operationId, Stopwatch = Stopwatch.StartNew(), ExpectedResponseType = expectedResponseType, UpsertedId = upsertedId }); } }
/// <summary> /// Writes the message. /// </summary> /// <param name="message">The message.</param> public void WriteMessage(UpdateMessage message) { Ensure.IsNotNull(message, "message"); var binaryWriter = CreateBinaryWriter(); var stream = binaryWriter.BsonStream; var startPosition = stream.Position; stream.WriteInt32(0); // messageSize stream.WriteInt32(message.RequestId); stream.WriteInt32(0); // responseTo stream.WriteInt32((int)Opcode.Update); stream.WriteInt32(0); // reserved stream.WriteCString(message.CollectionNamespace.FullName); stream.WriteInt32((int)BuildUpdateFlags(message)); WriteQuery(binaryWriter, message.Query); WriteUpdate(binaryWriter, message.Update, message.UpdateValidator); stream.BackpatchSize(startPosition); }
private void OnUpdateMessage(Updates update) { UpdateMessage?.Invoke(this, update); }