public static void Apply(string name, string gameDataFile, int videoBitRate, string destFile, bool highlights, Action <long, long> progressReporter, CancellationToken token) { var domain = AppDomain.CreateDomain(name, null, new AppDomainSetup()); try { var hostArgs = new TranscodeAndOverlayArguments(progressReporter, () => token.IsCancellationRequested); var arg = (TranscodeAndOverlayArguments)domain.CreateInstanceFromAndUnwrap( typeof(TranscodeAndOverlayArguments).Assembly.Location, typeof(TranscodeAndOverlayArguments).FullName, false, BindingFlags.CreateInstance, null, new object[] { gameDataFile, videoBitRate, destFile, highlights, (Action <long, long>)hostArgs.ProgressReporter, (Func <bool>)hostArgs.IsAborted, hostArgs.LogRepeater, Settings.Default.PluginName }, null, null); arg.Apply(); } catch (Exception e) { TraceError.WriteLine(e.Message); TraceError.WriteLine(e.StackTrace); throw e; } finally { AppDomain.Unload(domain); } }
public void Process(DataSample data, TimeSpan relativeTime) { try { var cameraGroupName = ""; var cameraName = ""; var cameraGroup = data.SessionData.CameraInfo.Groups.FirstOrDefault(g => g.GroupNum == data.Telemetry.CamGroupNumber); if (cameraGroup != null) { cameraGroupName = cameraGroup.GroupName; var camera = cameraGroup.Cameras.FirstOrDefault(c => c.CameraNum == data.Telemetry.CamCameraNumber); if (camera != null) { cameraName = camera.CameraName; } } TraceDebug.WriteLine("{0} Camera: Driver: {1}, GroupNumber: {2}, Number: {3}, State: {4}, GroupName: {5}, Name: {6}", data.Telemetry.SessionTimeSpan, data.Telemetry.CamCar.Details.Driver.UserName, data.Telemetry.CamGroupNumber, data.Telemetry.CamCameraNumber, data.Telemetry.CamCameraState, cameraGroupName, cameraName); } catch (Exception e) { TraceError.WriteLine(e.Message); TraceError.WriteLine(e.StackTrace); } }
/// <summary> /// Update handling /// </summary> /// public async Task Handle(Update update) { TraceError.Info($"inside message handler with {update?.Message?.Text}"); if (update == null) { TraceError.Error("Update is null"); return; } switch (update.Type) { case Telegram.Bot.Types.Enums.UpdateType.Message: await MessageUpdate(update); break; case Telegram.Bot.Types.Enums.UpdateType.CallbackQuery: await CallbackQuertUpdate(update); break; default: break; } return; }
private static void trace(TraceEventType eventType, string message) { Exception exception; switch (eventType) { case TraceEventType.Information: exception = new TraceInformation(message); break; case TraceEventType.Error: exception = new TraceError(message); break; case TraceEventType.Warning: exception = new TraceWarning(message); break; default: exception = new TraceWrite(message); break; } Trace(exception); }
private void CaptureNewFileNames(object sender, ElapsedEventArgs e) { try { var guessedFileName = Directory.GetFiles(workingFolder, "*.avi") .Concat(Directory.GetFiles(workingFolder, "*.mp4")) .Select(fn => new { FileName = fn, CreationTime = File.GetCreationTime(fn) }) .Where(f => f.CreationTime >= started) .OrderByDescending(f => f.CreationTime) .FirstOrDefault(); if (guessedFileName != null && !captureFileNames.Any(c => c.FileName == guessedFileName.FileName)) { TraceInfo.WriteLine("Found video file {0}", guessedFileName.FileName); captureFileNames.Add(new CapturedVideoFile { FileName = guessedFileName.FileName }); } } catch (Exception ee) { TraceError.WriteLine(ee.Message); TraceError.WriteLine(ee.StackTrace); } finally { if (timer != null) timer.Start(); } }
public async Task <IActionResult> Post([FromBody] Update update) { TraceError.Info("Called Trace Error from api/command"); if (update == null) { TraceError.Info($"Update is null"); } if (update?.Message == null) { TraceError.Info($"Message is null"); } if (update?.Message?.Text == null) { TraceError.Info($"Text is null"); } TraceError.Info("Update text - " + update?.Message?.Text); try { if (update?.Message?.Text != null && update.Message.Text.StartsWith("/")) { TraceError.Info("api/command called with: " + update?.Message?.Text); } await new MessageHandler().Handle(update); return(Ok()); } catch (System.Exception e) { TraceError.Error(e, "Upper level Exception"); return(Ok()); } }
public async Task GenerateAndSendWorkerAsync(TelegramBotClient bot, IList <string> parameters) { var currenciesNumber = 5; bool.TryParse(parameters[0], out bool sendAnyway); var result = await GetPricesAsync(currenciesNumber); if ((!sendAnyway && !result.Item2) || string.IsNullOrEmpty(result.Item1)) { return; } try { using (BotDBContext db = new BotDBContext()) { var clients = (from c in db.Clients join sub in db.Subscriptions on c.Subscription equals sub.Id where sub.SubsctiptionType == (int)Subscription.CoinCapMarket select c.ChatId ).Distinct(); foreach (var client in clients) { await bot.SendTextMessageAsync(client, result.Item1, parseMode : Telegram.Bot.Types.Enums.ParseMode.Html); } } } catch (Exception e) { TraceError.Error(e); } }
public async void HandleCoinAsync(string sendAnyway) { TraceError.Info("HandleCoinAsync called from Worker"); await new CoinModule().GenerateAndSendWorkerAsync(_bot, new List <string>() { sendAnyway }); }
private async Task SendComicsAsync(Subscription subscriptionType) { using (var db = new BotDBContext()) { var clients = (from c in db.Clients join sub in db.Subscriptions on c.Subscription equals sub.Id where sub.SubsctiptionType == (int)subscriptionType select c.ChatId ).Distinct(); MessageToSend message = (subscriptionType == Subscription.Oglaf) ? GetOglafPicture() : GetXKCDPicture(); foreach (var client in clients) { var lastPostedKey = (from cli in db.Clients join sub in db.Subscriptions on cli.Subscription equals sub.Id where cli.ChatId == client && sub.SubsctiptionType == (int)subscriptionType orderby sub.Id descending select new { LTK = sub.LastPostedKey, SUBID = sub.Id } ).First(); if (message.Title.Equals(lastPostedKey.LTK)) { continue; } DatabaseInteractions.Subscription subToUpdate = db.Subscriptions.Where(x => x.Id == lastPostedKey.SUBID).First(); string newHash = message.Title; subToUpdate.LastPostedKey = newHash; db.Update(subToUpdate); //db.Subscriptions.Where(x => x.Id == lastPostedKey.SUBID).First().LastPostedKey = message.Title.GetHashCode().ToString(); try { await _bot.SendTextMessageAsync(client, message.Title.ToUpper()); await _bot.SendTextMessageAsync(client, message.SubTitle); await _bot.SendPhotoAsync(client, new InputOnlineFile(message.Image)); } catch (ChatNotFoundException e) { TraceError.Info(e.Message); var clientsRecords = db.Clients.Where(c => c.ChatId == client).ToList(); TraceError.Info("Client Recs to remove: " + string.Join(",", clientsRecords.Select(c => c.ChatId))); var subscriptionsToRemove = db.Subscriptions.Where(x => clientsRecords.Select(o => o.Subscription).Contains(x.Id)); TraceError.Info("Subscription Recs to remove: " + string.Join(",", subscriptionsToRemove.Select(s => s.SubsctiptionType.ToString()))); db.Subscriptions.RemoveRange(subscriptionsToRemove); db.Clients.RemoveRange(clientsRecords); } } await db.SaveChangesAsync(); } }
internal async Task BalanceAddAsync(TelegramBotClient bot, Update update) { var params1 = update.Message.Text.Split(' '); if (params1.Length != 3) { await bot.SendTextMessageAsync(update.Message.From.Id, "Incorrect parameters", parseMode : ParseMode.Html); return; } var symbol = params1[1].ToUpper(); var parsed = double.TryParse(params1[2], out double value); var client = update.Message.From.Id; if (string.IsNullOrEmpty(symbol) && parsed) { await bot.SendTextMessageAsync(update.Message.From.Id, "Incorrect parameters", parseMode : ParseMode.Html); } string message; using (var db = new BotDBContext()) { var result = db.Balances.SingleOrDefault(o => o.Client == client && o.Symbol == symbol); if (result != null) { result.Shares = (decimal)value; message = symbol + " Record Updated!"; } else { var balance = new Balance() { Client = client, Symbol = symbol, Shares = (decimal)value }; db.Balances.Add(balance); message = symbol + " Record Added!"; } db.SaveChanges(); } try { await bot.SendTextMessageAsync(update.Message.From.Id, message); } catch (Exception e) { TraceError.Error(e); } }
public OkResult CoinUpdate([FromQuery] string sendAnyway = "false") { TraceError.Info("api/CoinUpdate called"); try { Task.Run(() => new WorkerHandler().HandleCoinAsync(sendAnyway)); } catch (Exception e) { TraceError.Error(e, "Upper level Exception"); return(Ok()); } return(Ok()); }
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { var ex = e.ExceptionObject as Exception; if (ex != null) { TraceError.WriteLine(ex.Message); TraceError.WriteLine(ex.StackTrace); } else { Trace.WriteLine("An unknown error occured. {0}, {1}".F(e.ExceptionObject.GetType().Name, e.ExceptionObject.ToString())); } }
public OkResult SendErrorMessageToBot([FromQuery] string errormsg) { TraceError.Info("api/SendErrorMessageToBot"); try { Task.Run(() => new WorkerHandler().SendErrorMessageToBot(errormsg)); } catch (Exception e) { TraceError.Error(e, "Upper level Exception"); return(Ok()); } return(Ok()); }
public OkResult ComicUpdate() { TraceError.Info("api/comicUpdate called"); try { Task.Run(() => new WorkerHandler().HandleComicAsync()); } catch (Exception e) { TraceError.Error(e, "Upper level Exception"); return(Ok()); } return(Ok()); }
public void RaiseError(Exception ex) { Exception e = ex; while (e.InnerException != null) { e = e.InnerException; } TraceError?.Invoke(this, e.Message); Log.Error(ex, "{class} {method} {message}", "QueryTraceEngine", "RaiseError", GetAllExceptionMessages(ex)); if (ex.InnerException != null) { Log.Error("{class} {method} {message}/n{stacktrace}", "QueryTraceEngine", "RaiseError (InnerException)", ex.InnerException.Message, ex.InnerException.StackTrace); } }
void RunTest(string filename, SynchronizationContext context) { try { TranscodeVideoTest(filename); } catch (Exception e) { TraceError.WriteLine(e.Message); TraceError.WriteLine(e.StackTrace); } finally { context.Post(ignored => testVideoCaptureButton.Enabled = true, null); } }
void Process(Transcoder transcoder, bool highlights, Action <long, long> monitorProgress, Func <bool> isAborted) { try { TraceInfo.WriteLineIf(highlights, "Transcoding highlights to {0}", transcoder.DestinationFile); TraceInfo.WriteLineIf(!highlights, "Transcoding full replay to {0}", transcoder.DestinationFile); transcoder.ProcessVideo((readers, saveToSink) => { var writeToSink = monitorProgress == null ? saveToSink : MonitorProgress(saveToSink); var fadeSegments = AVOperations.FadeIn(AVOperations.FadeOut(writeToSink)); var edits = highlights ? ApplyEdits(writeToSink) : writeToSink; var mainBodyOverlays = AVOperations.Overlay(applyRaceDataOverlay, edits); var introOverlay = AVOperations.Overlay(applyIntroOverlay, fadeSegments); var sourceReaderExtra = readers.FirstOrDefault(r => ((CapturedVideoFile)r.State).isIntroVideo); if (sourceReaderExtra != null) { var introSourceReader = sourceReaderExtra.SourceReader; var mainReaders = AVOperations.Combine(readers.Skip(1).Select(r => r.SourceReader).ToArray(), Settings.Default.VideoSplitGap); totalDuration += introSourceReader.Duration + mainReaders.Duration; AVOperations.StartConcat(introSourceReader, introOverlay, AVOperations.Concat(mainReaders, mainBodyOverlays, isAborted), isAborted); } else { var mainReaders = AVOperations.Combine(readers.Select(r => r.SourceReader).ToArray(), Settings.Default.VideoSplitGap); totalDuration += mainReaders.Duration; AVOperations.Concat(mainReaders, mainBodyOverlays, isAborted)(0, 0); } }); TraceInfo.WriteLineIf(highlights, "Done Transcoding highlights to {0}", transcoder.DestinationFile); TraceInfo.WriteLineIf(!highlights, "Done Transcoding full replay to {0}", transcoder.DestinationFile); } catch (Exception e) { TraceError.WriteLine(e.Message); TraceError.WriteLine(e.StackTrace); throw e; } }
public async Task GenerateAndSendAsync(TelegramBotClient bot, Update update) { TraceError.Info($"In Balance module"); double totalAmount = 0; double BTCtotalAmount = 0; double ALTtotalAmount = 0; try { using (BotDBContext db = new BotDBContext()) { TraceError.Info($"DB initiated"); var balances = db.Balances.Where(o => o.Client == (int)update.Message.From.Id); StringBuilder sb = new StringBuilder(); foreach (var b in balances) { sb.Append(b.Symbol + ','); } sb.Remove(sb.Length - 1, 1); var prices = GetPrices(sb.ToString()); foreach (var item in balances) { prices.TryGetValue(item.Symbol, out double price); totalAmount += ((double)item.Shares * price); if (item.Symbol == "BTC") { BTCtotalAmount += ((double)item.Shares * price); } if (item.Symbol != "BTC") { ALTtotalAmount += ((double)item.Shares * price); } } } } catch (Exception e) { TraceError.Info("EXception thrown "); TraceError.Info("DB ERROR: " + e.Message); } string msg = $"BTC: ${Math.Round(BTCtotalAmount, 2)}{Environment.NewLine}ALT: ${Math.Round(ALTtotalAmount, 2)}{Environment.NewLine}TOTAL: ${Math.Round(totalAmount, 2)}"; await bot.SendTextMessageAsync(update.Message.From.Id, msg, parseMode : ParseMode.Html); }
public OkResult CUTest() { try { using (var db = new BotDBContext()) { db.Subscriptions.Add(new DatabaseInteractions.Subscription() { LastPostedKey = "", SubsctiptionType = 7 }); db.SaveChanges(); } } catch (Exception e) { TraceError.Error(e, "Upper level Exception"); return(Ok()); } return(Ok()); }
public IRacingReplay InTheBackground(Action <string> onComplete) { requestAbort = false; var context = SynchronizationContext.Current; cancellationTokenSource = new CancellationTokenSource(); token = cancellationTokenSource.Token; backgrounTask = new Task(() => { try { foreach (var action in actions) { action(); if (token.IsCancellationRequested) { break; } } context.Post(() => onComplete(null)); } catch (Exception e) { TraceError.WriteLine(e.Message); TraceError.WriteLine(e.StackTrace); TraceInfo.WriteLine("Process aborted"); var message = e.InnerException != null ? e.InnerException.Message : e.Message; context.Post(() => onComplete("There was an error - details in Log Messages\n{0}".F(message))); } finally { backgrounTask = null; actions = new List <Action>(); } }); backgrounTask.Start(); return(this); }
SessionData ReadSessionInfo(iRSDKHeader header) { if (header.sessionInfoUpdate == sessionLastInfoUpdate) { return(lastSessionInfo); } sessionLastInfoUpdate = header.sessionInfoUpdate; Trace.WriteLine("New Session data retrieved from iRacing. {0}".F(sessionLastInfoUpdate), "DEBUG"); var t = Task.Factory.StartNew(() => { try { var sessionInfoData = new byte[header.sessionInfoLen]; accessor.ReadArray <byte>(header.sessionInfoOffset, sessionInfoData, 0, header.sessionInfoLen); var sessionInfoString = System.Text.Encoding.Default.GetString(sessionInfoData); var length = sessionInfoString.IndexOf('\0'); if (length == -1) { lastSessionInfo = null; return; } sessionInfoString = sessionInfoString.Substring(0, sessionInfoString.IndexOf('\0')); Trace.WriteLine(sessionInfoString, "DEBUG"); lastSessionInfo = DeserialiseSessionInfo(sessionInfoString, header.sessionInfoUpdate); } catch (Exception e) { TraceError.WriteLine(e.Message); TraceError.WriteLine(e.StackTrace); } }); if (lastSessionInfo == null) { t.Wait(); } return(lastSessionInfo); }
/// <summary> /// Get the bot and set the hook /// </summary> public static TelegramBotClient Get() { if (_bot != null) { return(_bot); } if (Config.Environment == "Development") { _bot = new TelegramBotClient(Config.BotApiKey); _bot.SetWebhookAsync(Config.WebHookUrl); _bot.SendTextMessageAsync(182328439, "Local Bot started!"); } else if (Config.Environment == "Production" || Config.Environment == "Release") { _bot = new TelegramBotClient(Config.BotApiKey); _bot.SetWebhookAsync(Config.WebHookUrl); _bot.SendTextMessageAsync(182328439, "Remote Bot started!!!"); TraceError.Info("Bot started"); } return(_bot); }
internal async Task BalanceRemoveAsync(TelegramBotClient bot, Update update) { var params1 = update.Message.Text.Split(' '); var client = update.Message.From.Id; if (params1.Length != 2 && string.IsNullOrEmpty(params1[1])) { await bot.SendTextMessageAsync(update.Message.From.Id, "Incorrect parameters"); return; } var symbol = params1[1].ToUpper(); string message; using (var db = new BotDBContext()) { var result = db.Balances.SingleOrDefault(o => o.Client == client && o.Symbol == symbol); if (result != null) { db.Balances.Remove(result); message = symbol + " Record Deleted!"; } else { message = symbol + " Record Not Found!"; } db.SaveChanges(); } try { await bot.SendTextMessageAsync(update.Message.From.Id, message); } catch (Exception e) { TraceError.Error(e); } }
private MessageToSend GetXKCDPicture() { WebClient webclient = new WebClient(); ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // Use SecurityProtocolType.Ssl3 if needed for compatibility reasons string html = ""; try { html = webclient.DownloadString("https://xkcd.com/"); } catch (Exception e) { TraceError.Error(e); } HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); List <HtmlNode> imageNodes = null; imageNodes = (from HtmlNode node in doc.DocumentNode.SelectNodes("//img") where node.Name == "img" && !string.IsNullOrEmpty(node.Attributes["title"]?.Value) && node.Attributes["src"].Value.Contains("comics") select node).ToList(); var attrs = imageNodes[0]?.Attributes; return(new MessageToSend { Title = attrs["alt"]?.Value.Replace(""", "\"").Replace("'", "'"), SubTitle = attrs["title"]?.Value.Replace(""", "\"").Replace("'", "'"), Image = attrs["src"]?.Value.Substring(2) }); }
static async Task Run() { var TelegramBotClient = new TelegramBotClient(Config.BotApiKey); var offset = 0; TraceError.Info("Inside NoHookLoop"); while (true) { var updates = await TelegramBotClient.GetUpdatesAsync(offset); foreach (var update in updates) { TraceError.Info("Update from NoHookLoop"); await Task.Run(() => new MessageHandler().Handle(update)); offset = update.Id + 1; } await Task.Delay(1000); } }
public static void Apply(string gameDataFile, int videoBitRate, string destFile, bool highlights, Action <long, long> progressReporter, Func <bool> isAborted, string pluginName) { try { var leaderBoard = new LeaderBoard { OverlayData = OverlayData.FromFile(gameDataFile), PluginName = pluginName }; var transcoder = new Transcoder { VideoFiles = leaderBoard.OverlayData.VideoFiles.ToSourceReaderExtra(), DestinationFile = destFile, VideoBitRate = videoBitRate }; new TranscodeAndOverlay(leaderBoard, progressReporter).Process(transcoder, highlights, progressReporter, isAborted); } catch (Exception e) { TraceError.WriteLine(e.Message); TraceError.WriteLine(e.StackTrace); throw e; } }
private async static Task <(string, bool)> GetPricesAsync(int currenciesNumber) { //HttpClient client = HttpClientProvider.GetClient(); if (currenciesNumber > 50) { currenciesNumber = 50; } if (currenciesNumber < 0) { return("Incorrect number", true); } if (currenciesNumber == 0) { currenciesNumber = 5; } try { var URL = new UriBuilder("https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest"); //var queryString = HttpUtility.ParseQueryString(string.Empty); //queryString["id"] = "1,2,3"; //URL.Query = queryString.ToString(); var client = new WebClient(); client.Headers.Add("X-CMC_PRO_API_KEY", API_KEY); client.Headers.Add("Accepts", "application/json"); var response = client.DownloadString(URL.ToString()); response = response.Replace("USD", "CurrentPriceInfo"); CoinmarketcapItemData result = JsonConvert.DeserializeObject <CoinmarketcapItemData>(response); List <Currency> currencyList = new List <Currency>(); foreach (ItemData data in result.DataList) { if (data.symbol.Contains("CurrentPriceInfo")) { continue; } Currency item = new Currency { Id = data.id.ToString(), Name = data.name, Symbol = data.symbol, Rank = data.cmc_rank.ToString(), Price = data.quote.CurrentPriceInfo.price ?? 0d, Volume24hUsd = data.quote.CurrentPriceInfo.volume_24h ?? 0, MarketCapUsd = data.quote.CurrentPriceInfo.volume_24h ?? 0, PercentChange1h = data.quote.CurrentPriceInfo.percent_change_1h ?? 0, PercentChange24h = data.quote.CurrentPriceInfo.percent_change_24h ?? 0, PercentChange7d = data.quote.CurrentPriceInfo.percent_change_7d ?? 0, LastUpdated = data.quote.CurrentPriceInfo.last_updated, MarketCapConvert = data.quote.CurrentPriceInfo.market_cap ?? 0d, ConvertCurrency = "USD" }; currencyList.Add(item); } //var response = await client.GetAsync("https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest"); //if (response.IsSuccessStatusCode) //{ // var result = response.Content.ReadAsAsync<CoinPrice[]>().Result; // StringBuilder sb = new StringBuilder(); // foreach (var item in result) // { // sb.Append($"{item.symbol.Bold()}: ${item.price_usd}, {item.percent_change_24h.Italic()}%{Environment.NewLine}"); // } // if (currenciesNumber == 1) // { // return (sb.ToString(), true); // } // else // { // double.TryParse(result[0].percent_change_24h, out double BTCchange); // double.TryParse(result[1].percent_change_24h, out double ETHchange); // var change = (Math.Abs(BTCchange) >= 10 || Math.Abs(ETHchange) >= 10) ? true : false; // return (sb.ToString(), change); // } //} StringBuilder sb = new StringBuilder(); for (int i = 0; i < currenciesNumber; i++) { sb.Append($"{currencyList[i].Symbol.Bold()}: ${Math.Round(currencyList[i].Price, 2).ToString()}, {Math.Round(currencyList[i].PercentChange24h, 1).ToString().Italic()}%{Environment.NewLine}"); } return(sb.ToString(), false); } catch (Exception e) { TraceError.Error(e); return("", false); } }
void RunTest(string workingFolder, SynchronizationContext context) { try { TraceInfo.WriteLine("Switching to iRacing ...."); var hwnd = Win32.Messages.FindWindow(null, "iRacing.com Simulator"); Win32.Messages.ShowWindow(hwnd, Win32.Messages.SW_SHOWNORMAL); Win32.Messages.SetForegroundWindow(hwnd); Thread.Sleep(2000); TraceInfo.WriteLine("Begining Test...."); var videoCapture = new VideoCapture(); TraceInfo.WriteLine("Broadcasting keypress ALT+F9 to activate your video capture software"); videoCapture.Activate(workingFolder); TraceInfo.WriteLine("Expecting video file to be written in folder: {0}", workingFolder); TraceInfo.WriteLine("Waiting for 5 seconds"); for (var i = 5; i >= 0; i--) { Thread.Sleep(1.Seconds()); TraceInfo.WriteLine("{0} Seconds...", i); } TraceInfo.WriteLine("Broadcasting keypress ALT+F9 to deactivate your video capture software"); var filenames = videoCapture.Deactivate(); TraceInfo.WriteLine("Minimising iRacing"); AltTabBackToApp(); if (filenames.Count == 0) { TraceInfo.WriteLine("\nFailure - Did not find any video files"); return; } if (filenames.Count != 1) { TraceInfo.WriteLine("\nFailure - Found more than 1 video file!"); return; } var filename = filenames[0]; if (filename != null) { TraceInfo.WriteLine(""); TraceInfo.WriteLine("Found your video file {0}.", filename); TranscodeVideoTest(filename.FileName); } else { TraceInfo.WriteLine(""); TraceInfo.WriteLine("Failure!"); } } catch (Exception e) { TraceError.WriteLine(e.Message); TraceError.WriteLine(e.StackTrace); } finally { context.Post(ignored => testVideoCaptureButton.Enabled = true, null); } }
public void OutputError(string message) { TraceError?.Invoke(this, message); }
public async Task UpdateSubscriptions(Update update) { Subscription subscriptionType = Subscription.NoSubscription; if (update.CallbackQuery.Data.Equals("/subs=Oglaf")) { subscriptionType = Subscription.Oglaf; } if (update.CallbackQuery.Data.Equals("/subs=Xkcd")) { subscriptionType = Subscription.XKCD; } if (update.CallbackQuery.Data.Equals("/subs=CoinCM")) { subscriptionType = Subscription.CoinCapMarket; } if (update.CallbackQuery.Data.Equals("/subs=ErrL")) { subscriptionType = Subscription.ErrorMessageLog; } var userId = update.CallbackQuery.From.Id; TraceError.Info("In callback"); using (BotDBContext db = new BotDBContext()) { try { TraceError.Info("DB Init"); var exists = (from c in db.Clients join sub in db.Subscriptions on c.Subscription equals sub.Id where c.ChatId == userId && sub.SubsctiptionType == (int)subscriptionType select c.Id ).Count(); if (exists == 0) { var subscription = new DatabaseInteractions.Subscription { SubsctiptionType = (int)subscriptionType }; db.Subscriptions.Add(subscription); db.SaveChanges(); var client = new DatabaseInteractions.Client { ChatId = userId, Subscription = subscription.Id }; db.Clients.Add(client); db.SaveChanges(); await _bot.SendTextMessageAsync(userId, $"You've subscribed to { subscriptionType.ToString() }!"); } else { var clients = db.Clients.Where(x => x.ChatId == userId && db.Subscriptions.Any(y => y.Id == x.Subscription && y.SubsctiptionType == (int)subscriptionType)); foreach (var item in clients) { db.Clients.Remove(item); var sub = db.Subscriptions.Where(x => x.Id == item.Subscription).FirstOrDefault(); db.Subscriptions.Remove(sub); } db.SaveChanges(); await _bot.SendTextMessageAsync(userId, $"Unsubscribed from { subscriptionType.ToString() }!"); } } catch (Exception e) { TraceError.Info(e.Message); } } }