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); }
// Demonstrates the consumption end of the producer and consumer pattern. public async Task <int> ConsumeAsync(ISourceBlock <byte[]> source) { // Initialize a counter to track the number of bytes that are processed. int bytesProcessed = 0; // Read from the source buffer until the source buffer has no // available output data. while (await source.OutputAvailableAsync()) { byte[] data = source.Receive(); // Increment the count of bytes received. bytesProcessed += data.Length; //My code for debugging lock (consumerLocker) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("The processed bytes so far: " + bytesProcessed); Console.ForegroundColor = ConsoleColor.White; } } return(bytesProcessed); }
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); }
static async Task <int> ConsumeAsync(ISourceBlock <List <Vertex> > source) { // Initialize a counter to track the number of bytes that are processed. int nodesProcessed = 0; int batch = 0; ElasticClient client = new ElasticClient(new Uri(AppSettings.Current.ElasticServerUrl)); Console.WriteLine("Indexing documents into elasticsearch..."); // Read from the source buffer until the source buffer has no // available output data. while (await source.OutputAvailableAsync()) { Stopwatch sw = new Stopwatch(); sw.Start(); List <Vertex> nodes = source.Receive(); var sb = new StringBuilder(); foreach (var item in nodes) { sb.AppendLine(JsonConvert.SerializeObject(item, Formatting.None)); } File.AppendAllText("/Users/chinkit/00D2D-CRC/04-BigData/stackoverflow/step2/full-graph.json", sb.ToString()); // Increment the count of bytes received. nodesProcessed += nodes.Count; Console.WriteLine($"Batch {batch++} : Documented {nodesProcessed} ellapsed is {sw.ElapsedMilliseconds / 1000} seconds"); } return(nodesProcessed); }
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"); }); }
// TODO: Wait until this becomes a part of the API // https://github.com/dotnet/corefx/issues/41125 public async static IAsyncEnumerable <TOutput> ReceiveAllAsync <TOutput>(this ISourceBlock <TOutput> source, [EnumeratorCancellation] CancellationToken cancellationToken = default) { while (await source.OutputAvailableAsync(cancellationToken)) { yield return(source.Receive()); } }
public async Task SerializeToXml(ISourceBlock <Person> source) { var settings = new XmlWriterSettings(); settings.Indent = true; XmlSerializer xml = new XmlSerializer(typeof(Person)); using (FileStream fs = File.Create(XmlPath)) using (StreamWriter sw = new StreamWriter(fs)) using (XmlWriter xw = XmlTextWriter.Create(sw, settings)) { xw.WriteStartDocument(); xw.WriteStartElement("People"); string temp = string.Empty; while (await source.OutputAvailableAsync()) { var person = source.Receive(); xw.WriteStartElement("Person"); xw.WriteElementString("Name", person.Name); xw.WriteElementString("Surname", person.Surname); xw.WriteElementString("Countrt", person.Country); xw.WriteElementString("Email", person.Email); xw.WriteElementString("IpAddress", person.IpAddress); xw.WriteEndElement(); } xw.WriteEndElement(); xw.WriteEndDocument(); } }
static async Task UserInputHandler(ISourceBlock <UserInputEvent> source) { // Read from the source buffer until the source buffer has no // available output data. while (await source.OutputAvailableAsync()) { var input = source.Receive(); if (input == UserInputEvent.ButtonPress) { if (boardState == clock) { boardState = countdown; } else { boardState = clock; } } if (input == UserInputEvent.RotateRight && boardState == countdown) { countdown.Increase(); } else if (input == UserInputEvent.RotateLeft && boardState == countdown) { countdown.Decrease(); } } }
//This is the method that consumes the Matrix images and runs some openCV //processing on each before saving them. The threads are asynchronus //so processing can occur out of order intentionally to speed up the flow private static async void AsynchronousImageConv(ISourceBlock <Image> imageQueue) { while (await imageQueue.OutputAvailableAsync()) { Image producedResult = imageQueue.Receive(); Task.Run( () => { if (DateTime.Now.Ticks % 3 == 0) { Thread.Sleep(550); } Mat output = new Mat(); Mat input = producedResult.mat; Mat flipped = input.Flip(FlipMode.Y); //create an inversion effect i.e white becomes black Cv2.BitwiseNot(flipped, output); string outputName = @"C:\Temp\MetroImgs\Output\" + producedResult.filename; output.ImWrite(outputName); Console.WriteLine("Processed Image {0} from the queue:", producedResult.filename); WriteToLog("Processed Image " + producedResult.filename + " from the queue: \n"); }); } }
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); }
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); } }
internal async Task <int> ConsumeBuffer(ISourceBlock <SyslogMessageInfo> source) { int count = 0; using (var bucket = DbCluster.OpenBucket("BornToFail1")) { while (await source.OutputAvailableAsync()) { var message = source.Receive(); var document = new Document <dynamic> { Id = DocumentPrefix + "message::" + Guid.NewGuid().ToString(), Content = message }; var insert = await bucket.InsertAsync(document); if (insert.Success) { Console.WriteLine(document.Id); count++; } else { System.Diagnostics.Debug.WriteLine(insert.Status.ToString()); } if ( message.Message != null && message.Message.Header != null && message.Message.Header.MessageType != null && message.Message.Header.MessageType.Facility == "SYS" && message.Message.Header.MessageType.Mnemonic == "CONFIG_I" ) { var oldColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Received Configuration change notification from " + message.Sender.ToString()); Console.ForegroundColor = oldColor; var client = new HttpClient(); var response = await PostAsJsonAsync( client, "http://localhost:51954/api/values", new ConfigRequestObject { ConfigurationId = Guid.NewGuid(), DeviceId = message.Sender.Address.ToString() } ); } } } return(count); }
private async Task <bool> SaveAsync(ISourceBlock <System.Action> source) { while (await source.OutputAvailableAsync()) { var data = source.Receive(); data.Invoke(); } return(true); }
protected override async Task LogConsumerAsync(ISourceBlock <string> Source) { while (await Source.OutputAvailableAsync()) { await WriteToFile($"{DateTime.Now} {Source.Receive()}\n"); LogWriteEvent?.Invoke(this, EventArgs.Empty); } }
public static async IAsyncEnumerable <T> ReceiveAllAsync <T>(this ISourceBlock <T> block, [EnumeratorCancellation] CancellationToken cancellation = default) { while (await block.OutputAvailableAsync(cancellation).ConfigureAwait(false)) { while (block.TryReceiveItem(out var value)) { yield return(value); } } }
// Demonstrates the consumption end of the producer and consumer pattern. async Task ConsumeAsync(ISourceBlock <IMessage> source) { // Read from the source buffer until the source buffer has no // available output data. while (await source.OutputAvailableAsync()) { var data = source.Receive(); aggregateMessage.AddMessage(data); } }
private static async void AsynchronousConsumer(ISourceBlock <IList <int> > sourceBlock) { while (await sourceBlock.OutputAvailableAsync()) { var producedResult = sourceBlock.Receive(); foreach (var result in producedResult) { Console.WriteLine("Receiver Received:" + result); } } }
public async Task <dynamic> ConsumeAsync(ISourceBlock <object> source, Action <object> action) { while (await source.OutputAvailableAsync()) { object data = source.Receive(); action(data); } return(null); }
protected override async Task ErrorConsumerAsync(ISourceBlock <Exception> Source) { while (await Source.OutputAvailableAsync()) { LogEntry le = new LogEntry() { Event = "Exception", Timestamp = DateTimeOffset.Now, Message = Source.Receive().ToString() }; _repoManager.LogEntryRepository.Add(le); } }
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 LogConsumerAsync(ISourceBlock <string> Source) { while (await Source.OutputAvailableAsync()) { LogEntry le = new LogEntry() { Timestamp = DateTimeOffset.Now, Message = Source.Receive() }; _repoManager.LogEntryRepository.Add(le); } }
public async Task WorkAsync(ISourceBlock <TEntity> source, CancellationToken c) { var bufferSize = _options .Value.BufferSize.GetOrDefault(typeof(TEntity).Name, _options.Value.DefaultBufferSize); var buffer = new TEntity[bufferSize]; _logger.LogInformation("Start working, buffer size: {0}", bufferSize); while (await source.OutputAvailableAsync(c)) { var i = 0; for (; i < bufferSize && await source.OutputAvailableAsync(c); i++) { buffer[i] = await source.ReceiveAsync(c); } await Insert(buffer.Take(i)); } }
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"); } } }
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); }
public async Task Sender(ISourceBlock <string> source) { while (await source.OutputAvailableAsync()) { try { string data = source.Receive(); await Client.SendAsync(data); } catch (Exception) { } } }
// 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); }
private async Task ConsumeObjects(ImportContext context, SchemaType type, ISourceBlock <IUser> source) { long userHighestTicks = 0; while (await source.OutputAvailableAsync()) { IUser user = source.Receive(); try { if (user.LastUpdated.HasValue) { AsyncHelper.InterlockedMax(ref userHighestTicks, user.LastUpdated.Value.Ticks); } CSEntryChange c = await this.UserToCSEntryChange(context.InDelta, type, user, context).ConfigureAwait(false); if (c != null) { context.ImportItems.Add(c, context.CancellationTokenSource.Token); } } catch (Exception ex) { UserImportProvider.logger.Error(ex); CSEntryChange csentry = CSEntryChange.Create(); csentry.DN = user.Id; csentry.ErrorCodeImport = MAImportError.ImportErrorCustomContinueRun; csentry.ErrorDetail = ex.StackTrace; csentry.ErrorName = ex.Message; context.ImportItems.Add(csentry, context.CancellationTokenSource.Token); } context.CancellationTokenSource.Token.ThrowIfCancellationRequested(); } string wmv; if (userHighestTicks <= 0) { wmv = context.IncomingWatermark["users"].Value; } else { wmv = userHighestTicks.ToString(); } context.OutgoingWatermark.Add(new Watermark("users", wmv, "DateTime")); }
public static async Task <int> SaveFileAsync(ISourceBlock <string> source) { while (await source.OutputAvailableAsync()) { WebClient wc = new WebClient(); if (!Directory.Exists("img")) { Directory.CreateDirectory("img"); } var imageUrl = source.Receive(); var savePath = GetCacheImageName(imageUrl); wc.DownloadFile(imageUrl, savePath); } return(1); }
private async System.Threading.Tasks.Task WriteOutputAsync(ISourceBlock<string> source) { while (await source.OutputAvailableAsync()) { string data = source.Receive(); if (OutputPane != null) { OutputPane.OutputStringThreadSafe(data); OutputPane.OutputStringThreadSafe("\r\n"); } } }
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); } } }