public static async Task <string> ReceiveString(WebSocket socket, int?timeOutSeconds = null, int bufferSize = DefaultBufferSize) { CommonLibs.Utils.Debug.ASSERT(socket != null, System.Reflection.MethodInfo.GetCurrentMethod(), $"Missing parameter '{nameof(socket)}'"); var cancellationToken = System.Threading.CancellationToken.None; if (timeOutSeconds != null) { var tokenSource = new System.Threading.CancellationTokenSource(); tokenSource.CancelAfter(millisecondsDelay: timeOutSeconds.Value * 1000); cancellationToken = tokenSource.Token; } // Read from socket var stream = new System.IO.MemoryStream(); var buffer = System.Net.WebSockets.WebSocket.CreateClientBuffer(bufferSize, bufferSize); RECEIVE_AGAIN: var result = await socket.ReceiveAsync(buffer, cancellationToken); stream.Write(buffer.Array, 0, result.Count); if (!result.EndOfMessage) { goto RECEIVE_AGAIN; } // Parse byte array var rv = System.Text.Encoding.UTF8.GetString(stream.ToArray()); return(rv); }
private async Task GoToUrl(WebDriver webDriver, System.Threading.CancellationTokenSource cts) { //await webDriver.Options().Timeouts.SetPageLoad(TimeSpan.FromSeconds(1)); await webDriver.GoToUrl(tailURLTbox.Text, cts.Token); cts.CancelAfter(TimeSpan.FromHours(1)); }
public async Task TestSubscribe() { var cts = new System.Threading.CancellationTokenSource(); cts.CancelAfter(5000); var streamName = Guid.NewGuid().ToString(); await Fixture.Client.CreateStream(streamName, "test.subscribe", cts.Token); var value = System.Text.Encoding.ASCII.GetBytes("hello, world"); await Fixture.Client.Publish(streamName, value, MessageOptions.Default, cts.Token); var sub = Fixture.Client.Subscribe(streamName, new SubscriptionOptions { Partition = 0, StartPosition = Proto.StartPosition.Earliest, }, cts.Token); await foreach (var message in sub) { Assert.Equal("hello, world", System.Text.Encoding.UTF8.GetString(message.Value)); break; } return; }
private async Task <bool> LoginAsync(string server) { if (_username.IsNotNullOrWhiteSpace()) { var dict = new Dictionary <string, string> { { "username", _username }, { "password", _password } }; var url = $"http://{server}{contextPath}{LOGIN_URL}"; if (server.Contains(ConstValue.HTTP_PREFIX)) { url = $"{server}{contextPath}{LOGIN_URL}"; } try { var cts = new System.Threading.CancellationTokenSource(); cts.CancelAfter(5000); var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(dict) }; var resp = await _httpClient.SendAsync(req, cts.Token); if (!resp.IsSuccessStatusCode) { _logger?.LogError("login failed: {0}", await resp.Content.ReadAsStringAsync()); return(false); } var content = await resp.Content.ReadAsStringAsync(); var obj = Newtonsoft.Json.Linq.JObject.Parse(content); if (obj.ContainsKey(ConstValue.ACCESS_TOKEN)) { _accessToken = obj.Value <string>(ConstValue.ACCESS_TOKEN); _tokenTtl = obj.Value <long>(ConstValue.TOKEN_TTL); _tokenRefreshWindow = _tokenTtl / 10; } } catch (Exception ex) { _logger?.LogError(ex, "[SecurityProxy] login http request failed, url: {0}", url); return(false); } } return(true); }
public async Task WatchMessagesWithLimit(int limit, int messageTimeout, string consumerGroup, string connectionString, string eventHubName) { string consumerGroupWithDefault = EventHubConsumerClient.DefaultConsumerGroupName; if (consumerGroup != null) { consumerGroupWithDefault = consumerGroup; } await using (var consumer = new EventHubConsumerClient(consumerGroupWithDefault, connectionString, eventHubName)) { EventPosition startingPosition = EventPosition.Latest; using var cancellationSource = new System.Threading.CancellationTokenSource(); int maxWaitTime = messageTimeout == 0 ? 30 : messageTimeout; cancellationSource.CancelAfter(TimeSpan.FromSeconds(maxWaitTime)); string[] partitionIds = await consumer.GetPartitionIdsAsync(); var partitions = new IAsyncEnumerable <PartitionEvent> [partitionIds.Length]; for (int i = 0; i < partitionIds.Length; i++) { partitions[i] = consumer.ReadEventsFromPartitionAsync(partitionIds[i], startingPosition, cancellationSource.Token); } var mergedPartitions = AsyncEnumerable.Merge <PartitionEvent>(partitions); var maxMessages = Math.Max(1, limit); try { Console.WriteLine("Waiting for messages.."); int messageCount = 0; await foreach (var pe in mergedPartitions.Take <PartitionEvent>(maxMessages)) { //Console.WriteLine($"Event received on partition {pe.Partition.PartitionId} with body {Encoding.UTF8.GetString(pe.Data.Body.ToArray())}"); DisplayMessage(pe); messageCount = messageCount + 1; if (messageCount >= maxMessages) { Console.WriteLine($"Total messages received: {messageCount}"); break; } } } catch (Exception ex) { Console.WriteLine($"{ex}"); } } }
public async Task <HttpResponseMessage> HttpRequest(string path, Dictionary <string, string> headers, Dictionary <string, string> paramValues, string encoding, long readTimeoutMs, HttpMethod method) { long endTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + readTimeoutMs; string currentServerAddr = _serverListMgr.GetCurrentServerAddr(); int maxRetry = Constants.MAX_RETRY; var requestUrl = $"{GetUrl(currentServerAddr, path)}?{InitParams(paramValues)}"; do { try { var cts = new System.Threading.CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromMilliseconds(readTimeoutMs)); HttpRequestMessage reqMsg = new HttpRequestMessage(method, requestUrl); foreach (var item in headers) { reqMsg.Headers.TryAddWithoutValidation(item.Key, item.Value); } var resp = await _httpClient.SendAsync(reqMsg, cts.Token).ConfigureAwait(false); if (IsFail(resp)) { _logger?.LogError("[NACOS ConnectException] currentServerAddr: {0}, httpCode: {1}", currentServerAddr, resp.StatusCode); } else { _serverListMgr.UpdateCurrentServerAddr(currentServerAddr); return(resp); } } catch (Exception ex) { _logger?.LogError(ex, "[NACOS Exception {0}] currentServerAddr: {1}", method.Method, currentServerAddr); } maxRetry--; if (maxRetry < 0) { throw new Exception( $"[NACOS HTTP-{method.Method}] The maximum number of tolerable server reconnection errors has been reached"); } _serverListMgr.RefreshCurrentServerAddr(); }while (DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() <= endTime); _logger?.LogError("no available server"); throw new Exception("no available server"); }
public static async Task streamToVimeo() { FFmpeg.SetExecutablesPath("C://ffmpeg/bin/"); var mediaInfo = await FFmpeg.GetMediaInfo("rtsp://*****:*****@192.168.1.2:554/onvif1"); var cancellationTokenSource = new System.Threading.CancellationTokenSource(); cancellationTokenSource.CancelAfter(10000); IConversionResult conversionResult = await FFmpeg.Conversions.New() .AddStream(mediaInfo.Streams.First()) .SetOutput(StreamOnline.buildVimeowLink()) .Start(); }
/// <summary> /// Read RTPS stream from camera and output image /// </summary> /// <returns></returns> public static async Task convertVideoImageCameraOnvif() { FFmpeg.SetExecutablesPath("C://ffmpeg/bin/"); var mediaInfo = await FFmpeg.GetMediaInfo("rtsp://*****:*****@192.168.1.2:554/onvif1"); var cancellationTokenSource = new System.Threading.CancellationTokenSource(); cancellationTokenSource.CancelAfter(10000); System.Func <string, string> outputFileNameBuilder = (number) => { return("G://VSCsharp/tmp_out/onvif/fileNameNo" + number + ".png"); }; IConversionResult conversionResult = await FFmpeg.Conversions.New() .AddStream(mediaInfo.Streams.First()) .ExtractEveryNthFrame(10, outputFileNameBuilder) .Start(cancellationTokenSource.Token); }
private async void Button_Clicked(object sender, EventArgs e) { reader = new NdefReader(); reader.Reading += Reader_Reading; reader.Error += Reader_Error; NdefScanOptions options = new NdefScanOptions(); System.Threading.CancellationTokenSource cts = new System.Threading.CancellationTokenSource(); options.Signal = cts.Token; await reader.ScanAsync(options); cts.CancelAfter(30000); }
public static async Task streamToTwitch() { FFmpeg.SetExecutablesPath("C://ffmpeg/bin/"); var mediaInfo = await FFmpeg.GetMediaInfo("rtsp://*****:*****@192.168.1.2:554/onvif1"); var cancellationTokenSource = new System.Threading.CancellationTokenSource(); cancellationTokenSource.CancelAfter(10000); IStream videoStream = mediaInfo.VideoStreams.FirstOrDefault().SetCodec(VideoCodec.libx264).SetBitrate(3000000); IStream audioStream = mediaInfo.AudioStreams.FirstOrDefault().SetCodec(AudioCodec.aac).SetBitrate(192000); IConversionResult conversionResult = await FFmpeg.Conversions.New() .AddStream(videoStream, audioStream) .SetOutput(StreamOnline.buildTwitchLink()) .SetOutputFormat(Format.flv) .Start(); }
public ClientFixture() { var options = new ClientOptions { Brokers = new[] { new BrokerAddress { Host = "localhost", Port = 9292 }, } }; Client = new ClientAsync(options); var tokenSource = new System.Threading.CancellationTokenSource(); tokenSource.CancelAfter(System.TimeSpan.FromMilliseconds(5000)); TimeoutToken = tokenSource.Token; }
/// <summary> /// 连接到设备 /// </summary> /// <returns></returns> private async Task ConnectDeviceAsync() { // 断开连接 this.DisconnectDevice(); // 创建TCPClient this.tcpClient = new StreamSocket(); // timeout var cts = new System.Threading.CancellationTokenSource(); cts.CancelAfter(3000); // 连接设备 var connectAsync = this.tcpClient.ConnectAsync(new HostName(this.ip), this.port); // 设置超时 var connectTask = connectAsync.AsTask(cts.Token); await connectTask; }
public async static Task <string> GetHTML(string link, int timeoutMilis = 30000) { var handler = new HttpClientHandler(); if (handler.SupportsAutomaticDecompression) { handler.AutomaticDecompression = DecompressionMethods.GZip; } using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.Add("user-agent", UA); client.DefaultRequestHeaders.Add("referer", link); var cts = new System.Threading.CancellationTokenSource(); cts.CancelAfter(timeoutMilis); var response = await client.GetAsync(link, cts.Token); var html = await response.Content.ReadAsStringAsync(); return(html); } }
async Task <PaymentResponseModel> PayOrder(long requestId, decimal price, string buyer_key) { PaymentResponseModel responseData = new PaymentResponseModel(); System.Threading.CancellationTokenSource cts; HttpClient httpClient = new HttpClient(); TimeSpan time = new TimeSpan(0, 0, 60); httpClient.Timeout = time; cts = new System.Threading.CancellationTokenSource(); cts.CancelAfter(time); PaymentRequestModel model = new PaymentRequestModel() { buyer_key = buyer_key, capture_buyer = 0, currency = Common.payme_currency, installments = 1, payme_sale_id = Common.payme_sale_id, product_name = "Order #" + requestId, sale_callback_url = Common.payme_sale_callback_url, sale_price = 1,//price, sale_return_url = Common.payme_sale_return_url, seller_payme_id = Common.payme_sale_id, transaction_id = requestId.ToString(),// "12345", }; string postData = Newtonsoft.Json.JsonConvert.SerializeObject(model); string url = Common.payme_PaymentUrl; StringContent str = new StringContent(postData, System.Text.Encoding.UTF8, "application/json"); var result = await httpClient.PostAsync(new Uri(url), str); var place = result.Content.ReadAsStringAsync().Result; // deserialization of the response returning from the api responseData = Newtonsoft.Json.JsonConvert.DeserializeObject <PaymentResponseModel> (await result.Content.ReadAsStringAsync()); return(responseData); }
public async Task TestSubscribeSameStream() { var cts = new System.Threading.CancellationTokenSource(); cts.CancelAfter(5000); var streamName = Guid.NewGuid().ToString(); await Fixture.Client.CreateStream(streamName, "test.subscribe", cts.Token); var value = System.Text.Encoding.ASCII.GetBytes("hello, world"); await Fixture.Client.PublishAsync(streamName, value, null, null, cts.Token); var sub1 = Fixture.Client.Subscribe(streamName, new SubscriptionOptions { Partition = 0, StartPosition = Proto.StartPosition.Earliest, }, cts.Token); var sub2 = Fixture.Client.Subscribe(streamName, new SubscriptionOptions { Partition = 0, StartPosition = Proto.StartPosition.Earliest, }, cts.Token); Func <IAsyncEnumerable <Message>, Task> subHandler = async(sub) => { await foreach (var message in sub) { Assert.Equal("hello, world", System.Text.Encoding.UTF8.GetString(message.Value)); break; } }; await Task.WhenAll(subHandler(sub1), subHandler(sub2)); return; }
private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e) { _logger.Debug("Event handler started"); var tokenSource = new System.Threading.CancellationTokenSource(); try { tokenSource.CancelAfter(TimeSpan.FromMilliseconds(_timerInterval)); new System.Threading.Tasks.Task( () => { CheckProcesses(); tokenSource.Token.ThrowIfCancellationRequested(); return; }, tokenSource.Token).Wait(); } catch (AggregateException) { _logger.Error("Timespan exceeded checking the health of running processes. Verify WMI is A-OK and things aren't otherwise stacked up on this server."); } finally { tokenSource.Dispose(); } timer.Start(); _logger.Debug("Event handler completed"); }
public void Connect(string hostName, int port) { //How to secure socket connections with TLS/SSL: //http://msdn.microsoft.com/en-us/library/windows/apps/jj150597.aspx //Networking in Windows 8 Apps - Using StreamSocket for TCP Communication //http://blogs.msdn.com/b/metulev/archive/2012/10/22/networking-in-windows-8-apps-using-streamsocket-for-tcp-communication.aspx Socket = new StreamSocket(); Socket.Control.KeepAlive = true; Socket.Control.NoDelay = true; var host = new HostName(hostName); SocketProtectionLevel spl = SocketProtectionLevel.PlainSocket; if (UseHTTPSProtocol) { spl = SocketProtectionLevel. #if UNITY_WSA_8_0 || BUILD_FOR_WP8 Ssl; } #else Tls12; #endif System.Threading.CancellationTokenSource tokenSource = new System.Threading.CancellationTokenSource(); // https://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj710176.aspx#content try { if (ConnectTimeout > TimeSpan.Zero) { tokenSource.CancelAfter(ConnectTimeout); } var task = Socket.ConnectAsync(host, UseHTTPSProtocol ? "https" : port.ToString(), spl).AsTask(tokenSource.Token); task.ConfigureAwait(false); task.Wait(); Connected = task.IsCompleted; } catch (AggregateException ex) { //https://msdn.microsoft.com/en-us/library/dd537614(v=vs.110).aspx?f=255&MSPPError=-2147217396 Connected = false; if (ex.InnerException != null) //throw ex.InnerException; { if (ex.Message.Contains("No such host is known") || ex.Message.Contains("unreachable host")) { throw new Exception("Socket Exception"); } else { throw ex.InnerException; } } else { throw ex; } } finally { // https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource tokenSource.Dispose(); } if (!Connected) { throw new TimeoutException("Connection timed out!"); } }
private async Task <bool> SelfUpdate() { ChangeProgress(999); ChangeText(I18N.GetString("Get latest version...")); var newVersion = await UpdateChecker.GetVersion(); string proxy = null; if (string.IsNullOrEmpty(newVersion)) { proxy = Microsoft.VisualBasic.Interaction.InputBox(I18N.GetString("We need a proxy to download v2ray core"), "Yo", "http://127.0.0.1:1080"); if (Uri.IsWellFormedUriString(proxy, UriKind.Absolute)) { newVersion = await UpdateChecker.GetVersion(proxy); } } if (string.IsNullOrEmpty(newVersion)) { Process.Start(UpdateChecker.SHELL_URL); return(false); } ChangeText(I18N.GetString("Upgrade {0} to {1} ...", Global.Version, newVersion)); var webClient = new WebClient(); if (!string.IsNullOrEmpty(proxy) && Uri.IsWellFormedUriString(proxy, UriKind.Absolute)) { webClient.Proxy = new WebProxy(new Uri(proxy)); } cts.Token.Register(() => webClient.CancelAsync()); webClient.DownloadProgressChanged += (s, e) => { ChangeProgress(e.ProgressPercentage); }; var downloadURL = $"https://github.wuyanzheshui.workers.dev/TkYu/V2RayShell/releases/download/v{newVersion}/V2RayShell{newVersion}.zip"; ChangeTitle(I18N.GetString("Sit back and relax") + " " + I18N.GetString("Upgrade {0} to {1} ...", Global.Version, newVersion)); ChangeText(I18N.GetString("Downloading file from {0}, You can download it manually and extract to same folder.", downloadURL)); try { webClient.Headers.Add(HttpRequestHeader.UserAgent, UA); cts.CancelAfter(10000); await webClient.DownloadFileTaskAsync(downloadURL, filePath); } catch { if (File.Exists(filePath)) { File.Delete(filePath); } } if (!File.Exists(filePath)) { downloadURL = $"https://github.com/TkYu/V2RayShell/releases/download/v{newVersion}/V2RayShell{newVersion}.zip"; ChangeText(I18N.GetString("Downloading file from {0}, You can download it manually and extract to same folder.", downloadURL)); try { await webClient.DownloadFileTaskAsync(downloadURL, filePath); } catch { if (File.Exists(filePath)) { File.Delete(filePath); } } } if (!File.Exists(filePath)) { if (MessageBox.Show(I18N.GetString("Download fail! Copy link?"), "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes) { Clipboard.SetText(downloadURL); } return(false); } ChangeProgress(100); ChangeText(newVersion + I18N.GetString("Extracting...")); var tempfile = Utils.GetTempPath(Guid.NewGuid().ToString("N")); try { using (var archive = ZipFile.OpenRead(filePath)) { foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.ToLower() == "v2rayshell.exe") { entry.ExtractToFile(tempfile, true); } } } } catch (Exception e) { Logging.LogUsefulException(e); if (File.Exists(tempfile)) { File.Delete(tempfile); } return(false); } finally { File.Delete(filePath); } if (File.Exists(tempfile)) { Program.ViewControllerInstance.HideTray(); var psi = new System.Diagnostics.ProcessStartInfo { Arguments = $"/C @echo off & Title Updating... & echo {I18N.GetString("Sit back and relax")} & taskkill /f /im {System.Diagnostics.Process.GetCurrentProcess().ProcessName}.exe & choice /C Y /N /D Y /T 1 & Del \"{Global.ProcessPath}\" & Move /y \"{tempfile}\" \"{Global.ProcessPath}\" & Start \"\" \"{Global.ProcessPath}\"", WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, CreateNoWindow = true, FileName = "cmd.exe" }; System.Diagnostics.Process.Start(psi); Environment.Exit(0); } return(true); }
async protected override void OnStart() { //////////////////// Read language settings //////////////////////////////// string strLangSequence = await LoadDataFromLocal(CURRENT_LANGUAGE_FILE); if (strLangSequence == string.Empty) { CurrentLanguage = Language.Arabic; // default language } else { CurrentLanguage = HelperClasses.Helper.GetLanguage(strLangSequence); } System.Globalization.CultureInfo ci = null; try { switch (CurrentLanguage) { case Language.English: ci = new System.Globalization.CultureInfo("en"); break; default: ci = new System.Globalization.CultureInfo("ar"); break; } AppResources.Culture = ci; } catch (Exception) { } ///////////////////////////////////////////////////////////////////////////// var cts = new System.Threading.CancellationTokenSource(); // The root page of your application var a = DependencyService.Get<HelperClasses.INetworkConnection>(); if (a.IsConnected) { try { if (!await LoadNewData()) { cts.CancelAfter(4000);// time out of update we can't check for updates more then 4sec await CheckForUpdates(cts.Token); } } catch (Exception) { } finally { if (Categroies != null) { foreach (var area in App.Categroies.CategoryList) { if (area.Type == "area") { if (area.Contents.ar.Title == "مكة") { page1.AddText(area.Contents.ar.Slider); } else { page2.AddText(area.Contents.ar.Slider); } } } } page1.btnEntry.IsEnabled = true; page2.btnEntry.IsEnabled = true; } } else { await LoadOldData(); if (Categroies != null) { foreach (var area in App.Categroies.CategoryList) { if (area.Type == "area") { if (area.Contents.ar.Title == "مكة") { page1.AddText(area.Contents.ar.Slider); } else { page2.AddText(area.Contents.ar.Slider); } } } } page1.btnEntry.IsEnabled = true; page2.btnEntry.IsEnabled = true; } if (await LoadDataFromLocal(SettingFile) == string.Empty) { await SaveToLocal(SettingFile, "false"); } else { bool.TryParse(await LoadDataFromLocal(SettingFile), out SettingPage.LocationEnabled); LocService.Enabled = SettingPage.LocationEnabled; } a = null; // Handle when your app starts }
private static void TestImage(MyUser user) { string image = "images\\1.jpg"; Album album = null; try { album = user.CreateAlbum("TestImageAlbum"); var imageUploader = album.CreateUploader(); try { System.Threading.CancellationTokenSource cts = new System.Threading.CancellationTokenSource(); cts.CancelAfter(1000); imageUploader.UploadProgress += img_UploadProgress; imageUploader.UploadImageAsync(image, cts.Token).Wait(); Debug.Fail("Upload should have been cancelled."); } catch (AggregateException) { Console.WriteLine("Upload canceled --- OK!"); } finally { imageUploader.UploadProgress -= img_UploadProgress; } Console.WriteLine("Re-uploading the image."); var img = imageUploader.UploadImage(image); Console.WriteLine("Image uploaded."); var c1 = img.AddComment("Test comment - no rating"); var c2 = img.AddComment("Test comment - rating 1", 1); img.GetComments(); Debug.Assert(img.Comments.Count == 2); // Watermark var watermark1 = img.CreateWatermark("Watermark 1"); var watermark1_site = user.GetWatermarks().Where((w) => w.Name == "Watermark 1").FirstOrDefault(); Debug.Assert(watermark1_site.id == watermark1.id); watermark1.Delete(); watermark1_site = user.GetWatermarks().Where((w) => w.Name == "Watermark 1").FirstOrDefault(); Debug.Assert(watermark1_site == null); // Printmark var printmark1 = img.CreatePrintmark("Printmark 1"); var printmark1_site = user.GetPrintmarks().Where((w) => w.Name == "Printmark 1").FirstOrDefault(); Debug.Assert(printmark1_site.id == printmark1.id); printmark1.Delete(); } finally { if (album != null) { album.Delete(); } } }
private async void subscribeUpdateItem_Click(object sender, EventArgs e) { var config = controller.GetConfigurationCopy(); if (config.subscribes == null || !config.subscribes.Any()) { return; } subscribeUpdateItem.Enabled = false; var before = config.configs.Count(c => !string.IsNullOrEmpty(c.@group)); foreach (var item in config.subscribes) { var wc = new System.Net.WebClient(); if (item.useProxy) { wc.Proxy = new System.Net.WebProxy(System.Net.IPAddress.Loopback.ToString(), config.localPort); } var cts = new System.Threading.CancellationTokenSource(); // ReSharper disable once AccessToDisposedClosure // ReSharper disable once ConvertToLambdaExpressionWhenPossible cts.Token.Register(() => { wc?.CancelAsync(); }); cts.CancelAfter(10000); string downloadString; try { downloadString = await wc.DownloadStringTaskAsync(item.url); } catch //TODO maybe we can notify? { continue; } wc.Dispose(); var lst = new List <ServerObject>(); if (downloadString.Contains("vmess://")) { var mcg = Regex.Matches(downloadString, @"vmess://(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace); foreach (Match s in mcg) { if (ServerObject.TryParse(s.Value, out ServerObject svc)) { svc.@group = item.name; lst.Add(svc); } } } else { try { var debase64 = downloadString.DeBase64(); var split = debase64.Split('\r', '\n'); foreach (var s in split) { if (ServerObject.TryParse(s, out ServerObject svc)) { svc.@group = item.name; lst.Add(svc); } } } catch { MessageBox.Show(I18N.GetString("Invalid Base64 string."), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } if (lst.Any()) { config.configs.RemoveAll(c => c.@group == item.name); config.configs.AddRange(lst); } } controller.SaveServers(config.configs, config.localPort, config.corePort); var after = config.configs.Count(c => !string.IsNullOrEmpty(c.@group)); if (before != after) { RebuildMenu(); } ShowBalloonTip(I18N.GetString("Update finished"), I18N.GetString("{0} before, {1} after.", before, after)); subscribeUpdateItem.Enabled = true; }
async void AsyncEntryPoint() { goto Started; Started: Started = System.DateTimeOffset.UtcNow; goto Aft; Aft: Begin: System.Tuple <System.Action, ThreadPriorityInformation, System.TimeSpan> Item; try { while (Itinerarius.Count > 0 && UpdateTokenSource.IsCancellationRequested.Equals(false)) { if (Itinerarius.TryDequeue(out Item)) { UpdateTokenSource.CancelAfter(Item.Item3); UnderlyingThread.Priority = System.Threading.ThreadPriority.Lowest; await System.Threading.Tasks.Task.Run(Item.Item1, UpdateTokenSource.Token); UnderlyingThread.Priority = System.Threading.ThreadPriority.BelowNormal; } else { UnderlyingThread.Priority = System.Threading.ThreadPriority.BelowNormal; } if (object.ReferenceEquals(System.Threading.Thread.CurrentThread, UnderlyingThread)) { UnderlyingThread.Priority = System.Threading.ThreadPriority.AboveNormal; } else { System.Threading.Thread.Sleep(System.Threading.Timeout.InfiniteTimeSpan); } } } catch (System.Exception) { if (object.ReferenceEquals(ExceptionHandler, null).Equals(false)) { AggregateExceptions.Handle(ExceptionHandler); goto Begin; } } finally { if (object.ReferenceEquals(ExceptionHandler, null).Equals(false) && AggregateExceptions.Data.Count > 0) { throw AggregateExceptions; } } if (object.ReferenceEquals(System.Threading.Thread.CurrentThread, UnderlyingThread)) { System.Threading.Thread.Sleep(System.Threading.Timeout.InfiniteTimeSpan); goto Begin; } }
private async void OKButton_Click(object sender, EventArgs e) { if (!SaveOld()) { return; } OKButton.Enabled = false; OKButton.Text = I18N.GetString("Busy..."); try { var currentSvc = _controller.GetCurrentServer(); _controller.SaveSubscribes(_modifiedConfiguration.subscribes); if (_lastSelectedIndex > -1) { var item = _modifiedConfiguration.subscribes[_lastSelectedIndex]; var wc = new WebClient(); if (item.useProxy) { wc.Proxy = new WebProxy(IPAddress.Loopback.ToString(), _modifiedConfiguration.localPort); } var cts = new System.Threading.CancellationTokenSource(); // ReSharper disable once AccessToDisposedClosure cts.Token.Register(() => wc?.CancelAsync()); cts.CancelAfter(10000); var downloadString = await wc.DownloadStringTaskAsync(item.url); wc.Dispose(); var lst = new List <ServerObject>(); if (downloadString.Contains("vmess://")) { var mcg = Regex.Matches(downloadString, @"vmess://(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace); foreach (Match s in mcg) { if (ServerObject.TryParse(s.Value, out ServerObject svc)) { svc.@group = item.name; lst.Add(svc); } } } else { try { var debase64 = downloadString.DeBase64(); var split = debase64.Split('\r', '\n'); foreach (var s in split) { if (ServerObject.TryParse(s, out ServerObject svc)) { svc.@group = item.name; lst.Add(svc); } } } catch { MessageBox.Show(I18N.GetString("Invalid Base64 string."), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } if (lst.Any()) { _modifiedConfiguration.configs.RemoveAll(c => c.@group == oldNames[_lastSelectedIndex]); _modifiedConfiguration.configs.AddRange(lst); } } _controller.SaveServers(_modifiedConfiguration.configs, _modifiedConfiguration.localPort, _modifiedConfiguration.corePort); var newIdx = _modifiedConfiguration.configs.IndexOf(currentSvc); if (newIdx == -1) { await _controller.SelectServerIndex(0); } else if (newIdx != _modifiedConfiguration.index) { await _controller.SelectServerIndex(newIdx); } } catch (Exception exception) { Logging.LogUsefulException(exception); } Close(); }