Esempio n. 1
0
 public BlurFace(string storeId, List <RestrictedFaceArea> hiddenRects, int jpegQuality)
 {
     dtStart = DateTime.Now;
     if (String.IsNullOrEmpty(storeId))
     {
         bytes = null;
     }
     else
     {
         bytes = null;
         using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
         {
             try
             {
                 byte[] result = httpClient.GetByteArrayAsync(String.Format("https://drive.google.com/uc?export=view&id={0}", storeId)).Result;
                 using (MemoryStream stream = new MemoryStream(result))
                     using (SKImage image = SKImage.FromEncodedData(stream))
                         Process(image, hiddenRects, jpegQuality);
                 result = null;
             }
             catch (Exception exc1)
             {
                 try
                 {
                     Thread.Sleep(100);
                     byte[] result = httpClient.GetByteArrayAsync(String.Format("https://drive.google.com/uc?export=view&id={0}", storeId)).Result;
                     using (MemoryStream stream = new MemoryStream(result))
                         using (SKImage image = SKImage.FromEncodedData(stream))
                             Process(image, hiddenRects, jpegQuality);
                     result = null;
                 }
                 catch (Exception exc2)
                 {
                     try
                     {
                         Thread.Sleep(100);
                         byte[] result = httpClient.GetByteArrayAsync(String.Format("https://drive.google.com/uc?export=view&id={0}", storeId)).Result;
                         using (MemoryStream stream = new MemoryStream(result))
                             using (SKImage image = SKImage.FromEncodedData(stream))
                                 Process(image, hiddenRects, jpegQuality);
                         result = null;
                     }
                     catch (Exception exc3)
                     {
                     }
                 }
             }
         }
     }
 }
Esempio n. 2
0
        public async Task <byte[]> GetFileStreamAsync(string url)
        {
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            var fileStream = await client.GetByteArrayAsync(url);

            return(fileStream);
        }
Esempio n. 3
0
        public async Task Update(string LatestVersion)
        {
            var message = await ReplyAsync("", false, Embed.GetEmbed("**Bot Update**", $"Downloading the files!, Won't be long!"));

            string url  = $"https://github.com/{Program.OwnerGithub}/{Program.BotRepo}/releases/download/{LatestVersion}/Release.zip";
            string path = $"Release.zip";

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            using (var client = new System.Net.Http.HttpClient())
            {
                var contents = client.GetByteArrayAsync(url).Result;
                File.WriteAllBytes(path, contents);
            }
            Program.Bot_Properties.updated   = true;
            Program.Bot_Properties.guildId   = Context.Guild.Id;
            Program.Bot_Properties.channelId = Context.Channel.Id;
            Program.Bot_Properties.messageId = message.Id;
            Updater.Save(Program.Bot_Properties);

            Json.CreateJson("Ver", $"{Program.Rootdir}", new Ver()
            {
                version = LatestVersion
            });

            await message.ModifyAsync(x => x.Embed = Embed.GetEmbed("**Bot Update**", $"There we go, brb!"));

            Environment.Exit(60001);
        }
Esempio n. 4
0
        public void DownloadIfNotExist(ProjectBuildContext context)
        {
            using (var client = new System.Net.Http.HttpClient())
            {
                if (File.Exists(context.Template.FilePath))
                {
                    return;
                }

                lock (LockObject)
                {
                    if (File.Exists(context.Template.FilePath))
                    {
                        return;
                    }

                    var downloadUrl = "https://github.com/" + context.Template.GithubRepository.RepositoryNameWithOrganization + "/archive/" + context.Template.Version + ".zip";

                    var credentials = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:", context.Template.GithubRepository.AccessToken);
                    credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));

                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentials);
                    client.Timeout = TimeSpan.FromMinutes(30);

                    var fileContents = AsyncHelper.RunSync(() => client.GetByteArrayAsync(downloadUrl));

                    File.WriteAllBytes(context.Template.FilePath, fileContents);
                }
            }
        }
Esempio n. 5
0
        public static async Task <Stream> GetStreamAsync(string url)
        {
            var client = new System.Net.Http.HttpClient();
            var array  = await client.GetByteArrayAsync(url);

            return(new MemoryStream(array));
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            var deferral = taskInstance.GetDeferral();

            if (localSettings.Values.ContainsKey("Theme") && (int)localSettings.Values["Theme"] == 4)
            {
                try
                {
                    var httpclient = new System.Net.Http.HttpClient();
                    var picbytes   = await httpclient.GetByteArrayAsync("http://appserver.m.bing.net/BackgroundImageService/TodayImageService.svc/GetTodayImage?dateOffset=0&urlEncodeHeaders=true&osName=windowsPhone&osVersion=8.10&orientation=480x800&deviceName=WP8&mkt=en-US");

                    var picfile = await localFolder.CreateFileAsync("bingbackground.jpg", CreationCollisionOption.ReplaceExisting);

                    await FileIO.WriteBytesAsync(picfile, picbytes);

                    localSettings.Values["isReloadBingSkin"] = true;
                    Debug.WriteLine("BingSkinUpdateSuccess");
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                }
            }
            deferral.Complete();
        }
Esempio n. 7
0
        protected override async void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            if (e.PropertyName == "Renderer")
            {
                if (loaded)
                {
                    return;
                }

                var uriImageSource = Element.Source as UriImageSource;
                if (uriImageSource == null || uriImageSource.Uri == null)
                {
                    return;
                }

                try
                {
                    loaded = true;
                    using (var client = new System.Net.Http.HttpClient())
                    {
                        var bytes = await client.GetByteArrayAsync(uriImageSource.Uri);

                        var sourceRef = CGImageSource.FromData(NSData.FromArray(bytes));
                        CreateAnimatedImageView(sourceRef, this.Control);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unable to load gif: " + ex.Message);
                }
            }
        }
Esempio n. 8
0
        static async Task <bool> DownloadTaskAsync(string url, string path)
        {
            try
            {
                using (var client = new System.Net.Http.HttpClient())
                {
                    var data = await client.GetByteArrayAsync(url);

                    System.Diagnostics.Debug.WriteLine("DownloadTask: byte array downloaded for [" + url + "]");
                    var fileNamePaths = path.Split('\\');
                    if (File.Exists(path))
                    {
                        System.Diagnostics.Debug.WriteLine("DownloadTask: FILE ALREADY EXISTS [" + path + "] [" + url + "]");
                    }
                    using (var stream = new FileStream(path, FileMode.Create))
                    //using (var stream = new IsolatedStorageFileStream(path, FileMode.Create, Storage))
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            return(false);
        }
        public static async System.Threading.Tasks.Task <string> BuildItAsync(string modulenameToBuild, bool Overwrite)
        {
            var repoLocation = "";

            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                repoLocation = @"c:\DecisionsModuleBuilderTemp\";
            }
            else
            {
                repoLocation = Path.GetTempPath();
            }
            var repofullpath = repoLocation + "" + modulenameToBuild;
            var exists       = System.IO.Directory.Exists(repofullpath);
            var user         = Environment.UserName;

            System.IO.Directory.CreateDirectory(repofullpath);
            exists = System.IO.Directory.Exists(repofullpath);
            var path = repofullpath;

            try
            {
                var url = "https://github.com/decisions-com/decisions-mod-skeleton/archive/master.zip";
                ;

                using (var client = new System.Net.Http.HttpClient())
                {
                    var contents = client.GetByteArrayAsync(url).Result;

                    System.IO.File.WriteAllBytes(path + "/master.zip", contents);
                    String ZipPath     = path + "/master.zip";
                    String extractPath = path;
                    ZipFile.ExtractToDirectory(ZipPath, extractPath);
                    var SourcePath = path + "/decisions-mod-skeleton-master";
                    foreach (string dirPath in Directory.GetDirectories(SourcePath, "*",
                                                                        SearchOption.AllDirectories))
                    {
                        Directory.CreateDirectory(dirPath.Replace(SourcePath, path));
                    }

                    //Copy all the files & Replaces any files with the same name
                    foreach (string newPath in Directory.GetFiles(SourcePath, "*.*",
                                                                  SearchOption.AllDirectories))
                    {
                        File.Move(newPath, newPath.Replace(SourcePath, path));
                    }

                    Directory.Delete(path + "/decisions-mod-skeleton-master", true);
                    File.Delete(path + "/master.zip");
                }
            }
            catch (Exception ex2)
            {
                return(ex2.Message);
            }



            return(path);
        }
Esempio n. 10
0
        public async Task <TemplateFile> GetAsync(string templateName, string version)
        {
            var localCacheFolder = Path.Combine(CliPaths.TemplateCache, version);

            DirectoryHelper.CreateIfNotExists(localCacheFolder);

            var localCacheFile = Path.Combine(localCacheFolder, templateName + ".zip");

            if (File.Exists(localCacheFile))
            {
                Logger.LogInformation("Using cached template: " + templateName + ", version: " + version);
                return(new TemplateFile(File.ReadAllBytes(localCacheFile)));
            }

            Logger.LogInformation("Downloading template: " + templateName + ", version: " + version);

            using (var client = new System.Net.Http.HttpClient())
            {
                client.Timeout = TimeSpan.FromMinutes(5);
                var downloadUrl  = "https://abp.io/downloads/templates/" + version + "/" + templateName + ".zip";
                var fileContents = await client.GetByteArrayAsync(downloadUrl);

                File.WriteAllBytes(localCacheFile, fileContents);
                return(new TemplateFile(fileContents));
            }
        }
        public async Task Widget([Remainder] string mod)
        {
            mod = mod.RemoveWhitespace();
            var(result, str) = await ShowSimilarMods(mod);

            if (result)
            {
                var modFound = ModsManager.Mods.FirstOrDefault(x => x.EqualsIgnoreCase(mod));

                if (modFound != null)
                {
                    var msg = await ReplyAsync($"Generating widget for {modFound}...");

                    // need perfect string.

                    using (var client = new System.Net.Http.HttpClient())
                    {
                        var response = await client.GetByteArrayAsync($"{ModsManager.WidgetUrl}{modFound}.png");

                        using (var stream = new MemoryStream(response))
                        {
                            await Context.Channel.SendFileAsync(stream, $"widget-{modFound}.png");
                        }
                    }
                    await msg.DeleteAsync();
                }
            }
        }
Esempio n. 12
0
        public async Task <int> GetBikeCountInStation(string station)
        {
            var httpClient = new System.Net.Http.HttpClient();

            var toast = await httpClient.GetByteArrayAsync("http://api.digitransit.fi/routing/v1/routers/hsl/bike_rental");

            string utfString = System.Text.Encoding.UTF8.GetString(toast);
            BikeRentalStationList stationInfo = Newtonsoft.Json.JsonConvert.DeserializeObject <BikeRentalStationList>(utfString);

            try
            {
                if (stationInfo.stations.Length != 0)
                {
                    for (int i = 0; i < stationInfo.stations.Length; ++i)
                    {
                        if (station.ToLower() == stationInfo.stations[i].name.ToLower())
                        {
                            _bikesAvailable = stationInfo.stations[i].bikesAvailable;
                            Console.WriteLine(stationInfo.stations[i].name + " has " + _bikesAvailable + " bike(s) available.\n");
                            return(_bikesAvailable);
                        }
                    }
                }
                throw new NotFoundException("Station with that name was not found");
            }
            catch (NotFoundException e)
            {
                Console.WriteLine(e.Message);
            }
            return(0);
        }
Esempio n. 13
0
        private async void SaveImage(object sender, RoutedEventArgs e)
        {
            var view      = flipview.Items[flipview.SelectedIndex] as ScrollViewer;
            var image     = view.Content as Image;
            var imgsource = image.Source as Windows.UI.Xaml.Media.Imaging.BitmapImage;

            if (Class.HttpPostUntil.isInternetAvailable)
            {
                var httpclient = new System.Net.Http.HttpClient();
                var bytes      = await httpclient.GetByteArrayAsync(imgsource.UriSource.ToString());

                var foler = await KnownFolders.PicturesLibrary.CreateFolderAsync("保存的图片", CreationCollisionOption.OpenIfExists);

                var filename = DateTime.Now.ToFileTime().ToString();
                var file     = await foler.CreateFileAsync(filename + ".jpg", CreationCollisionOption.ReplaceExisting);

                await FileIO.WriteBytesAsync(file, bytes);

                Class.Tools.ShowMsgAtFrame("图片已保存:" + file.Path);
            }
            else
            {
                Class.Tools.ShowMsgAtFrame("请检查网络连接");
            }
        }
Esempio n. 14
0
        public static async Task <string> HttpClientGetStringAsync(string url, Encoding encoding = null, CookieCollection cookies = null)
        {
            if (cookies != null)
            {
                var cookiesStr = "";
                foreach (System.Net.Cookie item in cookies)
                {
                    cookiesStr += $"{item.Name}={item.Value};";
                }
                var message = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
                message.Headers.Add("Cookie", cookiesStr);
                await httpClient.SendAsync(message);
            }

            var source = "";

            var buffer = await httpClient.GetByteArrayAsync(url);

            if (encoding == null)
            {
                encoding = EncodingUtil.GetEncoding(buffer);
            }

            source = encoding.GetString(buffer);
            return(source);
        }
Esempio n. 15
0
        public static void Httpdownload()
        {
            string url         = @"http://risk.longfor.sit/file/download/noauth/138aa91f-d6dc-4e16-b056-756f6f1c6909";
            string newFileName = Guid.NewGuid().ToString();
            var    httpClient  = new System.Net.Http.HttpClient();

            var t = httpClient.GetByteArrayAsync(url);

            t.Wait();


            string fileExtension = (Path.GetExtension(url) ?? string.Empty).ToLower();

            if (string.IsNullOrWhiteSpace(newFileName))
            {
                newFileName = Path.GetFileName(url);
            }
            else
            {
                //文件名+文件后缀名
                newFileName = newFileName + fileExtension;
            }
            //return File(t.Result, "application/octet-stream", newFileName);

            File.WriteAllBytes($"D:\\123\\{newFileName}", t.Result);
        }
Esempio n. 16
0
        internal static string Get(string url, int timeout = 10000)
        {
#if NET20 || NET40
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.Method  = "GET";
            httpWebRequest.Timeout = timeout;
            using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
            {
                var rs = httpWebResponse.GetResponseStream();
                if (rs == null)
                {
                    throw new Exception("服务器没有返回任何内容");
                }
                using (var streamReader = new StreamReader(rs))
                {
                    return(streamReader.ReadToEnd());
                }
            }
#else
            using (var hc = new System.Net.Http.HttpClient())
            {
                hc.Timeout = TimeSpan.FromMilliseconds(timeout);
                var t = hc.GetByteArrayAsync(url);
                t.Wait(timeout);
                if (!t.IsCompleted)
                {
                    throw new TimeoutException("Request Time Out");
                }
                var data = t.Result;
                return(Encoding.UTF8.GetString(data));
            }
#endif
        }
Esempio n. 17
0
        private async Task <Stream> GetStreamFromUrl(string url)
        {
            byte[] imageData;

            using (var client = new System.Net.Http.HttpClient())
                imageData = await client.GetByteArrayAsync(url);

            return(new MemoryStream(imageData));
        }
Esempio n. 18
0
        internal static async System.Threading.Tasks.Task <string> GetAsync(string url, int timeout = 10000)
        {
            using (var hc = new System.Net.Http.HttpClient())
            {
                hc.Timeout = TimeSpan.FromMilliseconds(timeout);
                var data = await hc.GetByteArrayAsync(url);

                return(Encoding.UTF8.GetString(data));
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Downloads the Report in binary form
        /// </summary>
        /// <returns></returns>
        public async Task <byte[]> DownloadAync()
        {
            var url = this.GetUrl();
            var cl  = new System.Net.Http.HttpClient();

#pragma warning disable CA2234 // Pass system uri objects instead of strings
            return(await cl.GetByteArrayAsync(url).ConfigureAwait(false));

#pragma warning restore CA2234 // Pass system uri objects instead of strings
        }
Esempio n. 20
0
 public static void GetRepoZip(string token, string url, string name, string Folder)
 {
     using (var client = new System.Net.Http.HttpClient())
     {
         var credentials = string.Format(CultureInfo.InvariantCulture, "{0}:", token);
         credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
         client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentials);
         var contents = client.GetByteArrayAsync(url).Result;
         File.WriteAllBytes(@Folder + "/" + name, contents);
     }
 }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            var wc = new System.Net.Http.HttpClient(new Uno.UI.Wasm.WasmHttpHandler());

            var _500KbFileSampleUrl = "https://file-examples-com.github.io/uploads/2017/10/file-example_PDF_500_kB.pdf";
            var _1MbFileSampleUrl   = "https://file-examples-com.github.io/uploads/2017/10/file-example_PDF_1MB.pdf";

            var bytes = await wc.GetByteArrayAsync(new Uri(_1MbFileSampleUrl));

            Console.WriteLine($"Array length: {(bytes?.Length.ToString() ?? "0")}");
        }
Esempio n. 22
0
 public static async Task<string> DownloadStringAsync(Uri url)
 {
     try
     {
         using (var client = new System.Net.Http.HttpClient())
         {
             var bytes = await client.GetByteArrayAsync(url);
             return System.Text.Encoding.GetEncoding("ISO-8859-1").GetString(bytes,0,bytes.Count());
         }
     }
     catch (Exception e) { return null; }
 }
Esempio n. 23
0
        public async Task <int> setImage(string currentWeatherIcon)
        {
            var httpClient = new System.Net.Http.HttpClient();
            var bytes      = await httpClient.GetByteArrayAsync("http://openweathermap.org/img/wn/" + currentWeatherIcon + "@2x.png");

            // wrap the bytes in a stream
            var stream = new MemoryStream(bytes);

            // decode the bitmap stream
            this.CurrentWeatherIcon = SKBitmap.Decode(stream);

            return(0);
        }
        public async Task <bool> SaveFileFromServer(StorageFolder folder, string fileName, Uri serverURI)
        {
            try
            {
                Debug.WriteLine("Opening Client");
                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

                Debug.WriteLine("Getting Image Bytes");
                byte[] data = await client.GetByteArrayAsync(serverURI);

                return(await CreateFile(folder, fileName, data));
            }
            catch (Exception) { }

            return(false);
        }
Esempio n. 25
0
        public static ImageSource GetResizeImageSourceFromUrl(int size, int quality, string url)
        {
            var httpClient = new System.Net.Http.HttpClient();
            var bytes      = httpClient.GetByteArrayAsync(serverUrl + url).Result;
            var stream     = new MemoryStream(bytes);
            var bitmap     = SKBitmap.Decode(stream);

            int width, height;

            //Считаем новые размеры исходя из оригенального размера
            if (bitmap.Width > bitmap.Height)
            {
                width  = size;
                height = bitmap.Height * size / bitmap.Width;
            }
            else
            {
                width  = bitmap.Width * size / bitmap.Height;
                height = size;
            }

            //Создаем картинку с новым размером
            using (var resized = bitmap?.Resize(new SKImageInfo(width, height), SKBitmapResizeMethod.Lanczos3))
            {
                if (resized == null)
                {
                    throw new Exception("Error resized.");
                }

                using (var image = SKImage.FromBitmap(resized))
                {
                    SKData encodedData = image.Encode(SKEncodedImageFormat.Jpeg, 100);

                    string folder    = Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures);
                    string filename  = $"{Guid.NewGuid()}.jpeg";
                    string imagePath = Path.Combine(FileSystem.CacheDirectory, filename);

                    var bitmapImageStream = File.Open(imagePath, FileMode.Create, FileAccess.Write, FileShare.None);

                    encodedData.SaveTo(bitmapImageStream);
                    bitmapImageStream.Flush(true);
                    bitmapImageStream.Dispose();

                    return(ImageSource.FromFile(imagePath));
                }
            }
        }
            public static async Task GetBingTheme()
            {
                try
                {
                    var httpclient = new System.Net.Http.HttpClient();
                    var picbytes   = await httpclient.GetByteArrayAsync("http://appserver.m.bing.net/BackgroundImageService/TodayImageService.svc/GetTodayImage?dateOffset=0&urlEncodeHeaders=true&osName=windowsPhone&osVersion=8.10&orientation=480x800&deviceName=WP8&mkt=en-US");

                    var picfile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Theme/Skin/Bing/background.jpg"));

                    await FileIO.WriteBytesAsync(picfile, picbytes);

                    WriteableBitmap wb = new WriteableBitmap(1000, 1500);
                    await wb.SetSourceAsync(await picfile.OpenAsync(FileAccessMode.Read));

                    var bingtheme = new BingThemeData();
                    bingtheme.BackgroundColor  = GetColor.GetMajorColor(wb);
                    bingtheme.BackgroundColor1 = Color.FromArgb(190, bingtheme.BackgroundColor.R, bingtheme.BackgroundColor.G, bingtheme.BackgroundColor.B);
                    var rgb = bingtheme.BackgroundColor.R * 0.299 + bingtheme.BackgroundColor.G * 0.587 + bingtheme.BackgroundColor.B * 0.114;
                    bingtheme.BackgroundColor2 = bingtheme.BackgroundColor;
                    if (rgb >= 192)
                    {
                          {
                            bingtheme.Foreground      = Colors.White;
                            bingtheme.Front1          = Colors.White;
                            bingtheme.Front2          = Color.FromArgb(255, 185, 185, 185);
                            bingtheme.List_Background = Color.FromArgb(100, 103, 103, 103);
                        }
                    }
                    else
                    {
                        bingtheme.Foreground      = Colors.White;
                        bingtheme.Front1          = Colors.Black;
                        bingtheme.Front2          = Color.FromArgb(255, 124, 124, 124);
                        bingtheme.List_Background = Color.FromArgb(180, 255, 255, 255);
                    }
                    string xamlstring = await PathIO.ReadTextAsync("ms-appx:///Theme/BingTemp.txt");

                    xamlstring = String.Format(xamlstring, bingtheme.BackgroundColor.ToString(), bingtheme.BackgroundColor1.ToString(), bingtheme.BackgroundColor2.ToString(), bingtheme.Foreground.ToString(), bingtheme.Front1.ToString(), bingtheme.Front2.ToString(), bingtheme.List_Background.ToString());
                    var xamlfile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Theme/BingTheme.xaml"));

                    await FileIO.WriteTextAsync(xamlfile, xamlstring);
                }
                catch (Exception)
                {
                    await new MessageDialog("无网络连接!").ShowAsync();
                }
            }
Esempio n. 27
0
        static void Main(string[] args)
        {
            if (!Directory.Exists("Bot") || !File.Exists("Bot/CaliBotCore.exe"))
            {
                Directory.CreateDirectory("Bot");
                Console.WriteLine("Bot not found, Bot directory created, Once the bot launches, please ensure that it is updated to the latest version using the update command");

                string url  = @"https://github.com/{OwnerGithub}/{BotRepo}/releases/download/{Ver}/Release.zip";
                string path = $"Release.zip";
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                using (var client = new System.Net.Http.HttpClient())
                {
                    var contents = client.GetByteArrayAsync(url).Result;
                    File.WriteAllBytes(path, contents);
                }

                ZipFile.ExtractToDirectory(@"Release.zip", "Bot", true);
            }

            var bot = Restart();

            while (true)
            {
                bot.WaitForExit();
                var exit = bot.ExitCode;
                Console.WriteLine($"Bot exited with code: {exit}");
                if (exit == 60000)
                {
                    Console.WriteLine($"Restarting...");
                    bot = Restart();
                }
                else if (exit == 60001)
                {
                    Console.WriteLine($"Updating");
                    ZipFile.ExtractToDirectory(@"Release.zip", "Bot", true);
                    bot = Restart();
                }
                else
                {
                    Console.WriteLine("Unspecified exit");
                    Console.ReadKey();
                }
            }
        }
Esempio n. 28
0
 /// <summary>
 /// Download an internet resource
 /// </summary>
 /// <param name="URL">The url to try to access</param>
 /// <param name="outdir">The directory to write the file to</param>
 /// <param name="outname">The name of the file to write</param>
 /// <returns>The result of the operation</returns>
 public static async Task <bool> DownloadResource(string URL, string outdir, string outname)
 {
     try
     {
         byte[] FileData;
         using (var client = new System.Net.Http.HttpClient())
         {
             FileData = await client.GetByteArrayAsync(URL);
         }
         File.WriteAllBytes(Path.Combine(outdir, outname), FileData);
     }
     catch
     {
         return(false);
     }
     return(true);
 }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                var split  = value.ToString().Split('/').Last();
                var dirs   = split.Split('\\');
                var incDir = "";
                for (int i = 0; i < dirs.Count() - 1; i++)
                {
                    incDir += (i > 0 ? "\\" : "") + dirs[i];
                    if (!System.IO.Directory.Exists(incDir))
                    {
                        System.IO.Directory.CreateDirectory(incDir);
                    }
                }

                string file = "";
                for (int i = 0; i < dirs.Count(); i++)
                {
                    file += (i > 0 ? "\\":"") + dirs[i];
                }

                using (var client = new System.Net.Http.HttpClient())
                {
                    var stream = client.GetByteArrayAsync(new Uri(value.ToString())).Result;
                    System.IO.File.WriteAllBytes(file, stream);
                    //  client.DownloadFile(new Uri(value.ToString()), file);
                }


                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.CacheOption   = BitmapCacheOption.OnLoad;
                image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                image.UriSource     = new Uri(file as string, UriKind.Relative);
                image.EndInit();

                CroppedBitmap chunk = new CroppedBitmap(image, new Int32Rect(image.PixelWidth / 4, image.PixelHeight / 4, image.PixelWidth / 2, image.PixelHeight / 3));

                return(chunk);
            }
            catch (Exception ex)
            { System.IO.File.WriteAllText("logconv.txt", ex.Message); }

            return(null);
        }
Esempio n. 30
0
        private async Task DownloadImageAsync(string fileName, Uri uri)
        {
            try
            {
                using (var httpClient = new System.Net.Http.HttpClient()) {
                    // Get the file extension
                    var uriWithoutQuery = uri.GetLeftPart(UriPartial.Path);
                    var fileExtension   = System.IO.Path.GetExtension(uriWithoutQuery);

                    // Download the image and write to the file
                    var path       = System.IO.Path.Combine(mediaPath, $"{fileName}{fileExtension}");
                    var imageBytes = await httpClient.GetByteArrayAsync(uri);

                    await File.WriteAllBytesAsync(path, imageBytes);
                }
            }
            catch { }
        }
Esempio n. 31
0
        public async Task <bool> SaveUrlDataToFile(string url, string destinationPath)
        {
            try{
                Uri baseUri = new Uri(url);
                System.Net.Http.HttpClientHandler clientHandler = new System.Net.Http.HttpClientHandler();
                System.Net.Http.HttpClient        httpClient    = new System.Net.Http.HttpClient(clientHandler);
                httpClient.BaseAddress = baseUri;
                byte[] imageBytes = await httpClient.GetByteArrayAsync(baseUri);

                System.IO.File.WriteAllBytes(destinationPath, imageBytes);

                Console.WriteLine("Data saved succesfully for " + url + " to " + destinationPath);
                return(true);
            } catch (Exception e) {
                throw new Exception("error when saving data for " + url + ". " + e);
                //return false;
            }
        }
Esempio n. 32
0
        /// <summary>
        /// 根据SceneId 获取 二维码图片流
        /// </summary>
        /// <param name="scene_id"></param>
        /// <returns></returns>
        public static Stream GetQrCodeImageStream(string scene_id)
        {
            string Ticket = CreateTicket(scene_id);

            if (Ticket == null)
                throw new ArgumentNullException("Ticket");

            //ticket需 urlEncode
            string strUrl = string.Format(WeiXinConst.WeiXin_QrCode_GetUrl, HttpUtility.UrlEncode(Ticket));
            try
            {
                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                Byte[] bytes = client.GetByteArrayAsync(strUrl).Result;
                return new MemoryStream(bytes);
            }
            catch
            {
                throw new Exception("获取二维码图片失败!");
            }
        }