protected override async Task WhenAsync( CancellationToken cancellationToken) { _settingsReceived = await _settingsSubscription .ReceiveAsync(2, cancellationToken) .ConfigureAwait(false); }
private static async Task ConsumeAsync(ISourceBlock <string> source, string pathToFolder, int maxDegreeOfParallelism, CancellationToken token, AbstractLogger logger) { await Task.Run(async() => { var documentPipeline = new DocumentsPipeline(AppDomain.CurrentDomain.BaseDirectory, pathToFolder, maxDegreeOfParallelism, token); documentPipeline.OnFinished += (s) => logger.WriteLine($"Сonsumer finished processing {s}"); logger.WriteLine("Consumer is ready"); while (await source.OutputAvailableAsync()) { var newFile = await source.ReceiveAsync(); await documentPipeline.Processing(newFile); logger.WriteLine($"Consumer started processing {newFile}"); } logger.WriteLine("Buffer is not available"); await documentPipeline.Complete(); logger.WriteLine("Consumer was stopped"); }); }
public async Task Factory_LogsFrameworkOptions() { IOptionsLoggingSource source = new OptionsLoggingSource(); IOptionsFactory <LoggerFilterOptions> factory = new WebJobsOptionsFactory <LoggerFilterOptions>( Enumerable.Empty <IConfigureOptions <LoggerFilterOptions> >(), Enumerable.Empty <IPostConfigureOptions <LoggerFilterOptions> >(), source, new LoggerFilterOptionsFormatter()); LoggerFilterOptions options = factory.Create(null); source.LogStream.Complete(); IList <string> logs = new List <string>(); ISourceBlock <string> logStream = source.LogStream; while (await logStream.OutputAvailableAsync(CancellationToken.None)) { logs.Add(await logStream.ReceiveAsync()); } string log = logs.Single(); string expected = "LoggerFilterOptions" + Environment.NewLine + "{" + Environment.NewLine + " \"MinLevel\": \"Trace\"," + Environment.NewLine + " \"Rules\": []" + Environment.NewLine + "}"; Assert.Equal(expected, log); }
public async Task Factory_LogsOptions() { IOptionsLoggingSource source = new OptionsLoggingSource(); IOptionsFactory <TestOptions> factory = new WebJobsOptionsFactory <TestOptions>( Enumerable.Empty <IConfigureOptions <TestOptions> >(), Enumerable.Empty <IPostConfigureOptions <TestOptions> >(), source); TestOptions options = factory.Create(null); source.LogStream.Complete(); IList <string> logs = new List <string>(); ISourceBlock <string> logStream = source.LogStream; while (await logStream.OutputAvailableAsync(CancellationToken.None)) { logs.Add(await logStream.ReceiveAsync()); } string log = logs.Single(); string expected = "TestOptions" + Environment.NewLine + "{" + Environment.NewLine + " \"SomeValue\": \"abc123\"" + Environment.NewLine + "}"; Assert.Equal(expected, log); }
private async Task <Action[]> MergeActionsAsync(ISourceBlock <Action[]> actionSource, int?take) { var result = new Action[0]; while (await actionSource.OutputAvailableAsync()) { Console.WriteLine($"[{DateTime.Now:T}] OutputAvailableAsync"); var next = await actionSource.ReceiveAsync(); Console.WriteLine($"[{DateTime.Now:T}] Merging next result {next.Length}. Total {result.Length}"); if (next.Length == 0) { continue; } IEnumerable <Action> current = new HashSet <Action>(result.Concat(next)).OrderByDescending(action => action.ActionDateTime); if (take.HasValue) { current = current.Take(take.Value); } result = current.ToArray(); Console.WriteLine($"[{DateTime.Now:T}] Merged with next result {next.Length}. Total {result.Length}"); } return(result); }
protected virtual async Task BackgroundLoopMain(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested && await metricQueue.OutputAvailableAsync(cancellationToken)) { await metricWriteProcessor.Invoke(await metricQueue.ReceiveAsync(cancellationToken)); } }
//Semi Batch processor async Task ConsumerAsync(ISourceBlock <Uri> syncBlock, ProcessResult processResult) { //!SPOT: blocking GetConsumingEnumerable() vs non-blocking OutputAvailableAsync while (await syncBlock.OutputAvailableAsync()) //Waits until an available item appear { var uri = await syncBlock.ReceiveAsync(); //Waits until there is an available item await WorkerAsync(uri, processResult); } }
protected override async Task WhenAsync( CancellationToken cancellationToken) { Session.Open(SynStream.PriorityLevel.High, headers: new NameValueHeaderBlock( ("header1", new[] { "value1" }))); _synStream = await _synStreamSubscription .ReceiveAsync(cancellationToken) .ConfigureAwait(false); }
protected override async Task WhenAsync( CancellationToken cancellationToken) { await _stream.SendAsync(Encoding.UTF8.GetBytes("my data"), cancellationToken : cancellationToken) .ConfigureAwait(false); _dataSent = await _dataSubscription .ReceiveAsync(cancellationToken) .ConfigureAwait(false); }
internal static async Task <IEnumerable <T> > ReceiveAsync <T>( this ISourceBlock <T> source, int numberOfItems = 1, CancellationToken cancellationToken = default) { return(await Task.WhenAll( Enumerable.Range(1, numberOfItems) .Select( _ => source.ReceiveAsync(cancellationToken))) .ConfigureAwait(false)); }
public static async Task <IReadOnlyCollection <TItem> > ReceiveAllData <TItem>(this ISourceBlock <TItem> sourceBlock) { var items = new List <TItem>(); while (await sourceBlock.OutputAvailableAsync()) { items.Add(await sourceBlock.ReceiveAsync()); } return(items.AsReadOnly()); }
protected override async Task WhenAsync( CancellationToken cancellationToken) { await Server.SendAsync( new WindowUpdate(_stream.Id, UInt31.MaxValue), cancellationToken) .ConfigureAwait(false); _rstStream = await _rstStreamSubscription .ReceiveAsync(CancellationToken) .ConfigureAwait(false); }
protected override async Task WhenAsync( CancellationToken cancellationToken) { await Server.SendAsync( SynReply.Accept(_stream.Id), cancellationToken) .ConfigureAwait(false); _rstStream = await _rstStreamSubscription .ReceiveAsync(CancellationToken) .ConfigureAwait(false); }
protected override async Task WhenAsync( CancellationToken cancellationToken) { await _stream.SendHeadersAsync(new NameValueHeaderBlock( ("header1", new[] { "value1", "value2" })), cancellationToken : cancellationToken) .ConfigureAwait(false); _headersSent = await _headersSubscription .ReceiveAsync(cancellationToken) .ConfigureAwait(false); }
public static async Task <IList <T> > ReceiveAllAsync <T>(this ISourceBlock <T> target) { var items = new List <T>(); while (await target.OutputAvailableAsync()) { items.Add(await target.ReceiveAsync()); } await target.Completion; return(items); }
private async System.Threading.Tasks.Task WriteOutputAsync(ISourceBlock <string> source) { while (await source.OutputAvailableAsync()) { string data = await source.ReceiveAsync(); if (OutputPane != null) { OutputPane.OutputStringThreadSafe(data); OutputPane.OutputStringThreadSafe("\r\n"); } } }
/// <summary> /// Tries to asynchronously receives a value from a specified source. /// </summary> /// <typeparam name="TOutput">The type of data contained in the source to receive.</typeparam> /// <param name="source">The source from which to receive the value.</param> /// <returns> /// A task that represents the asynchronous receive operation. When an item value is successfully received from the source, /// the returned task is completed and its <see cref="Task{T}.Result"/> returns a successful <see cref="TryValue{TOutput}"/> /// containing the received value. If an item value cannot be retrieved because the source is empty and completed, the returned /// task is completed and its <see cref="Task{T}.Result"/> returns <see cref="TryValue.None()"/>. /// </returns> public static async Task <TryValue <TOutput> > TryReceiveAsync <TOutput>(this ISourceBlock <TOutput> source) { Contracts.Requires.That(source != null); try { return(TryValue.New(await source.ReceiveAsync().DontMarshallContext())); } catch (InvalidOperationException) { return(TryValue.None <TOutput>()); } }
static async Task <int> ConsumeAsync(ISourceBlock <byte[]> source) { int bytesProcessed = 0; while (await source.OutputAvailableAsync()) { byte[] data = await source.ReceiveAsync(); bytesProcessed += data.Length; } return(bytesProcessed); }
// TCP Consumer static async Task <BufferBlockWrapperTCP> ConsumeAsyncTCP(ISourceBlock <BufferBlockWrapperTCP> source) { // Read from the source buffer while (await source.OutputAvailableAsync()) { BufferBlockWrapperTCP wrapper = await source.ReceiveAsync(); TCPMessage msg = wrapper.message; ConsumeMessageTCP(msg, wrapper.netID); } return(null); }
/// <summary> /// Tries to asynchronously receives a value from a specified source. /// </summary> /// <typeparam name="TOutput">The type of data contained in the source to receive.</typeparam> /// <param name="source">The source from which to receive the value.</param> /// <param name="timeout"> /// The maximum time interval, in milliseconds, to wait for the synchronous operation to complete, /// or an interval that represents -1 milliseconds to wait indefinitely. /// </param> /// <param name="cancellation">The token to use to cancel the receive operation.</param> /// <returns> /// A task that represents the asynchronous receive operation. When an item value is successfully received from the source, /// the returned task is completed and its <see cref="Task{T}.Result"/> returns a successful <see cref="TryValue{TOutput}"/> /// containing the received value. If an item value cannot be retrieved because the source is empty and completed, the returned /// task is completed and its <see cref="Task{T}.Result"/> returns <see cref="TryValue.None()"/>. /// </returns> public static async Task <TryValue <TOutput> > TryReceiveAsync <TOutput>( this ISourceBlock <TOutput> source, TimeSpan timeout, CancellationToken cancellation) { Contracts.Requires.That(source != null); Contracts.Requires.That(timeout.IsDuration()); try { return(TryValue.New(await source.ReceiveAsync(timeout, cancellation).DontMarshallContext())); } catch (InvalidOperationException) { return(TryValue.None <TOutput>()); } }
public static async Task <String> take(ISourceBlock <String> source) { String cake = null; while (await source.OutputAvailableAsync()) { //cake = source.Receive(); cake = await source.ReceiveAsync(); Console.WriteLine(Thread.CurrentThread.Name + " takes " + cake); } //Console.WriteLine(Thread.CurrentThread.Name + " takes " + cake); return(cake); }
/// <summary> /// Asynchronously pull messages from a block, and send it to the connected server /// </summary> /// <param name="block"></param> /// <returns></returns> public async void SendBlockMessagesToServer(ISourceBlock <String> block) { using (var stream = client.GetStream()) using (var writer = new StreamWriter(stream, Encoding.ASCII)) { while (await block.OutputAvailableAsync()) { var message = await block.ReceiveAsync(); writer.WriteLine(message); writer.Flush(); Console.WriteLine("Sent to server: " + message); } } }
private async Task ProcessLogs() { ISourceBlock <string> source = _source.LogStream; try { while (await source.OutputAvailableAsync(_cts.Token)) { _logger.LogInformation(await source.ReceiveAsync()); } } catch (OperationCanceledException) { // This occurs during shutdown. } }
/// <summary> /// Consumes/processes string data from the ISourceBlock/Buffer /// and will write out the data to the specified directory path as PDF files /// </summary> /// <param name="source"></param> /// <param name="destDir"></param> /// <returns>Count of EPA files written out</returns> static async Task <int> ConsumeAsyncPdf(ISourceBlock <InputDataHolder> source, string destDir) { int count = 0; while (await source.OutputAvailableAsync()) { var dd = await source.ReceiveAsync(); var outPath = Path.Combine(destDir, dd.Item1 + ".pdf"); using (var fs = new FileStream(outPath, FileMode.Create)) { CreateDoc(String.Join(", ", dd.Item2), fs); Console.WriteLine("pdf file written to {0}", outPath); } } return(count); }
// Demonstrates the consumption end of the producer and consumer pattern. private static async Task <int> ConsumeAsync(ISourceBlock <byte[]> source) { // Initialize a counter to track the number of bytes that are processed. var bytesProcessed = 0; // Read from the source buffer until the source buffer has no // available output data. while (await source.OutputAvailableAsync()) { var data = await source.ReceiveAsync().ConfigureAwait(false); // Increment the count of bytes received. bytesProcessed += data.Length; } return(bytesProcessed); }
protected override async Task WhenAsync( CancellationToken cancellationToken) { ReadResult data; do { data = await _stream.ReceiveAsync(cancellationToken : cancellationToken) .ConfigureAwait(false); _dataReceived.AddRange(data.Buffer.ToArray()); } while (data.IsCompleted == false); _flowControlMessages.AddRange(await _windowUpdateSubscription .ReceiveAsync(2, cancellationToken) .ConfigureAwait(false)); }
public static async IAsyncEnumerable <T> ToAsyncEnumerable <T>(this ISourceBlock <T> block, [EnumeratorCancellation] CancellationToken cancellationToken = default) { while (!block.Completion.IsCompleted) { T item; try { item = await block.ReceiveAsync(cancellationToken); } catch (InvalidOperationException) { break; } yield return(item); } await block.Completion; }
private async Task SendUpdates(ISourceBlock <PriceUpdate> input, IServerStreamWriter <PriceUpdate> output, CancellationToken cancel) { try { while (true) { var data = await input.ReceiveAsync(cancel); await output.WriteAsync(data); } } catch (Exception ex) { Console.Error.WriteLine(ex); throw; } }
internal async Task ProcessLogs() { ISourceBlock <ConsoleLog> source = _source.LogStream; try { while (await source.OutputAvailableAsync(_cts.Token)) { var consoleLog = await source.ReceiveAsync(); _logger.Log(consoleLog.Level, consoleLog.Message); } } catch (OperationCanceledException) { // This occurs during shutdown. } }
/// <summary> /// Receives an envelope from the buffer. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="buffer">The buffer.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> /// <exception cref="System.InvalidOperationException"></exception> private async Task <T> ReceiveEnvelopeFromBufferAsync <T>(ISourceBlock <T> buffer, CancellationToken cancellationToken) where T : Envelope, new() { if (State < SessionState.Established) { throw new InvalidOperationException($"Cannot receive envelopes in the '{State}' session state"); } try { return(await buffer.ReceiveAsync(cancellationToken).ConfigureAwait(false)); } catch (InvalidOperationException ex) when(buffer.Completion.IsCompleted) { await _consumeTransportTask.ConfigureAwait(false); throw new InvalidOperationException("The channel listener task is complete and cannot receive envelopes", ex); } }
async Task ProcessMessages(ISourceBlock<Message> queue) //обрабатываю сообщения в буфере { Message message; while (await queue.OutputAvailableAsync()) { message = (await queue.ReceiveAsync()); User user; try { using (var repository = new Repository<DutyBotDbContext>()) { user = repository.Get<User>(u => u.TlgNumber == message.chat.id); if (user == null) { user = new User { Name = message.chat.first_name, TlgNumber = message.chat.id, State = -1, Login = "", Password = "", TicketNumber = "" }; repository.Create(user); } } } catch (Exception) { _bot.SendMessage(message.chat.id, "Что-то пошло не так при обращении к базе данных. Дальнейшая работа не возможна."); Thread.Sleep(5000); return; } try { using (var repository = new Repository<DutyBotDbContext>()) { user = repository.Get<User>(u => u.Id == user.Id); switch (user.State) //смотрю, в каком статусе пользователь //- 1 его нет, 0 ззнакомство с DUtyBot, 1 Ввод пароля, 2, проверка доступа в jira, //3 основной статус, ожидаем команды, 4 пользователь решает что делать с тикетом, который получил от бота по кнопке Проверь тикеты //5 идёт мониторинг тикетов, пользователь получает уведомления, 6 пользователь решает что делать с тикетом, который получил при мониторинге { case -1: _bot.SendMessage(message.chat.id, "Привет, " + message.chat.first_name + @"! Меня зовут DutyBot, я создан, чтобы помогать дежурить. Давай знакомиться! ", "{\"keyboard\": [[\"Рассказать DutyBot'у о себе\"], [\"Не хочу знакомиться, ты мне не нравишься\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}"); user.State = 0; break; case 0: if ((message.text) == "Рассказать DutyBot'у о себе" | (message.text) == "Ввести учётку еще раз") { _bot.SendMessage(message.chat.id, @"Чтобы мы могли работать в Jira, мне нужны твои учётные данные. Напиши мне свой логин в формате d.bot и нажми отправить. Твои данные будут относительно безопасно храниться на сервере"); user.Name = message.chat.first_name; user.TlgNumber = message.chat.id; user.State = 1; break; } if ((message.text) == "Не хочу знакомиться, ты мне не нравишься") { _bot.SendMessage(message.chat.id, @"Очень жаль, но если надумешь, пиши. Я забуду об этом неприятном разговоре"); repository.Delete(user); } break; case 1: _bot.SendMessage(message.chat.id, @"Теперь напиши пароль"); user.Login = message.text; user.State = 2; break; case 2: user.Password = message.text; _bot.SendMessage(message.chat.id, @"Отлично, сейчас я проверю, есть ли у тебя доступ в Jira"); if (JiraAddFuncions.CheckConnection(_jiraConn, user.Login, user.Password)) { _bot.SendMessage(message.chat.id, @"Всё хорошо, можно начинать работу", "{\"keyboard\": [[\"Начнём\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}"); user.Password = message.text; user.State = 3; break; } _bot.SendMessage(message.chat.id, @"Доступа к JIra нет. Возможно учётные данные не верны. Давай попробуем ввести их еще раз. ", "{\"keyboard\": [[\"Ввести учётку еще раз\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}"); user.State = 0; break; case 3: switch (message.text) { case "Начнём": _bot.SendMessage(message.chat.id, "Просто напиши мне сообщение, когда я тебе понадоблюсь. В ответ я пришлю меню с вариантами моих действий. Вот такое ↓", "{\"keyboard\": [[\"Кто сейчас дежурит?\"], [\"Проверь тикеты\"], [\"Помоги с дежурством\"], [\"Пока ничем\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}"); break; case "Кто сейчас дежурит?": _bot.SendMessage(message.chat.id, DbReader.Readrespersone(), "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}"); break; case "Проверь тикеты": _jiraConn = Jira.CreateRestClient(_jiraParam.Value, user.Login, user.Password); try { var issues = _jiraConn.GetIssuesFromJql(_filterParam.Value); IList<Issue> enumerable = issues as IList<Issue> ?? issues.ToList(); if (enumerable.Any()) { _ticket = enumerable.Last(); user.TicketNumber = _ticket.Key.ToString(); user.State = 4; _bot.SendMessage(message.chat.id, _ticket); } else { _bot.SendMessage(message.chat.id, "Тикетов нет", "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}"); } } catch (Exception ex) { _bot.SendMessage(message.chat.id, "Jira не доступна", "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}"); var logReccord = new Log { Date = DateTime.Now, MessageTipe = "error", UserId = 0, Operation = "SendThatJiraDoesNotWork", Exception = ex.GetType() + ": " + ex.Message, AddInfo = "" }; repository.Create(logReccord); } break; case "Помоги с дежурством": _bot.SendMessage(message.chat.id, "Как будем дежурить?", "{\"keyboard\": [[\"Начать мониторить тикеты\"], [\"Мониторить тикеты в моё дежурство\"], [\"Отмена\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}"); break; case "Пока ничего": _bot.SendMessage(message.chat.id, "Ок, если что, пиши."); break; case "Начать мониторить тикеты": _bot.SendMessage(message.chat.id, @"Начинаю мониторинг. Я буду мониторить тикеты в течение ближайших 12 часов, после чего мониторинг будет автоматически остановлен."); user.State = 5; user.DutyStart = DateTime.Now; user.DutyEnd = DateTime.Now.AddHours(12); break; case "Мониторить тикеты в моё дежурство": if (DbReader.Readuserdutystart(message.chat.id) == Convert.ToDateTime("01.01.1900 0:00:00 ") | DbReader.Readuserdutystart(message.chat.id) == Convert.ToDateTime("01.01.1900 0:00:00 ")) { _bot.SendMessage(message.chat.id, "У тебя нет дежурств в ближайшее время", "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}"); break; } _bot.SendMessage(message.chat.id, "Я буду мониторить тикеты с " + DbReader.Readuserdutystart(message.chat.id).ToShortDateString() + " " + DbReader.Readuserdutystart(message.chat.id).ToShortTimeString() + " по " + DbReader.Readuserdutyend(message.chat.id).ToShortDateString() + " " + DbReader.Readuserdutyend(message.chat.id).ToShortTimeString()); user.State = 5; user.DutyStart = DbReader.Readuserdutystart(message.chat.id); user.DutyEnd = DbReader.Readuserdutyend(message.chat.id); break; default: _bot.SendMessage(message.chat.id, "Чем я могу помочь?", "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}"); break; } break; case 4: if (_ticket.Assignee == null & _ticket.Key.ToString().Equals(user.TicketNumber)) { switch ((message.text)) { case "Распределить": _bot.SendMessage(message.chat.id, "Кому назначим?", "{\"keyboard\": [[\"Технологи\", \"Коммерция\"], [\"Админы\", \"Связисты\"], [\"Олеся\", \"Женя\"], [\"Алексей\", \"Максим\"], [\"Паша\", \"Марина\"], [\"Андрей\", \"Гриша\"], [\"Оля\", \"Настя\"], [\"Маркетинг\", \"Даша\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}"); break; case "Решить": JiraAddFuncions.ResolveTicket(user, _ticket, message, user.Login, _bot, _jiraConn); break; case "Назначить себе": JiraAddFuncions.AssingTicket(user, _ticket, message, user.Login, _bot, _jiraConn); break; case "Технологи": JiraAddFuncions.AssingTicket(user, _ticket, message, "technologsupport", _bot, _jiraConn); break; case "Коммерция": JiraAddFuncions.AssingTicket(user, _ticket, message, "crm_otdel", _bot, _jiraConn); break; case "Админы": JiraAddFuncions.AssingTicket(user, _ticket, message, "Uk.Jira.TechSupport", _bot, _jiraConn); break; case "Связисты": JiraAddFuncions.AssingTicket(user, _ticket, message, "uk.jira.noc", _bot, _jiraConn); break; case "Олеся": JiraAddFuncions.AssingTicket(user, _ticket, message, "o.likhacheva", _bot, _jiraConn); break; case "Женя": JiraAddFuncions.AssingTicket(user, _ticket, message, "ev.safonov", _bot, _jiraConn); break; case "Алексей": JiraAddFuncions.AssingTicket(user, _ticket, message, "a.sapotko", _bot, _jiraConn); break; case "Максим": JiraAddFuncions.AssingTicket(user, _ticket, message, "m.shemetov", _bot, _jiraConn); break; case "Андрей": JiraAddFuncions.AssingTicket(user, _ticket, message, "an.zarubin", _bot, _jiraConn); break; case "Гриша": JiraAddFuncions.AssingTicket(user, _ticket, message, "g.dementiev", _bot, _jiraConn); break; case "Оля": JiraAddFuncions.AssingTicket(user, _ticket, message, "o.tkachenko", _bot, _jiraConn); break; case "Настя": JiraAddFuncions.AssingTicket(user, _ticket, message, "a.zakharova", _bot, _jiraConn); break; case "Марина": JiraAddFuncions.AssingTicket(user, _ticket, message, "m.vinnikova", _bot, _jiraConn); break; case "Паша": JiraAddFuncions.AssingTicket(user, _ticket, message, "p.denisov", _bot, _jiraConn); break; case "Даша": JiraAddFuncions.AssingTicket(user, _ticket, message, "d.kormushina", _bot, _jiraConn); break; case "Маркетинг": JiraAddFuncions.AssingTicket(user, _ticket, message, "Uk.Jira.TradeMarketing", _bot, _jiraConn); break; default: _bot.SendMessage(message.chat.id, "", "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}"); user.State = 3; break; } } else { _bot.SendMessage(message.chat.id, "Похоже, тикет уже распределён.", "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}"); user.State = 3; } break; case 5: switch (message.text) { case ("Ок"): break; case ("Остановить мониторинг"): _bot.SendMessage(message.chat.id, "Готово"); user.State = 3; break; case ("Продолжить мониторинг"): _bot.SendMessage(message.chat.id, "Хорошо, продолжим"); break; default: _bot.SendMessage(message.chat.id, "да?", "{\"keyboard\": [[\"Остановить мониторинг\"], [\"Продолжить мониторинг\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}"); break; } break; case 6: switch (message.text) { case "Распределить": if (lastIssue.Assignee == null & lastIssue.Key.ToString().Equals(user.TicketNumber)) { _bot.SendMessage(message.chat.id, "Кому назначим?", "{\"keyboard\": [[\"Технологи\", \"Коммерция\"], [\"Админы\", \"Связисты\"], [\"Олеся\", \"Женя\"], [\"Алексей\", \"Максим\"], [\"Паша\", \"Марина\"], [\"Андрей\", \"Гриша\"], [\"Оля\", \"Настя\"], [\"Маркетинг\", \"Даша\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}"); break; } _bot.SendMessage(message.chat.id, "Похоже, тикет уже распределён."); user.State = 5; break; case "Решить": if (lastIssue.Assignee == null & lastIssue.Key.ToString().Equals(user.TicketNumber)) { JiraAddFuncions.ResolveTicket(user, lastIssue, message, user.Login, _bot, _jiraConn); break; } _bot.SendMessage(message.chat.id, "Похоже, тикет уже распределён."); user.State = 5; break; case "Назначить себе": if (lastIssue.Assignee == null & lastIssue.Key.ToString().Equals(user.TicketNumber)) { JiraAddFuncions.AssingTicket(user, lastIssue, message, user.Login, _bot, _jiraConn); break; } _bot.SendMessage(message.chat.id, "Похоже, тикет уже распределён."); user.State = 5; break; case "Технологи": JiraAddFuncions.AssingTicket(user, lastIssue, message, "technologsupport", _bot, _jiraConn); break; case "Коммерция": JiraAddFuncions.AssingTicket(user, lastIssue, message, "crm_otdel", _bot, _jiraConn); break; case "Админы": JiraAddFuncions.AssingTicket(user, lastIssue, message, "Uk.Jira.TechSupport", _bot, _jiraConn); break; case "Связисты": JiraAddFuncions.AssingTicket(user, lastIssue, message, "uk.jira.noc", _bot, _jiraConn); break; case "Олеся": JiraAddFuncions.AssingTicket(user, lastIssue, message, "o.likhacheva", _bot, _jiraConn); break; case "Женя": JiraAddFuncions.AssingTicket(user, lastIssue, message, "ev.safonov", _bot, _jiraConn); break; case "Алексей": JiraAddFuncions.AssingTicket(user, lastIssue, message, "a.sapotko", _bot, _jiraConn); break; case "Максим": JiraAddFuncions.AssingTicket(user, lastIssue, message, "m.shemetov", _bot, _jiraConn); break; case "Андрей": JiraAddFuncions.AssingTicket(user, lastIssue, message, "an.zarubin", _bot, _jiraConn); break; case "Гриша": JiraAddFuncions.AssingTicket(user, lastIssue, message, "g.dementiev", _bot, _jiraConn); break; case "Оля": JiraAddFuncions.AssingTicket(user, lastIssue, message, "o.tkachenko", _bot, _jiraConn); break; case "Настя": JiraAddFuncions.AssingTicket(user, lastIssue, message, "a.zakharova", _bot, _jiraConn); break; case "Марина": JiraAddFuncions.AssingTicket(user, lastIssue, message, "m.vinnikova", _bot, _jiraConn); break; case "Паша": JiraAddFuncions.AssingTicket(user, lastIssue, message, "p.denisov", _bot, _jiraConn); break; case "Маркетинг": JiraAddFuncions.AssingTicket(user, lastIssue, message, "Uk.Jira.TradeMarketing", _bot, _jiraConn); break; case "Даша": JiraAddFuncions.AssingTicket(user, lastIssue, message, "d.kormushina", _bot, _jiraConn); break; case "Остановить мониторинг": { user.State = 3; _bot.SendMessage(message.chat.id, "Готово"); break; } case "Продолжить мониторинг": { user.State = 5; _bot.SendMessage(message.chat.id, "Хорошо, продолжим"); break; } default: _bot.SendMessage(message.chat.id, "да?", "{\"keyboard\": [[\"Остановить мониторинг\"], [\"Продолжить мониторинг\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}"); break; } break; } repository.Update(); } } catch (Exception ex) { using (var repository = new Repository<DutyBotDbContext>()) { var RepUser = repository.Get<User>(usr => usr.Id == user.Id); if (RepUser.State > 3) RepUser.State = 3; _bot.SendMessage(message.chat.id, "Что-то пошло не так при обработке сообщения. Что будем делать?", "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}"); repository.Update(); var logReccord = new Log { Date = DateTime.Now, MessageTipe = "info", UserId = message.chat.id, Operation = "ProcessMessage", Exception = ex.Message, AddInfo = "" }; repository.Create(logReccord); } Thread.Sleep(5000); } } }