//get new image private void button1_Click(object sender, EventArgs e) { //rolling for random image int id = ids[r.Next(ids.Length)]; FileInfo f = new FileInfo(Path.Combine(appdir, id + ".jpg")); //TODO: work on the existing picture logic //if (!f.Exists) { //} //downloading json file into a string WebClient wc = new WebClient(); string s; try { s = wc.DownloadString("https://www.gstatic.com/prettyearth/assets/data/" + id + ".json"); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); wc.Dispose(); return; } wc.Dispose(); //converting json file to object Location loc = JsonConvert.DeserializeObject<Location>(s); //saving image from json to a local file loc.getImage().Save(f.FullName, System.Drawing.Imaging.ImageFormat.Jpeg); lblId.Text = "ID: " + loc.id; lblLoc.Text = loc.geocode.ToString(); //setting wallpaper SystemParametersInfo(0x14, 0, f.FullName, 0x01 | 0x02); }
/// <summary> /// /// </summary> /// <param name="UriStr"></param> private void LoadDocumentFromURI(String UriStr) { if (!_downloading) { _client = new WebClient(); _client.DownloadProgressChanged += _client_DownloadProgressChanged; _client.DownloadDataCompleted += _client_DownloadDataCompleted; try { // запускаем загрузку _client.DownloadDataAsync(new Uri(UriStr)); _downloading = true; //DownloadBtn.Text = "Отменить"; } catch (UriFormatException ex) { OperationResult = ex.Message; _client.Dispose(); } catch (WebException ex) { OperationResult = ex.Message; _client.Dispose(); } } else { _client.CancelAsync(); } }
void download(object o) { WebClient wc = null; try { List<object> obj = (List<object>)o; string uri = (string)obj[0]; string local = (string)obj[1]; Song song = (Song)obj[2]; int diff = (int)obj[3]; wc = new WebClient(); wc.Proxy = null; wc.CachePolicy = new System.Net.Cache.HttpRequestCachePolicy(System.Net.Cache.HttpRequestCacheLevel.NoCacheNoStore); wc.DownloadFile(uri, local); if (downloadFinish != null) { downloadFinish.Invoke(song, diff); } wc.Dispose(); } catch (ThreadAbortException) { if (wc != null) { wc.Dispose(); } } catch (Exception) { if (wc != null) { wc.Dispose(); } } }
/// <summary> /// Parses and returns an array of nodes grabbed from https://wiki.tox.im/Nodes. Only use this if you're desperate. /// </summary> /// <returns></returns> public static ToxNode[] GetNodes() { WebClient client = new WebClient(); string content = ""; try { content = client.DownloadString("https://wiki.tox.im/Nodes"); client.Dispose(); } catch { client.Dispose(); return new ToxNode[0]; } var list = new List<ToxNode>(); int index = content.IndexOf("<table"); string table = content.Substring(index, content.IndexOf("</table") - index + "</table".Length); for (int i = 0; i < table.Length; i++) { if (table[i] != '<') continue; if (string.Concat(table[i], table[i+1], table[i+2]) == "<tr") { index = table.IndexOf(">", i + 3) + 1; string row = table.Substring(index, table.IndexOf("</tr>", i) - index).Replace("\n", ""); if (row.StartsWith("<th")) continue; string[] cells = new string[7]; int count = 0; for (int j = 0; j < row.Length; j++) { if (row[j] != '<') continue; if (string.Concat(row[j], row[j + 1], row[j + 2], row[j + 3]) == "<td>") { index = row.IndexOf("<td>", j) + 4; string cell = row.Substring(index, row.IndexOf("</td>", j) - index); cells[count] = cell; count++; } } list.Add(new ToxNode(cells[0], int.Parse(cells[2]), new ToxKey(ToxKeyType.Public, cells[3]))); } } return list.ToArray(); }
private void genBtn_Click(object sender, EventArgs e) { WebClient client = new WebClient(); try { client.DownloadString(webUrl.Text); } catch (Exception WTFBBQ) //Yes, I know WTFBBQ is never used, tysm VS! Now shut up. -DeathRight { client.Dispose(); MessageBox.Show("The URL specified, \"" + webUrl.Text + "\" does not exist.", "Why did you give me a invalid URL?!"); return; } client.Dispose(); /*if (String.IsNullOrWhiteSpace(serverName.Text)) { MessageBox.Show("Sorry, but I don't think that \"" + serverName.Text + "\" is a very good name.\r\nTry again, only this time, do it properly, noob.", "Interesting choice of a server name"); return; } else*/ if (serverName.Text == "MapleStory") { MessageBox.Show("Is Nexon using my Patch Creator?", "...Nexon?"); } else if (serverName.Text == "MapleSEA") { MessageBox.Show("¿Está utilizando Nexon mi Creador Parche?", "...Nexon?"); } if (String.IsNullOrWhiteSpace(startVer.Text)) { MessageBox.Show("Enter a valid number, noob.", "Enter a valid number"); return; } try { int test = Convert.ToInt32(startVer.Text); } catch (Exception WTFBBQ) { MessageBox.Show("Enter a valid number, noob.", "Enter a valid number"); return; } WzSettingsManager SettingsMngr = new WzSettingsManager(System.IO.Path.Combine(Application.StartupPath, "PatcherSettings.wz"), typeof(Patcher_UserSettings), typeof(Patcher_AppSettings)); SettingsMngr.Load(); Patcher_UserSettings.CurrentVersion = Convert.ToInt32(startVer.Text); Patcher_AppSettings.PatchURL = webUrl.Text; Patcher_AppSettings.ServerName = serverName.Text; Patcher_AppSettings.PatcherLogo = new Bitmap(logoPicture.Image); AppSettings.Logo = new Bitmap(logoPicture.Image); SettingsMngr.Save(); MessageBox.Show("It was saved to: "+Application.StartupPath+"\\PatcherSettings.wz","Patcher settings file generated successfully!"); }
public async Task<bool> Download(string uri, string filename) { try { string downloadPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string downloadFilePath = Path.Combine(downloadPath, filename); if (System.IO.File.Exists(downloadFilePath)) { PlayVideo( downloadFilePath ); return true; } webClient = new WebClient(); webClient.DownloadDataCompleted += async (s, e) => { if( e.Cancelled ) { BTProgressHUD.Dismiss(); webClient.Dispose(); return; } var bytes = e.Result; // get the downloaded data string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string localFilename = filename; string localPath = Path.Combine(documentsPath, localFilename); File.WriteAllBytes(localPath, bytes); // writes to local storage ALAssetsLibrary videoLibrary = new ALAssetsLibrary(); await videoLibrary.WriteVideoToSavedPhotosAlbumAsync( new Foundation.NSUrl( localPath )); BTProgressHUD.Dismiss(); PlayVideo( localPath ); webClient.Dispose(); }; BTProgressHUD.Show("cancel", OnCancelDownload, "Downloading Media....",-1, ProgressHUD.MaskType.Black ); var url = new Uri(uri); webClient.DownloadDataAsync(url); return true; } catch( Exception ex ) { return false; } }
public BitmapImage BitmapImage(string url) { Stream stream = null; WebClient webClient = new WebClient(); BitmapImage image = new BitmapImage(); try { stream = new MemoryStream(webClient.DownloadData(url)); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; // here image.StreamSource = stream; image.EndInit(); image.Freeze(); } catch { } if (stream != null) { stream.Close(); stream.Dispose(); stream = null; } url = null; webClient.Dispose(); webClient = null; return image; }
public string downloadBinaryFile_Action(string urlOfFileToFetch, string targetFileOrFolder) { if (urlOfFileToFetch.is_Null() || targetFileOrFolder.is_Null()) return null; var targetFile = targetFileOrFolder; if (Directory.Exists(targetFileOrFolder)) targetFile = targetFileOrFolder.pathCombine(urlOfFileToFetch.fileName()); PublicDI.log.debug("Downloading Binary File {0}", urlOfFileToFetch); lock (this) { using (var webClient = new WebClient()) { try { byte[] pageData = webClient.DownloadData(urlOfFileToFetch); O2Kernel_Files.WriteFileContent(targetFile, pageData); PublicDI.log.debug("Downloaded File saved to: {0}", targetFile); webClient.Dispose(); GC.Collect(); // because of WebClient().GetRequestStream prob return targetFile; } catch (Exception ex) { PublicDI.log.ex(ex); } } } GC.Collect(); // because of WebClient().GetRequestStream prob return null; }
protected virtual void UpdateAsync(string url, string filename, bool silent, object userState) { WebClient client = null; WorkingUI work = null; try { if (silent == false) { work = new WorkingUI(); } string updatedExePath = Path.Combine(Program.AppData, filename); client = new WebClient(); client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(updater_DownloadFileCompleted); client.DownloadFileAsync(new Uri(url), updatedExePath, new object[] { client, updatedExePath, silent, work, userState }); } catch { if (client != null) { client.Dispose(); client = null; } if (silent == false) { work.Dispose(); } throw; } }
static void Main(string[] args) { // Task 4: Write a program that downloads a file from Internet // (e.g. http://www.devbg.org/img/Logo-BASD.jpg) and stores it // the current directory. Find in Google how to download files // in C#. Be sure to catch all exceptions and to free any used // resources in the finally block. WebClient webClient = new WebClient(); try { webClient.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", "Logo-BASD.jpg"); Console.WriteLine("Operation executed successfully."); } catch (ArgumentNullException) { Console.WriteLine("The address parameter is Nothing."); } catch (WebException) { Console.WriteLine("Invalid address or file does not exist."); } catch (NotSupportedException) { Console.WriteLine("The method has been called simultaneously on multiple threads."); } finally { webClient.Dispose(); } }
/// <summary> /// This method is used to upload a file to the specified URI. /// </summary> /// <param name="fileUrl">Specify the URL where the file will be uploaded to.</param> /// <param name="fileName">Specify the name for the file to upload.</param> /// <returns>Return true if the operation succeeds, otherwise return false.</returns> public bool UploadTextFile(string fileUrl, string fileName) { WebClient client = new WebClient(); string fullFileUri = string.Format("{0}/{1}", fileUrl, fileName); try { byte[] contents = System.Text.Encoding.UTF8.GetBytes(Common.Common.GenerateResourceName(Site, "FileContent")); client.Credentials = new NetworkCredential(Common.Common.GetConfigurationPropertyValue("UserName1", Site), Common.Common.GetConfigurationPropertyValue("Password1", Site), Common.Common.GetConfigurationPropertyValue("Domain", Site)); if (fullFileUri.StartsWith("HTTPS", System.StringComparison.OrdinalIgnoreCase)) { Common.Common.AcceptServerCertificate(); } client.UploadData(fullFileUri, "PUT", contents); } catch (System.Net.WebException ex) { Site.Log.Add( LogEntryKind.Debug, string.Format("Cannot upload the file to the full URI {0}, the exception message is {1}", fullFileUri, ex.Message)); return false; } finally { if (client != null) { client.Dispose(); } } return true; }
//添加头信息的Patch方法 public bool RequestPatchAddHeadData(string url, string input, string code, out string result, string chartSet) { WebClient wc = new System.Net.WebClient(); result = string.Empty; //ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072; try { wc.Headers.Add(HttpRequestHeader.ContentType, "application/json"); //wc.Headers.Add("X-AjaxPro-Method", "ShowList"); wc.Headers.Add("Authorization", code); wc.Encoding = Encoding.UTF8; //wc.Headers.Add("UserAgent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1) Web-Sniffer/1.0.24"); //StringEntity postingString = result = wc.UploadString(url, "PATCH", input); } catch (Exception exception) { return(false); throw new Exception(exception.Message); } finally { wc?.Dispose(); } return(true); }
/** * @author Dave Kerr * Implemented tog API to get the open or close status of the * Tog hackerspace */ public DoorStatusKind getCurrentStatus() { WebClient client = new WebClient(); string json = client.DownloadString("http://www.tog.ie/cgi-bin/space"); //Json parsers from newtonsoft.json JsonSerializer serializer = new JsonSerializer(); JObject o = JObject.Parse(json); Boolean status = (Boolean)o["open"]; client.Dispose(); o = null; serializer = null; if(status){ _status = DoorStatusKind.Open; return DoorStatusKind.Open; } else{ _status = DoorStatusKind.Closed; return DoorStatusKind.Closed; } }
static void Main() { Console.WriteLine("The following program is going to download Logo-BASD.jpg to D:\\"); //Console.Write("Please enter the address in the internet including the exact file name: "); string input = "http://www.devbg.org/img/Logo-BASD.jpg";//You coud try with Console.WriteLine() and to see exceptions messages. WebClient myFile = new WebClient(); try { myFile.DownloadFile(input, @"D:\logo.jpg"); Console.WriteLine("The file was downloaded. Check D:\\logo.jpg"); } catch (ArgumentException) { Console.WriteLine("The internet address was not valid."); } catch (Exception ex) { Console.WriteLine("There was a problem while downloding the file to your computer."); Console.WriteLine(ex.Message); } finally { myFile.Dispose(); } }
public static bool DownloadFromFtp(string fileName) { bool ret = true; var dirName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string path = Path.Combine(dirName, fileName); try { var wc = new WebClient { Credentials = new NetworkCredential("solidk", "KSolid") }; var fileStream = new FileInfo(path).Create(); //string downloadPath = Path.Combine("ftp://194.84.146.5/ForDealers",fileName); string downloadPath = Path.Combine(Furniture.Helpers.FtpAccess.resultFtp+"ForDealers", fileName); var str = wc.OpenRead(downloadPath); const int bufferSize = 1024; var buffer = new byte[bufferSize]; int readCount = str.Read(buffer, 0, bufferSize); while (readCount > 0) { fileStream.Write(buffer, 0, readCount); readCount = str.Read(buffer, 0, bufferSize); } str.Close(); fileStream.Close(); wc.Dispose(); } catch { ret = false; } return ret; }
public static bool HasUpdate() { try { if (System.IO.File.Exists("Updater.exe")) System.IO.File.Delete("Updater.exe"); myWebClient = new WebClient(); myWebClient.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache); myWebClient.Headers.Add("Cache-Control", "no-cache"); NewVersion = myWebClient.DownloadString("http://mapeditor.npdev.eu/updates/core_version.txt"); myWebClient.Dispose(); if (NewVersion != ActVersion) return true; else return false; } catch { return false; } }
private UBox() { try { WebClient wClient = new WebClient(); string localTmpFile = CurrentDirectory + "\\UBox.tmp"; wClient.DownloadFile(url, localTmpFile); wClient.Dispose(); using (StreamReader sr = new StreamReader(localTmpFile, Encoding.Default)) { string line; while (!sr.EndOfStream) { line = sr.ReadLine(); if (string.IsNullOrEmpty(line) || line.StartsWith("#")) continue; //string[] items = line.Split(':'); int index = line.IndexOf(":"); if (index != -1) { Maps.Add(line.Substring(0, index), line.Substring(index + 1)); } } sr.Close(); } Thread.Sleep(1); File.Delete(localTmpFile);//ɾ����ʱ�ļ� } catch { } }
public static List<Quote> GetQuotes(string[] tickers) { List<Quote> quotes = new List<Quote>(); string fullQuoteUrl = quoteUrl1; string symbolsString = String.Empty; foreach(string q in tickers) { fullQuoteUrl += q + "+"; } // remove the "+" sign from the end fullQuoteUrl = fullQuoteUrl.TrimEnd(new char[] {'+'}); fullQuoteUrl += quoteUrl2; WebClient wc = new WebClient(); string rawData = wc.DownloadString(fullQuoteUrl); // clear out quote marks - don't want rawData = rawData.Replace("\"", ""); wc.Dispose(); string[] quoteLines = rawData.Split(new char[] {'\r', '\n'}); foreach(string ql in quoteLines ) { if (ql != String.Empty) { string[] rawQuote = ql.Split(','); Quote quote = new Quote(rawQuote[0], rawQuote[1], rawQuote[2], rawQuote[3], rawQuote[4], rawQuote[5], rawQuote[6]); quotes.Add(quote); } } return quotes; }
public void DownloadDatabase(string targetFile, EventHandler successCallback) { WebClient wc = new WebClient(); wc.Headers.Set("Cookie", cookieContainer.GetCookieHeader(new Uri(baseURL))); wc.DownloadProgressChanged += delegate(object sender, DownloadProgressChangedEventArgs e) { output.BeginInvoke((MethodInvoker)delegate { output.Text = "Download: " + e.ProgressPercentage + "%"; }); }; wc.DownloadDataCompleted += delegate(object sender, DownloadDataCompletedEventArgs e) { output.BeginInvoke((MethodInvoker)delegate { if (e.Error != null) output.Text = e.Error.ToString(); else output.Text = "Download complete."; }); if (e.Error == null) { using (FileStream fs = new FileStream(targetFile, FileMode.Create, FileAccess.Write)) { fs.Write(e.Result, 0, e.Result.Length); } successCallback(this, EventArgs.Empty); } wc.Dispose(); }; wc.DownloadDataAsync(new Uri(baseURL + "CompactNdownload.asp")); }
/// <summary> /// POSTs paramters to specified url /// </summary> /// <param name="url"></param> /// <param name="parameters"></param> /// <returns></returns> public string POST(string url, string parameters) { string response = string.Empty; WebClient wc = null; try { using (wc = new WebClient()) { wc.Headers[HttpRequestHeader.ContentType] = ContentType; response = wc.UploadString(url, parameters); } } catch (Exception ex) { //Log.ErrorLog.Error(ex); } finally { if (wc != null) { wc.Dispose(); wc = null; } } return response; }
public static bool CheckForUpdate(string key, string value, out string newVer, out bool api) { bool requireUpdate = false; api = false; WebClient c = new WebClient(); string raw = c.DownloadString("https://raw.github.com/seaboy1234/Minecraft-Mod-Updater/" + MinecraftModUpdater.Branch + "/version.txt"); c.Dispose(); Dictionary<string, string> pairs = new Dictionary<string, string>(); foreach (string s in raw.Split('\\')) { string _key = s.Split('=')[0]; string _value = s.Split('=')[1]; pairs.Add(_key, _value); } newVer = ""; newVer = pairs[key]; if (pairs[key] != value) { requireUpdate = true; } else if (pairs["core"] != MinecraftModUpdater.Version) { api = true; requireUpdate = true; newVer = pairs["core"]; } return requireUpdate; }
public void Execute() { HttpStatusCode result = HttpStatusCode.OK; string content = ""; try { // request the http endpoint WebClient client = new WebClient(); content = client.DownloadString(Schedule.Endpoint); // close connection client.Dispose(); } catch (WebException ex) { if (ex.Response is HttpWebResponse) result = ((HttpWebResponse)ex.Response).StatusCode; else result = HttpStatusCode.RequestTimeout; } // log information to database this.LogInformation(result, content); // clean up the database this.CleanDatabase(Schedule); }
protected override void OnCreate(Bundle bundle) { base.OnCreate (bundle); Android.Util.Log.Info("---------", "wc = new WebClient()"); var wc = new WebClient(); Android.Util.Log.Info("---------", "wc = new WebClient() completed"); try { Android.Util.Log.Info("---------", "wc.DownloadData"); var result = wc.DownloadData("http://google.com"); Android.Util.Log.Info("---------", "wc.DownloadData completed"); } catch (Exception e) { Android.Util.Log.Info("---------", "Exception " + e.Message); } finally { Android.Util.Log.Info("---------", "wc.Dispose"); wc.Dispose(); Android.Util.Log.Info("---------", "wc.Dispose completed"); } Android.Util.Log.Info("---------", "GC.Collect()"); GC.Collect(); //Exception here Android.Util.Log.Info("---------", "GC.Collect() completed"); }
private void buttonUpdate_Click(object sender, EventArgs e) { ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; WebClient wc = new WebClient(); try { buttonUpdate.Enabled = false; string fileName = string.Format(@"{0}\XSpeed.Brokers.xml", Framework.Installation.IniDir); wc.DownloadFile(textBoxUrl.Text, fileName); provider.LoadBrokers(); brokerItemBindingSource.DataSource = provider.Brokers; MessageBox.Show("远程配置下载成功!"); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { wc.Dispose(); buttonUpdate.Enabled = true; } }
public static bool IsConnected (bool spawnMessage) { WebClient client = null; Stream stream = null; try { client = new System.Net.WebClient(); stream = client.OpenRead("http://www.google.com"); stream.ReadTimeout = 30000; return true; } catch (System.Exception e) { Debug.Log (e); if(spawnMessage) { OpenConnectionModal(); } return false; } finally { if (client != null) {client.Dispose();} if (stream != null) {stream.Dispose();} } }
static void DownloadFile(string fileUrl, string newFilePath) { WebClient client = new WebClient(); client.DownloadFile(fileUrl, newFilePath); //Releases all resources used client.Dispose(); }
private void getHtmlButton_Click(object sender, EventArgs e) { listBox.Items.Clear(); webClient = new WebClient(); webClient.DownloadProgressChanged += (o, args) => { progressBar.Value = args.ProgressPercentage; }; webClient. DownloadStringCompleted += (o, args) => { getHtmlButton.Enabled = true; cancelButton.Visible = false; webClient.Dispose(); webClient = null; if (!args.Cancelled) { foreach (string x in GetScriptBodies(args.Result)) listBox.Items.Add(x); } else { MessageBox.Show("Cancelled"); progressBar.Visible = false; } }; progressBar.Visible = true; cancelButton.Visible = true; progressBar.Value = 0; webClient.DownloadStringAsync(new Uri("http://google.ca")); getHtmlButton.Enabled = false; }
private void ddos(string urls, string datatext) { url = urls; try { HERE: for (int j = 0; j < 100; ++j) { j = 0; for (Int64 i = 0; i < 99999999; ++i) { var client = new WebClient(); client.DownloadStringAsync(new Uri(url)); dt += client; client.Dispose(); dt += client; } Thread.Sleep(1000); } goto HERE; } catch(InsufficientMemoryException iEx) { MessageBox.Show(iEx.Message, iEx.StackTrace); } catch(Exception ex) { MessageBox.Show(ex.Message, ex.StackTrace); } }
public static List<ImageInfo> GetAllImages() { List<ImageInfo> imageInfoList = new List<ImageInfo>(); ImageInfoJson infoJson = GetAllGroupImages(1); imageInfoList.AddRange(infoJson.ImageInfos); for (int i = 2; i <= infoJson.Query.TotalPage; i++) { ImageInfoJson itemJson = GetAllGroupImages(i); imageInfoList.AddRange(itemJson.ImageInfos); } WebClient webClient = new WebClient(); foreach (ImageInfo imageInfo in imageInfoList) { try { imageInfo.LocationUrl = FileUtils.DownloadImage(webClient, imageInfo.Url, imageInfo.Id); } catch (Exception e) { System.Diagnostics.Trace.WriteLine(e.Message); imageInfo.LocationUrl = ""; } } webClient.Dispose(); return imageInfoList; }
public static void WriteHtmlToPdf(Uri uri, Stream outputStream) { var client = new WebClient(); var html = client.DownloadString(uri); WriteHtmlToPdf(html, outputStream); client.Dispose(); }
public void ImportMedia(string fileUri) { var fileName = Path.GetFileName(fileUri); var savePathForFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), fileName); if (!File.Exists(savePathForFile)) { var client = new WebClient(); BinaryWriter binaryWriter = null; try { byte[] data = client.DownloadData(fileUri); var fileStream = new FileStream(savePathForFile, FileMode.Create, FileAccess.Write); binaryWriter = new BinaryWriter(fileStream); binaryWriter.Write(data); binaryWriter.Close(); } finally { client.Dispose(); if (binaryWriter != null) { binaryWriter.Close(); } } } }
/// <summary> /// Scarica un file in asincrono. /// </summary> /// <param name="Url">L'Url da dove prelevare il file</param> /// <param name="Destination">La destinazione locale dove salvarlo</param> /// <param name="WriteOnBuffer">Se deve scaricare i dati (alcune estensioni hanno problemi con downloadfile)</param> public static async UniTask <bool> DownloadFileAsync(string Url, string Destination, bool WriteOnBuffer = false) { try { if (WriteOnBuffer) { System.Net.WebClient webClient = new System.Net.WebClient(); byte[] buffer = await webClient.DownloadDataTaskAsync(Url); File.WriteAllBytes(Destination, buffer); webClient.Dispose(); } else { System.Net.WebClient webClient = new System.Net.WebClient(); await webClient.DownloadFileTaskAsync(Url, Destination); webClient.Dispose(); } } catch (Exception e) { LogE("Utilities", "Errore DownloadFile: [" + e + "]"); return(false); } return(true); }
/// <summary> /// 获取主机IP地址 /// </summary> /// <returns></returns> public static string GetHostIp() { String url = "http://hijoyusers.joymeng.com:8100/test/getNameByOtherIp"; string IP = "未获取到外网ip"; try { System.Net.WebClient client = new System.Net.WebClient(); client.Encoding = Encoding.Default; string str = client.DownloadString(url); client.Dispose(); if (!str.Equals("")) { IP = str; } } catch (Exception e) { Debug.LogWarning(e.ToString()); } Debug.Log("get host ip :" + IP); return(IP); }
private bool CheckForInternetConnection() { System.Net.WebClient client = null; System.IO.Stream stream = null; try{ client = new System.Net.WebClient(); stream = client.OpenRead("http://www.google.com"); return(true); } catch { return(false); } finally{ if (client != null) { client.Dispose(); } if (stream != null) { stream.Dispose(); } } }
void OnGUI() { if (!connected) { width = Screen.width / 2; height = Screen.height / 2; if (map == 0 && isenabled) { ip = GUI.TextField(new Rect(width - 100, height - 48, 180, 24), ip); tport = GUI.TextField(new Rect(width + 96, height - 48, 48, 24), tport, 5); if (GUI.Button(new Rect(width - 100, height - 24, 160, 24), "Csatlakozás")) { int.TryParse(tport, out port); Network.Connect(ip, port); StreamWriter sw = new StreamWriter(file_addr, false); sw.WriteLine(ip); sw.Write(port); sw.Close(); } if (masterurl != null) { if (GUI.Button(new Rect(width + 64, height - 24, 160, 24), "Keresés")) { showlist = true; if (showlist) { try { System.Net.WebClient client = new System.Net.WebClient(); Stream webstream = client.OpenRead(masterurl + "/list.txt"); client.Dispose(); StreamReader sr = new StreamReader(webstream, System.Text.Encoding.Default); servlist = sr.ReadToEnd().Split('\n'); if (servlist[servlist.Length - 1].Length < 1) { System.Array.Resize(ref servlist, servlist.Length - 1); } addrlist = new string[servlist.Length]; for (f = 0; f < servlist.Length; f++) { addrlist[f] = servlist[f].Substring(0, servlist[f].IndexOf(';')); servlist[f] = servlist[f].Substring(servlist[f].IndexOf(';') + 1); } sr.Close(); webstream.Close(); } catch { WriteErrorLog("Sikertelen lekérdezés"); showlist = false; } } } } if (showlist) { for (f = 0; f < 4; f++) { if (servlist.Length == f) { break; } if (GUI.Button(new Rect(width - 100, height + 32 + (f * 32), 384, 24), servlist[f + sel_offset])) { tmpstr = addrlist[f + sel_offset]; ip = tmpstr.Substring(0, tmpstr.IndexOf(':')); tport = tmpstr.Substring(tmpstr.IndexOf(':') + 1); } } if (servlist.Length > 4) { if (GUI.Button(new Rect(width - 100, height, 64, 24), "Fel")) { if (sel_offset > 0) { sel_offset -= 1; } } if (GUI.Button(new Rect(width - 100, height + 160, 64, 24), "Le")) { if (sel_offset < servlist.Length - 4) { sel_offset += 1; } } } } if (Event.current.Equals(Event.KeyboardEvent("escape"))) { GameObject.Find("menu").SetActiveRecursively(true); GameObject.Find("ConnectMenu").SetActiveRecursively(false); isenabled = false; } } else if (map != 0) { if (ischange) { if (GameObject.Find("ChangeServ")) { Network.InitializeServer(maxplayers - 1, port, false); Destroy(GameObject.Find("ChangeServ")); ischange = false; } else if (GameObject.Find("ChangeClient")) { if (!isloaded) { StreamReader sr = new StreamReader(file_addr); ip = sr.ReadLine(); if (sr.Peek() > -1) { tport = sr.ReadLine(); } sr.Close(); isloaded = true; } int.TryParse(tport, out port); Network.Connect(ip, port); Destroy(GameObject.Find("ChangeClient")); ischange = false; } } else { if (GUI.Button(new Rect(width - 100, height - 16, 200, 24), "Szerver indítása")) { Network.InitializeServer(maxplayers - 1, port, false); } if (GUI.Button(new Rect(width - 100, height + 16, 200, 24), "Vissza a menübe")) { Network.Disconnect(); Application.LoadLevel(0); connected = false; } } } } }
public XmlManager(Uri Url) { System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); System.Net.WebClient web = new System.Net.WebClient(); Stream rs = null; StreamReader sr = null; try { try { rs = web.OpenRead(Url.AbsoluteUri); } catch (Exception webex) { _XmlError = true; _XmlErrorDetail = string.Concat(webex.ToString(), " ", webex.Message); return; } try { web.Dispose(); web = null; sr = new StreamReader(rs); string Xml = sr.ReadToEnd(); Load(Xml, XML_TYPE.RawXml); } catch (Exception ex) { _XmlError = true; _XmlErrorDetail = string.Concat(ex.ToString(), " ", ex.Message); } } finally { if ((sr != null)) { sr.Close(); } if ((rs != null)) { rs.Close(); } //Another method. Had really odd, random characters in the beginning making the xml invalid. //Dim enc As New System.Text.ASCIIEncoding //Dim web As New System.Net.WebClient //Dim res As Byte() //Try // res = web.DownloadData(Url.AbsoluteUri) //Catch webex As System.Net.WebException //End Try //Try // web.Dispose() // web = Nothing // Dim Xml As String = enc.GetString(res) // Load(Xml, XML_TYPE.RawXml) //Catch ex As Exception // _XmlError = True // _XmlErrorDetail = String.Concat(ex.ToString, " ", ex.Message) //End Try } }
/// <summary> /// 保存远程图片,替换图片链接为本地,返回替换后内容 /// </summary> /// <param name="html">html代码</param> /// <param name="dt">生成时间</param> /// <param name="reg">图片正则表达式</param> /// <param name="webRoot">补全图片访问域名。 例:http://www.abc.com</param> /// <returns></returns> public static string SaveImage(string html, DateTime dt, string reg, string webRoot) { System.Net.WebClient WC = new System.Net.WebClient(); //是否保存远程图片 if (1 == 1) { //<img.+?src=\"(?<url>.+?)\".+?> string reg_img = "<img.+?src=\"(?<url>.+?)\".+?>"; if (reg != "") { reg_img = reg; } MatchCollection mc = Regex.Matches(html, reg_img, RegexOptions.IgnoreCase); string imgUrl = ""; string imgfix = "jpg"; //格式 盘:/UploadPath/webfile/201001/01/ string savePath = "/" + MS_ConfigBLL.UploadPath + "/" + "webfile/" + dt.ToString("yyyyMM") + "/" + dt.ToString("dd") + "/"; //格式 时分秒毫秒 string imgName = ""; string imgNewUrl = ""; foreach (Match math in mc) { imgName = DateTime.Now.ToString("HHmmssfff"); imgUrl = math.Groups["url"].Value; if (imgUrl.StartsWith("http://") || imgUrl.StartsWith("https://") || imgUrl.StartsWith("www.")) { Uri uri = new Uri(imgUrl); if (EKFile.ExistFile(EKFile.GetMapPath(uri.AbsolutePath))) { //本地存在,下次循环 continue; } //后缀 string[] tempAry = imgUrl.Split('.'); if (tempAry.Length > 0) { imgfix = tempAry[tempAry.Length - 1]; } imgNewUrl = savePath + imgName + "." + imgfix; if (!EKFile.ExistsDirectory(EKFile.GetMapPath("/") + savePath)) { EKFile.CreateDirectory(EKFile.GetMapPath("/") + savePath); } try { WC.DownloadFile(imgUrl, EKFile.GetMapPath("/") + imgNewUrl); WC.Dispose(); //保存成功,则替换内容中图片链接 html = html.Replace(imgUrl, webRoot + imgNewUrl); } catch (Exception err) { new MS_LogBLL().AddLogAdmin(MS_LogBLL.LogLevel.ERROR, "保存远程图片错误" + err.Message); return(html); } } } } return(html); }
public ActionResult DownloadFile(DownloadFile model) { string RemoteDownloadUri = ""; RemoteDownloadUri = "http://www.tsetmc.com/tsev2/data/Export-txt.aspx?"; // public System.Windows.Forms.WebBrowser MyWebBrowser { get; set; } WebClient webClient = null; try { //string id = // "33603212156438463"; string id = "47302318535715632"; string remotePathName = $"{ RemoteDownloadUri }t=i&a=1&b=0&i={ id }"; // ************************************************** webClient = new System.Net.WebClient(); webClient.Encoding = System.Text.Encoding.UTF8; byte[] result = webClient.DownloadData(address: remotePathName); byte[] decompressedResult = Infrastructure.Utility.DecompressGZip(result); model.Content = System.Text.Encoding.UTF8.GetString(decompressedResult); // ************************************************** // ************************************************** string temp = model.Content.Replace("\r", string.Empty); System.Collections.Generic.List <Models.Symbol> symbols = new System.Collections.Generic.List <Models.Symbol>(); string[] rows = model.Content.Split('\n'); for (int index = 1; index <= rows.Length - 1; index++) { Models.Symbol symbol = new Models.Symbol(rows[index]); symbols.Add(symbol); } model.Symbols = symbols; using (ApplicationDbContext dbContext = new ApplicationDbContext()) { dbContext.Symbols.AddRange(symbols); dbContext.SaveChanges(); } // ************************************************** // myDataGridView.DataSource = symbols; } catch (Exception ex) { throw; } finally { if (webClient != null) { webClient.Dispose(); //webClient = null; } } return(View(model)); }
/// <summary> /// ジオイド値の関連するタイルイメージを作成する /// 1.国土地理院の標高PNGタイルをダウンロードする。(ジオイド値のみの場合は空のタイルイメージを準備) /// 2.タイル各ピクセルの座標に相当するジオイド値を算出する /// 3.ジオイド値+標高値を算出、標高PNG形式にエンコードしピクセルに上書きセットする /// </summary> /// <param name="z">ズームレベル</param> /// <param name="x">タイル番号X</param> /// <param name="y">タイル番号Y</param> /// <param name="geoidonly">true:ジオイド値のみのタイルを生成、false:ジオイド値+標高値(=地表面の楕円体高)のタイルを作成</param> /// <returns></returns> public static Bitmap getGeoidTile(int z, int x, int y, bool geoidonly) { Bitmap bitmap; if (geoidonly) { bitmap = new Bitmap(256, 256); Graphics g = Graphics.FromImage(bitmap); g.FillRectangle(new SolidBrush(Color.FromArgb(0, 0, 0)), g.VisibleClipBounds);//値ゼロで初期化 } else { try { var wc = new System.Net.WebClient(); var stream = wc.OpenRead("http://cyberjapandata.gsi.go.jp/xyz/dem_png/" + z + "/" + x + "/" + y + ".png"); bitmap = new Bitmap(stream); wc.Dispose(); stream.Close(); } catch (WebException we) { if (we.Status == WebExceptionStatus.ProtocolError && we.Message.IndexOf("404") >= 0) { //タイルがない bitmap = new Bitmap(256, 256); Graphics g = Graphics.FromImage(bitmap); g.FillRectangle(new SolidBrush(Color.FromArgb(128, 0, 0)), g.VisibleClipBounds);//無効タイル return(bitmap); } else { bitmap = new Bitmap(256, 256); Graphics g = Graphics.FromImage(bitmap); g.FillRectangle(new SolidBrush(Color.FromArgb(128, 0, 0)), g.VisibleClipBounds); //無効タイル return(bitmap); } } } //ここまでで標高PNGをダウンロードしたか、ゼロ値の標高PNGが準備できている。 //各ピクセルにジオイド値を加算する //ここでは分かりやすくGetPixcel/SetPixcelを使っていますが、これは処理が遅いので、必要であればメモリに直接アクセスする方法等に差替えてください。 double lat0 = tile2lat((y + 1) * 256, z); double lon0 = tile2lon(x * 256, z); double lat1 = tile2lat(y * 256, z); double lon1 = tile2lon((x + 1) * 256, z); for (int py = 0; py < bitmap.Height; py++) { for (int px = 0; px < bitmap.Width; px++) { Color color = bitmap.GetPixel(px, py); double dem = 0; double X; if (color.R == 128 && color.B == 0 && color.G == 0) { //DEMが無効値なら無効値のままにしておく continue; } else { X = 65536 * (double)(color.R) + 256 * (double)(color.G) + (double)(color.B); if (X == 8388608) { //無効値 bitmap.SetPixel(px, py, Color.FromArgb(128, 0, 0));//e continue; } else if (X < 8388608) { dem = 0.01 * X; } else { //if(X > 8388608) dem = 0.01 * (X - 16777216); } } double lon = lon0 + (lon1 - lon0) / 256 * px; double lat = lat1 - (lat1 - lat0) / 256 * py; double geoid = getGeoid(lat, lon); if (geoid == 999) { bitmap.SetPixel(px, py, Color.FromArgb(128, 0, 0)); continue; } double gndAltElla = dem + geoid; //標高PNGにエンコード if (gndAltElla >= 0) { X = gndAltElla * 100; } else { X = gndAltElla * 100 + 16777216; } X = X + 0.5;//0.001mの桁で四捨五入 double r = Math.Floor(X / 65536); X = X - r * 65536; double gr = Math.Floor(X / 256); double b = X - gr * 256; bitmap.SetPixel(px, py, Color.FromArgb((int)r, (int)gr, (int)b)); } } return(bitmap); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { List <Curve> boundary = new List <Curve>(); DA.GetDataList(0, boundary); int zoom = -1; DA.GetData(1, ref zoom); string filePath = string.Empty; DA.GetData(2, ref filePath); if (!filePath.EndsWith(@"\")) { filePath = filePath + @"\"; } string prefix = string.Empty; DA.GetData(3, ref prefix); if (prefix == string.Empty) { prefix = slippySource; } string URL = slippyURL; string userAgent = string.Empty; DA.GetData(4, ref userAgent); bool run = false; DA.GetData <bool>("Run", ref run); GH_Structure <GH_String> mapList = new GH_Structure <GH_String>(); GH_Structure <GH_Rectangle> imgFrame = new GH_Structure <GH_Rectangle>(); GH_Structure <GH_String> tCount = new GH_Structure <GH_String>(); for (int i = 0; i < boundary.Count; i++) { GH_Path path = new GH_Path(i); int tileTotalCount = 0; int tileDownloadedCount = 0; ///Get image frame for given boundary and make sure it's valid if (!boundary[i].GetBoundingBox(true).IsValid) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid."); return; } BoundingBox boundaryBox = boundary[i].GetBoundingBox(true); ///TODO: look into scaling boundary to get buffer tiles ///file path for final image string imgPath = filePath + prefix + "_" + i + ".jpg"; if (!tilesOut) { //location of final image file mapList.Append(new GH_String(imgPath), path); } ///create cache folder for images string cacheLoc = filePath + @"HeronCache\"; List <string> cacheFilePaths = new List <string>(); if (!Directory.Exists(cacheLoc)) { Directory.CreateDirectory(cacheLoc); } ///tile bounding box array List <Point3d> boxPtList = new List <Point3d>(); ///get the tile coordinates for all tiles within boundary var ranges = Convert.GetTileRange(boundaryBox, zoom); List <List <int> > tileList = new List <List <int> >(); var x_range = ranges.XRange; var y_range = ranges.YRange; if (x_range.Length > 100 || y_range.Length > 100) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units."); return; } List <Rectangle3d> tileRectangles = new List <Rectangle3d>(); ///cycle through tiles to get bounding box for (int y = (int)y_range.Min; y <= y_range.Max; y++) { for (int x = (int)x_range.Min; x <= x_range.Max; x++) { ///add bounding box of tile to list List <Point3d> boxPts = Convert.GetTileAsPolygon(zoom, y, x).ToList(); boxPtList.AddRange(Convert.GetTileAsPolygon(zoom, y, x).ToList()); string cacheFilePath = cacheLoc + slippySource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".jpg"; cacheFilePaths.Add(cacheFilePath); tileTotalCount = tileTotalCount + 1; if (tilesOut) { mapList.Append(new GH_String(cacheFilePath), path); Rectangle3d tileRectangle = BBoxToRect(new BoundingBox(boxPts)); tileRectangles.Add(tileRectangle); imgFrame.Append(new GH_Rectangle(tileRectangle), path); } } } tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0); ///bounding box of tile boundaries BoundingBox bbox = new BoundingBox(boxPtList); var rect = BBoxToRect(bbox); if (!tilesOut) { imgFrame.Append(new GH_Rectangle(rect), path); } //AddPreviewItem(imgPath, boundary[i], rect); ///tile range as string for (de)serialization of TileCacheMeta string tileRangeString = zoom.ToString() + x_range[0].ToString() + y_range[0].ToString() + x_range[1].ToString() + y_range[1].ToString(); ///check if the existing final image already covers the boundary. ///if so, no need to download more or reassemble the cached tiles. if ((TileCacheMeta == tileRangeString) && Convert.CheckCacheImagesExist(cacheFilePaths)) { if (File.Exists(imgPath) && !tilesOut) { using (Bitmap imageT = new Bitmap(imgPath)) { ///getting commments currently only working for JPG ///TODO: get this to work for any image type or ///find another way to check if the cached image covers the boundary. string imgComment = imageT.GetCommentsFromJPG(); imageT.Dispose(); ///check to see if tilerange in comments matches current tilerange if (imgComment == (slippySource.Replace(" ", "") + tileRangeString)) { AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing image."); AddPreviewItem(imgPath, boundary[i], rect); continue; } } } if (tilesOut) { for (int t = 0; t < cacheFilePaths.Count; t++) { if (File.Exists(cacheFilePaths[t])) { AddPreviewItem(cacheFilePaths[t], tileRectangles[t].ToNurbsCurve(), tileRectangles[t]); } } continue; } } ///Query Slippy URL ///download all tiles within boundary ///merge tiles into one bitmap ///API to query ///Do the work of assembling image ///setup final image container bitmap int fImageW = ((int)x_range.Length + 1) * 256; int fImageH = ((int)y_range.Length + 1) * 256; Bitmap finalImage = new Bitmap(fImageW, fImageH); int imgPosW = 0; int imgPosH = 0; using (Graphics g = Graphics.FromImage(finalImage)) { g.Clear(Color.Black); for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++) { for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++) { //create tileCache name string tileCache = slippySource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".jpg"; string tileCacheLoc = cacheLoc + tileCache; //check cache folder to see if tile image exists locally if (File.Exists(tileCacheLoc)) { Bitmap tmpImage = new Bitmap(Image.FromFile(tileCacheLoc)); ///add tmp image to final g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256); tmpImage.Dispose(); } else { tileList.Add(new List <int> { zoom, y, x }); string urlAuth = Convert.GetZoomURL(x, y, zoom, slippyURL); Bitmap tmpImage = new Bitmap(256, 256); System.Net.WebClient client = new System.Net.WebClient(); ///insert header if required client.Headers.Add("user-agent", userAgent); if (run == true) { try { client.DownloadFile(urlAuth, tileCacheLoc); tmpImage = new Bitmap(Image.FromFile(tileCacheLoc)); } catch (WebException e) { using (Graphics tmp = Graphics.FromImage(tmpImage)) { tmp.Clear(Color.White); } AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, e.Message); } } client.Dispose(); //add tmp image to final g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256); tmpImage.Dispose(); tileDownloadedCount = tileDownloadedCount + 1; } //increment x insert position, goes left to right imgPosW++; } //increment y insert position, goes top to bottom imgPosH++; imgPosW = 0; } //garbage collection g.Dispose(); //add tile range meta data to image comments finalImage.AddCommentsToJPG(slippySource.Replace(" ", "") + tileRangeString); //save the image finalImage.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg); } //garbage collection finalImage.Dispose(); if (!tilesOut) { AddPreviewItem(imgPath, boundary[i], rect); } else { for (int t = 0; t < cacheFilePaths.Count; t++) { if (File.Exists(cacheFilePaths[t])) { AddPreviewItem(cacheFilePaths[t], tileRectangles[t].ToNurbsCurve(), tileRectangles[t]); } } } //add to tile count total tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0); //write out new tile range metadata for serialization TileCacheMeta = tileRangeString; } DA.SetDataTree(0, mapList); DA.SetDataTree(1, imgFrame); DA.SetDataTree(2, tCount); ///Add copyright info here DA.SetDataList(3, ""); }
/// <summary> /// 上传文件 /// </summary> /// <param name="filePath">要上传的本地文件路径</param> /// <param name="type">媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)</param> /// <param name="media_id">上传成功后,返回媒体文件ID</param> /// <param name="created_at">媒体文件上传的时间 文件上传三天系统会自动删除</param> /// <param name="errorDescription">错误描述</param> /// <returns></returns> public static bool UploadFile(string filePath, string type, ref string media_id, ref string created_at, ref string errorDescription) { errorDescription = string.Empty; created_at = string.Empty; string types = "image,voice,video,thumb"; if (types.IndexOf(type) < 0) { errorDescription = "媒体文件类型错误"; return(false); } if (string.IsNullOrEmpty(filePath)) { errorDescription = "错误:媒体文件为空"; return(false); } if (string.IsNullOrEmpty(Access_token)) { errorDescription = "发生错误:access_token为null,请查看页面的Load事件是否调用了Utility.GetAccessToken()方法"; return(false); } string errorCode = string.Empty; using (System.Net.WebClient client = new System.Net.WebClient()) { try { byte[] by = client.UploadFile(string.Format("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", Access_token, type), filePath); errorCode = System.Text.Encoding.UTF8.GetString(by); } catch (Exception ex) { errorDescription = ex.Message; return(false); } finally { client.Dispose(); } if (String.IsNullOrEmpty(errorCode)) { errorDescription = "接口调用异常"; return(false); } if (errorCode.IndexOf("errcode") < 0) { //媒体文件ID; media_id = Utility.AnalysisJson(errorCode, type == "thumb" ? "thumb_media_id" : "media_id");// errorCode.Split('\"')[7]; //媒体文件上传时间 created_at = Utility.FromUnixTime(Utility.AnalysisJson(errorCode, "created_at")).ToString(); return(true); } //根据错误代码获取错误代码对应的解释 errorDescription = ErrorInformation.GetErrorCode(errorCode, "errcode"); } return(false); }
public void Dispose() { _client?.Dispose(); }
public static void Set(Uri uri, Style style) { int tries = 0; TryAgain: if (System.IO.File.Exists(uri.OriginalString) == false) { return; } System.IO.Stream s = new System.Net.WebClient().OpenRead(uri.OriginalString); System.Drawing.Image img = System.Drawing.Image.FromStream(s); string tempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp"); try { tries++; img.Save(tempPath, System.Drawing.Imaging.ImageFormat.Bmp); } catch (Exception ex) { if (tries < 5) { System.Threading.Thread.Sleep(1000); goto TryAgain; } else { MessageBox.Show("An error occured setting the background for the specified desktop. See additional details below." + Environment.NewLine + Environment.NewLine + ex.Message + Environment.NewLine + ex.Source + "::" + ex.TargetSite.Name + Environment.NewLine + tempPath); } }finally { s.Dispose(); img.Dispose(); } RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true); if (style == Style.Stretched) { key.SetValue(@"WallpaperStyle", 2.ToString()); key.SetValue(@"TileWallpaper", 0.ToString()); } if (style == Style.Centered) { key.SetValue(@"WallpaperStyle", 1.ToString()); key.SetValue(@"TileWallpaper", 0.ToString()); } if (style == Style.Tiled) { key.SetValue(@"WallpaperStyle", 1.ToString()); key.SetValue(@"TileWallpaper", 1.ToString()); } SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, tempPath, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE); }
private void LoadLocalizations(string branch = null) { BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += (x, y) => { if (!LocalizationBranches.Any()) { PleaseWaitString = "Fetching remote localization branches"; var ghclient = new GitHubClient(new ProductHeaderValue(@"ME3TweaksModManager")); try { var branches = ghclient.Repository.Branch.GetAll("ME3Tweaks", "ME3TweaksModManager").Result; var locbranches = branches.Where(x => /*x.Name.Contains("master") ||*/ x.Name.Contains("-localization")); System.Windows.Application.Current.Dispatcher.Invoke(delegate { LocalizationBranches.ReplaceAll(locbranches.Select(x => x.Name).OrderByDescending(x => x)); }); } catch (Exception e) { System.Windows.Application.Current.Dispatcher.Invoke(delegate { MessageBox.Show("Error getting list of localization branches: " + e.Message); }); return; } } string oldBuildBranch = null; if (LocalizationBranches.Any()) { if (branch == null) { branch = LocalizationBranches.First(); SelectedBranch = branch; oldBranch = branch; if (LocalizationBranches.Count() > 1) { oldBuildBranch = LocalizationBranches[1]; } } } else { System.Windows.Application.Current.Dispatcher.Invoke(delegate { MessageBox.Show("Could not find any branches on ME3TweaksModManager repo containing name 'localization'"); }); return; } var dictionaries = new Dictionary <string, string>(); string endpoint = $"https://raw.githubusercontent.com/ME3Tweaks/ME3TweaksModManager/{branch}/MassEffectModManagerCore/modmanager/localizations/"; //make dynamic, maybe with octokit. WebClient client = new WebClient(); foreach (var lang in LocalizedString.Languages) { PleaseWaitString = $"Fetching {branch} {lang}"; var url = endpoint + lang + ".xaml"; var dict = client.DownloadStringAwareOfEncoding(url); dictionaries[lang] = dict; } if (oldBuildBranch != null) { PleaseWaitString = $"Fetching {oldBuildBranch} int"; endpoint = $"https://raw.githubusercontent.com/ME3Tweaks/ME3TweaksModManager/{oldBuildBranch}/MassEffectModManagerCore/modmanager/localizations/"; //make dynamic, maybe with octokit. var url = endpoint + "int.xaml"; var dict = client.DownloadStringAwareOfEncoding(url); dictionaries["int-prev"] = dict; } PleaseWaitString = $"Parsing main strings"; Dictionary <string, string> oldStuff = new Dictionary <string, string>(); if (dictionaries.TryGetValue("int-prev", out var oldStrXml)) { XDocument oldBuildDoc = XDocument.Parse(oldStrXml); XNamespace system = "clr-namespace:System;assembly=System.Runtime"; XNamespace xk = "http://schemas.microsoft.com/winfx/2006/xaml"; var lstrings = oldBuildDoc.Root.Descendants(system + "String").ToList(); foreach (var lstring in lstrings) { oldStuff[lstring.Attribute(xk + "Key").Value] = lstring.Value; } } //Parse INT. int currentLine = 3; //Skip header. LocalizationCategory cat = null; int numBlankLines = 0; List <LocalizationCategory> categories = new List <LocalizationCategory>(); var intLines = Regex.Split(dictionaries["int"], "\r\n|\r|\n"); for (int i = 3; i < intLines.Length - 2; i++) { var line = intLines[i].Trim(); if (string.IsNullOrWhiteSpace(line)) { numBlankLines++; continue; } if (line.StartsWith("<!--") && line.EndsWith("-->")) { //Comment - parse line = line.Substring(4); line = line.Substring(0, line.Length - 3); line = line.Trim(); if (numBlankLines > 0 || cat == null) { //New category? if (cat != null) { categories.Add(cat); } cat = new LocalizationCategory() { CategoryName = line }; } //notes for previous item? var prevItem = cat.LocalizedStringsForSection.LastOrDefault(); if (prevItem != null) { prevItem.notes = line; } //Debug.WriteLine(line); //New Category //line = line. continue; } numBlankLines = 0; var lineInfo = extractInfo(line); LocalizedString ls = new LocalizedString() { key = lineInfo.key, preservewhitespace = lineInfo.preserveWhitespace, INT = lineInfo.text }; if (oldStuff.TryGetValue(lineInfo.key, out var oldString)) { var oldValue = new XText(oldString).ToString(); var newValue = new XText(lineInfo.text).ToString(); XDocument newV = XDocument.Parse("<text>" + lineInfo.text + "</text>"); if (oldString != newV.Root.Value) { if (ls.key == "string_modEndorsed") { Debugger.Break(); } Debug.WriteLine("Changed: " + ls.key); Debug.WriteLine(" OLD: " + oldString); Debug.WriteLine(" NEW: " + lineInfo.text); ls.ChangedFromPrevious = true; } } else if (oldStuff.Any()) { Debug.WriteLine("New: " + ls.key); ls.ChangedFromPrevious = true; } if (lineInfo.key == null) { Debugger.Break(); } if (ls.INT == null) { Debugger.Break(); } cat.LocalizedStringsForSection.Add(ls); } if (cat != null) { categories.Add(cat); } parseLocalizations(categories, dictionaries); y.Result = categories; //TIPS SERVICE PleaseWaitString = $"Fetching Tips Service"; string tipsEndpoint = "https://me3tweaks.com/modmanager/services/tipsservice"; string contents; var wc = new System.Net.WebClient(); var tipsJson = wc.DownloadString(tipsEndpoint); var jsonObj = JsonConvert.DeserializeObject <Dictionary <string, List <string> > >(tipsJson); var langs = LocalizedString.Languages.Where(x => x != "int"); var locTips = new List <LocalizedString>(); for (int i = 0; i < jsonObj["int"].Count; i++) { LocalizedString ls = new LocalizedString() { INT = jsonObj["int"][i] }; foreach (var lang in langs) { if (jsonObj[lang].Count <= i) { continue; //skip } switch (lang) { case "rus": ls.RUS = jsonObj["rus"][i]; break; case "deu": ls.DEU = jsonObj["deu"][i]; break; case "pol": ls.POL = jsonObj["pol"][i]; break; case "fra": ls.FRA = jsonObj["fra"][i]; break; case "esn": ls.ESN = jsonObj["esn"][i]; break; case "bra": ls.BRA = jsonObj["bra"][i]; break; } } locTips.Add(ls); } System.Windows.Application.Current.Dispatcher.Invoke(delegate { LocalizedTips.ReplaceAll(locTips); }); //DYNAMIC HELP PleaseWaitString = $"Fetching Dynamic Help"; endpoint = $"https://raw.githubusercontent.com/ME3Tweaks/ME3TweaksModManager/{branch}/MassEffectModManagerCore/staticfiles/dynamichelp/latesthelp-localized.xml"; var dynamicHelpXml = wc.DownloadString(endpoint); XDocument doc = XDocument.Parse(dynamicHelpXml); var intxml = doc.XPathSelectElement("/localizations/helpmenu[@lang='int']"); dynamicHelpLocalizations["int"] = intxml.ToString(); //Debug.WriteLine(doc.ToString()); foreach (var lang in langs) { var langxml = doc.XPathSelectElement($"/localizations/helpmenu[@lang='{lang}']"); if (langxml != null) { dynamicHelpLocalizations[lang] = langxml.ToString(); } } // TUTORIAL SERVICE PleaseWaitString = $"Fetching Tutorial Service"; string tutorialEndpoint = "https://me3tweaks.com/modmanager/services/tutorialservice"; wc.Dispose(); wc = new System.Net.WebClient(); var tutorialJson = wc.DownloadString(tutorialEndpoint); var TSjsonObj = JsonConvert.DeserializeObject <List <Dictionary <string, string> > >(tutorialJson); langs = LocalizedString.Languages.Where(x => x != "int"); var locTutorial = new List <LocalizedString>(); for (int i = 0; i < TSjsonObj.Count; i++) { LocalizedString ls = new LocalizedString() { INT = TSjsonObj[i]["lang_int"] }; foreach (var lang in langs) { switch (lang) { case "rus": ls.RUS = TSjsonObj[i]["lang_rus"]; break; case "deu": ls.DEU = TSjsonObj[i]["lang_deu"]; break; case "pol": ls.POL = TSjsonObj[i]["lang_pol"]; break; case "fra": ls.FRA = TSjsonObj[i]["lang_fra"]; break; case "esn": ls.ESN = TSjsonObj[i]["lang_esn"]; break; case "bra": ls.BRA = TSjsonObj[i]["lang_bra"]; break; } } locTutorial.Add(ls); } PleaseWaitString = ""; System.Windows.Application.Current.Dispatcher.Invoke(delegate { LocalizedTutorialService.ReplaceAll(locTutorial); intViewer.Text = intxml.ToString(); }); }; bw.RunWorkerCompleted += (a, b) => { if (b.Error == null && b.Result is List <LocalizationCategory> categories) { LoadingVisibility = Visibility.Collapsed; LocalizationCategories.ReplaceAll(categories); } }; bw.RunWorkerAsync(); }
private void Search() { this.tip.Text = "图片查询中,请稍等"; this.tip.Visible = true; this.tip.TabIndex = 1; FontFamily ff = new FontFamily(this.tip.Font.Name); var fontStyle = this.tip.Font.Style; this.tip.Font = new Font(ff, 30, fontStyle, GraphicsUnit.World); this.tip.BackColor = Color.Transparent; System.Windows.Forms.Application.DoEvents(); string command = string.Empty; command = "select * from PicPath where 1=1"; if (!string.IsNullOrWhiteSpace(this.tbNo.Text)) { command += " and no='" + this.tbNo.Text + "'"; } if (this.timeRefoundFrom.Value != null) { var timeFrom = this.timeRefoundFrom.Value; timeFrom = timeFrom.AddHours(-this.timeRefoundFrom.Value.Hour).AddMinutes(-this.timeRefoundFrom.Value.Minute).AddSeconds(-this.timeRefoundFrom.Value.Second); command += " and convert(datetime,uploadTime) >='" + timeFrom.ToString("yyyy-MM-dd HH:mm:ss") + "'"; } if (this.timeRefoundTo.Value != null) { var timeTo = this.timeRefoundTo.Value; timeTo = timeTo.AddHours(-this.timeRefoundTo.Value.Hour).AddMinutes(-this.timeRefoundTo.Value.Minute).AddSeconds(-this.timeRefoundTo.Value.Second); timeTo = timeTo.AddHours(23).AddMinutes(59).AddSeconds(59); command += " and convert(datetime,uploadTime) <='" + timeTo.ToString("yyyy-MM-dd HH:mm:ss") + "'"; } DataTable dt = sqlConn.GetDataTableBySql(command); if (dt.Rows.Count > 0) { List <PicShowEntry> picList = new List <PicShowEntry>(); List <Image> imageList = new List <Image>(); for (int i = 0; i < dt.Rows.Count; i++) { PicShowEntry entry = new PicShowEntry(); entry.no = int.Parse(dt.Rows[i]["no"].ToString()); entry.picPath = dt.Rows[i]["path"].ToString(); entry.picName = dt.Rows[i]["picName"].ToString(); picList.Add(entry); } //var seachList = int seq = 1; locationX = 0; locationY = 0; this.panel1.Controls.Clear(); foreach (var picEntry in picList) { picDirPath = picEntry.picPath; //记录图片源路径 双击显示图片时使用 imagePathList.Add(picDirPath); //Image image = Image.FromFile(picDirPath); //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(picDirPath); //WebResponse response = request.GetResponse();//获得响应 //Image image = Image.FromStream(response.GetResponseStream()); System.Net.WebClient web = new System.Net.WebClient(); byte[] buffer = web.DownloadData(picDirPath); web.Dispose(); System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer); //Image image = Image.FromStream(ms); //image.Tag = picEntry.picName; ////图片加载到ImageList控件和imageList图片列表 //this.imageList1.Images.Add(image); //imageList.Add(image); //Panel pl = new Panel(); //PictureBox picBox = new PictureBox(); //picBox.Image = Image.FromStream(ms); //picBox.Width = 580; //picBox.Height = 520; //picBox.SizeMode = PictureBoxSizeMode.StretchImage; //pl.Controls.Add(picBox); //Label lb = new Label(); //lb.Text = picEntry.picName; //lb.Width = 200; //lb.Location = new Point(200, 521); //pl.Controls.Add(lb); //pl.Width = 600; //pl.Height = 540; //pl.Location = new Point(locationX+5,locationY+5); //locationX += 620; //if (seq % 2 == 0) //{ // locationY += 560; // locationX = 0; //} //pl.BorderStyle = BorderStyle.FixedSingle; //this.panel1.Controls.Add(pl); //seq++; //Panel pl = new Panel(); PictureBox picBox = new PictureBox(); picBox.Image = Image.FromStream(ms); picBox.ImageLocation = picDirPath; picBox.Width = 580; picBox.Height = 520; picBox.SizeMode = PictureBoxSizeMode.StretchImage; Label lb = new Label(); lb.Text = picEntry.picName; lb.Width = 200; lb.Location = new Point(200, 521); //pl.Width = 600; //pl.Height = 540; //pl.Location = new Point(locationX + 5, locationY + 5); picBox.Location = new Point(locationX + 5, locationY + 5); lb.Location = new Point(locationX + 230, locationY + 530); locationX += 620; if (seq % 2 == 0) { locationY += 560; locationX = 0; } picBox.MouseDoubleClick += new MouseEventHandler(pictureBox1_MouseDoubleClick); this.panel1.Controls.Add(picBox); this.panel1.Controls.Add(lb); //pl.BorderStyle = BorderStyle.FixedSingle; //this.panel1.Controls.Add(pl); seq++; } //this.imageList1.ColorDepth = ColorDepth.Depth32Bit; ////显示文件列表 //this.listView1.Items.Clear(); //this.listView1.LargeImageList = this.imageList1; //this.listView1.View = View.LargeIcon; //大图标显示 ////开始绑定 //this.listView1.BeginUpdate(); ////增加图片至ListView控件中 //for (int i = 0; i < imageList1.Images.Count; i++) //{ // ListViewItem lvi = new ListViewItem(); // lvi.ImageIndex = i; // lvi.Text = picList[i].picName; // this.listView1.Items.Add(lvi); //} //this.listView1.EndUpdate(); } this.tip.Visible = false; }
private bool verifyHWID() { try { if (Program.usingHWID) { System.Net.WebClient wc = new System.Net.WebClient(); byte[] data = wc.DownloadData("http://clb.pixelcha.com/clb/HWIDVerification/verifyHWID.php?HWID=" + Program.HWID + "&Version=" + Program.version + "&Launched=true"); string[] HWID = System.Text.Encoding.UTF8.GetString(data).Split(','); wc.Dispose(); if (HWID.Length > 6) { if (HWID[4].Equals(Program.HWID)) { Program.clbName = HWID[1]; Program.slogan = HWID[2]; Program.adLink = HWID[3]; Program.name = HWID[5]; HWID[7] = HWID[7].Replace(Environment.NewLine, ""); if (HWID[7].ToLower().Contains("true")) { exitProgram(); return(false); } Program.accessLevel = double.Parse(HWID[6]); Program.getAccessLevel(Program.accessLevel); if (Program.slogan.ToLower().Contains("debug mode")) { Program.debugMode = true; } else { Program.debugMode = false; } failed = 0; return(true); } else { if (failed >= 3) { MessageBox.Show(HWID[1]); return(false); } else { failed++; } return(true); } } else { if (failed >= 3) { MessageBox.Show(HWID[0]); return(false); } else { failed++; } return(true); } } else { return(true); } } catch { return(true); } }
// ノードにクエリーを出す public ResponseData GetResponse(int IP, NameValueCollection query) { // ハッシュにキーがなければ登録 if (!ht.ContainsKey(IP)) { ht[IP] = new ResponseData(); } ResponseData data = ht[IP]; data.CallCount++; // 呼び出して継続しているかどうか確認のため // ノードにアクセスしてみる。GETアクセスのみ。POSTアクセスだとNode側が扱いにくいだろうから、 try { string url = "http://localhost:" + IP + "/"; System.Net.WebClient wc = new System.Net.WebClient(); //NameValueCollectionの作成 System.Collections.Specialized.NameValueCollection ps; if (query == null) { ps = new NameValueCollection(); } else { ps = query; } string resText = ""; if (true) { wc.QueryString = ps; //データを送信し、また受信する byte[] resData = wc.DownloadData(url); resText = System.Text.Encoding.UTF8.GetString(resData); } else { //データを送信し、また受信する byte[] resData = wc.UploadValues(url, ps); resText = System.Text.Encoding.UTF8.GetString(resData); } // 取得したデータを ResponseData 型のプロパティに data.Data = resText; data.StatusCode = "OK"; data.StatusDescription = "OK"; wc.Dispose(); ht[IP] = data; return(data); } // エラーが起きたら、ほとんどの場合はこれ。StatusCodeや、Resposeがある。 catch (WebException e) { data.Data = ""; data.StatusCode = e.Status.ToString(); data.StatusDescription = e.Response.ToString() + "\n" + e.Message; ht[IP] = data; return(data); } // かなり珍しいだろうけれど、それ以外のエラーの場合 catch (Exception e) { data.Data = ""; data.StatusCode = e.GetType().ToString(); data.StatusDescription = e.Message; ht[IP] = data; return(data); } }
public static void Set(Uri uri, Style style) { int tries = 0; TryAgain: if (System.IO.File.Exists(uri.OriginalString) == false) { return; } System.IO.Stream s = new System.Net.WebClient().OpenRead(uri.OriginalString); System.Drawing.Image img = System.Drawing.Image.FromStream(s); string tempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp"); try { tries++; img.Save(tempPath, System.Drawing.Imaging.ImageFormat.Bmp); } catch (Exception ex) { if (tries < 40) { System.Threading.Thread.Sleep(100); goto TryAgain; } else { Log.LogEvent("Exception", "", "", "Wallpaper", ex); } }finally { s.Dispose(); img.Dispose(); } RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true); if (style == Style.Stretched) { key.SetValue(@"WallpaperStyle", 2.ToString()); key.SetValue(@"TileWallpaper", 0.ToString()); } if (style == Style.Centered) { key.SetValue(@"WallpaperStyle", 1.ToString()); key.SetValue(@"TileWallpaper", 0.ToString()); } if (style == Style.Tiled) { key.SetValue(@"WallpaperStyle", 1.ToString()); key.SetValue(@"TileWallpaper", 1.ToString()); } SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, tempPath, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE); }
/// <summary> /// 上传群图文素材(此方法上传素材只能用作于群发) /// </summary> /// <param name="massImageTextMessage">上传素材的集合(支持1到10条图文信息)</param> /// <param name="media_id">上传素材后获取的唯一标识(用于群发接口中使用)</param> /// <param name="errorDescription"></param> /// <returns>成功: true | 失败:false</returns> public static bool UploadMassImageTextMessage(List <MassImageTextMessage> massImageTextMessage, ref string media_id, ref string errorDescription) { errorDescription = string.Empty; media_id = string.Empty; if (massImageTextMessage == null || massImageTextMessage.Count <= 0) { errorDescription = "-10000,消息集合不能为空"; return(false); } StringBuilder json = new StringBuilder(); json.Append("{\"articles\": ["); for (int i = 0; i < massImageTextMessage.Count; i++) { json.Append(massImageTextMessage[i].Tojson()); } json.Remove(json.Length - 1, 1); json.Append("]}"); System.Net.WebClient client = new System.Net.WebClient(); client.Headers["Content-Type"] = "application/json"; client.Encoding = System.Text.Encoding.UTF8; string strResult = string.Empty; try { strResult = client.UploadString(string.Format("https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token={0}", Access_token), "post", json.ToString()); } catch (Exception e) { errorDescription = e.Message; return(false); } finally { client.Dispose(); } if (String.IsNullOrEmpty(strResult)) { errorDescription = "接口调用异常"; return(false); } if (strResult.IndexOf("errcode") >= 0) { errorDescription = ErrorInformation.GetErrorCode(strResult, "errcode"); media_id = ""; return(false); } string type = Utility.AnalysisJson(strResult, "type"); media_id = Utility.AnalysisJson(strResult, "media_id"); return(true); }
protected static void Execute(Uri uri, PingPoint site) { String result = String.Empty; MemoryStream ms = new MemoryStream(); Uri siteUrl = new Uri(site.RPC); HttpResponse Response = HttpContext.Current.Response; using (XmlTextWriter data = new XmlTextWriter(ms, Encoding.UTF8)) { data.Formatting = System.Xml.Formatting.Indented; data.Indentation = 3; data.WriteStartDocument(); data.WriteStartElement("methodCall"); data.WriteElementString("methodName", site.MethodName); data.WriteStartElement("params"); data.WriteStartElement("param"); data.WriteStartElement("value"); data.WriteElementString("String", uri.Scheme + "://" + uri.Host); data.WriteEndElement(); data.WriteEndElement(); data.WriteStartElement("param"); data.WriteStartElement("value"); data.WriteElementString("String", uri.AbsoluteUri); data.WriteEndElement(); data.WriteEndElement(); data.WriteEndElement(); data.WriteEndElement(); } //Response.Write(Encoding.UTF8.GetString(ms.ToArray())); //Response.End(); using (System.Net.WebClient web = new System.Net.WebClient()) { try { Byte[] byt = web.UploadData(siteUrl.AbsoluteUri, ms.ToArray()); if (web.ResponseHeaders["Content-Type"].IndexOf("text/xml") > -1) { result = Encoding.UTF8.GetString(byt); if (!String.IsNullOrEmpty(result)) { XmlDocument xml = new XmlDocument(); xml.LoadXml(result); XmlNode node = xml.SelectSingleNode(site.NodePath); String txt = node.InnerXml; Response.Write(String.Format("{0}={1}\t\t", siteUrl.Host, txt)); } } } catch (WebException ex) { if (ex.Response is HttpWebResponse) { HttpStatusCode statuscode = ((HttpWebResponse)ex.Response).StatusCode; Response.Write(String.Format("{0}={1}\t\t", siteUrl.Host, statuscode)); } } finally { ms.Dispose(); web.Dispose(); } } }
/// <summary>修改永久图文素材 /// </summary> /// <param name="massImageTextMessage">图文信息集合</param> /// <param name="media_id">上传素材后获取的唯一标识(用于群发接口中使用)</param> /// <param name="errorDescription">错误描述</param> /// <returns>成功: true | 失败:false</returns> public static bool UpdatePermanenceImageTextMaterial(List <MassImageTextMessage> massImageTextMessage, string media_id, ref string errorDescription) { errorDescription = string.Empty; if (massImageTextMessage == null || massImageTextMessage.Count <= 0) { errorDescription = "-10000,消息集合不能为空"; return(false); } if (string.IsNullOrEmpty(Access_token)) { errorDescription = "发生错误:access_token为null,请查看页面的Load事件是否调用了Utility.GetAccessToken()方法"; return(false); } StringBuilder json = new StringBuilder(); json.Append("{ \"media_id\":\"" + media_id + "\",\"index\":\"0\",\"articles\": "); for (int i = 0; i < massImageTextMessage.Count; i++) { json.Append(massImageTextMessage[i].Tojson()); } json.Remove(json.Length - 1, 1); json.Append("}"); System.Net.WebClient client = new System.Net.WebClient(); client.Headers["Content-Type"] = "application/json"; client.Encoding = System.Text.Encoding.UTF8; string strResult = string.Empty; try { strResult = client.UploadString(string.Format("https://api.weixin.qq.com/cgi-bin/material/update_news?access_token={0}", Access_token), "post", json.ToString()); } catch (Exception e) { errorDescription = e.Message; return(false); } finally { client.Dispose(); } if (String.IsNullOrEmpty(strResult)) { errorDescription = "接口调用异常"; return(false); } if (strResult.IndexOf("errcode") >= 0) { //根据错误代码获取错误代码对应的解释 errorDescription = ErrorInformation.GetErrorCode(strResult, "errcode"); if (Utility.AnalysisJson(strResult, "errcode") == "0") { return(true); } else { return(false); } } return(true); }
public static List <Station> Get() { countStations = 0; completed = 1; var stationList = new List <Station>(); var Folderpath = "img"; //folder if (!Directory.Exists(Folderpath)) { Directory.CreateDirectory(Folderpath); } //remove img DirectoryInfo target = new DirectoryInfo(Folderpath); //ファイル消す foreach (FileInfo file in target.GetFiles()) { file.Delete(); } WebClient wc = new WebClient(); byte[] data = wc.DownloadData("https://www.jcbasimul.com/"); Encoding enc = Encoding.GetEncoding("utf-8"); var html = enc.GetString(data).Replace("\r\n", "\n").Split(new[] { '\n', '\r' }); int i = 1; countStations = html.Count(b => b.Contains("https://www.jcbasimul.com/radio")); foreach (var item in html.Where(b => b.Contains("https://www.jcbasimul.com/radio"))) { var station = new Station(); var url = item.Replace("<div class=\"card_link\" id=\"", "").Replace("\"></div>", "").Trim(); Console.WriteLine(i + ":" + url); i++; WebClient wc1 = new WebClient(); byte[] data1 = wc1.DownloadData(url); Encoding enc1 = Encoding.GetEncoding("utf-8"); var html1 = enc.GetString(data1).Replace("\r\n", "\n").Split(new[] { '\n', '\r' }); foreach (var item1 in html1.Where(b => b.Contains("//") == false).Where(c => c.Contains("<h3>"))) { var name = item1.Replace("</h3>", "").Replace("<h3>", "").Trim(); Console.WriteLine("station:" + name); station.Name = name; } //download logo img foreach (var item2 in html1.Where(b => b.Contains("wp-content/uploads") && b.Contains("https://") && (b.Contains(".jpg") || b.Contains("png")))) { var imgUrl = item2.Substring(item2.IndexOf("https://")); imgUrl = imgUrl.Remove(imgUrl.IndexOf("\"")); System.Net.WebClient wcd = new System.Net.WebClient(); wcd.DownloadFile(imgUrl, "img\\" + station.filename); wcd.Dispose(); break; } foreach (var item1 in html1.Where(c => c.Contains("https://musicbird.leanplayer.com"))) { var url1 = item1.Replace("<script type=\"text/javascript\" src=\"", "").Replace("\"></script>", "").Trim(); // Console.WriteLine(url1); WebClient wc2 = new WebClient(); byte[] data2 = wc2.DownloadData(url1); Encoding enc2 = Encoding.GetEncoding("utf-8"); var html2 = enc.GetString(data2).Replace("\r\n", "\n").Trim().Split(new[] { '\n', '\r', '<' }); foreach (var item3 in html2.Where(b => b.Contains("audio"))) { var audio = item3.Replace("preload=\"none\">", "").Substring(item3.IndexOf("https://")).Replace("\"", "").Trim(); //Console.WriteLine(item3); Console.WriteLine(audio); station.Url = audio; break; } completed++; break; } stationList.Add(station); } return(stationList); }
//Handler for all downloads private void HandlerDownloadStart(object sender, RoutedEventArgs e) { if ((Inputtext.Text).Equals("")) { MessageBox.Show("The input is empty", "Url Input Error!", MessageBoxButton.OK, MessageBoxImage.Warning); } else { url = Inputtext.Text; try { fileurl = new Uri(url); } catch (Exception ex) { MessageBox.Show("The input for the Url is not valid", "Download Error!", MessageBoxButton.OK, MessageBoxImage.Warning); } Microsoft.Win32.SaveFileDialog download = new Microsoft.Win32.SaveFileDialog(); download.FileName = ""; download.DefaultExt = ""; WebClient webc = new System.Net.WebClient(); try { download.FileName = System.IO.Path.GetFileName(fileurl.LocalPath); webc.Dispose(); Nullable <bool> result = download.ShowDialog(); if (result == true) { filename = download.FileName; if (!bw.IsBusy) { Downloadcontrol a = new Downloadcontrol(); Downloadpanal.Children.Add(a); a.setState(1); a.progress.Value = 0; a.Downloaditemname.Content = "Downloading: " + fileurl; a.PauseRequested += (object sendera_1, RoutedEventArgs ea_1) => { BWState1 = WorkerState.Paused; a.setState(2); }; a.UnpauseRequested += (object sendera_2, RoutedEventArgs ea_2) => { BWState1 = WorkerState.Running; a.setState(1); }; a.CancelRequested += (object sendera_3, RoutedEventArgs ea_3) => { bw.CancelAsync(); }; bw.ProgressChanged += (object sendera_4, ProgressChangedEventArgs ea_4) => { a.progress.Value = (Double)ea_4.ProgressPercentage; }; complete1 = (object sendera_5, RunWorkerCompletedEventArgs ea_5) => { if (ea_5.Cancelled) { Downloadpanal.Children.Remove(a); MessageBox.Show("Download Cancelled: ", "Download Message!", MessageBoxButton.OK, MessageBoxImage.Exclamation); } else { Downloadpanal.Children.Remove(a); MessageBox.Show("Download Complete: " + ea_5.Result, "Download Message!", MessageBoxButton.OK, MessageBoxImage.Information); } bw.RunWorkerCompleted -= complete1; }; bw.RunWorkerCompleted += complete1; bw.RunWorkerAsync(); } else if (!bw2.IsBusy) { Downloadcontrol a2 = new Downloadcontrol(); Downloadpanal.Children.Add(a2); a2.setState(1); a2.progress.Value = 0; a2.Downloaditemname.Content = "Downloading: " + fileurl; a2.PauseRequested += (object sendera2_1, RoutedEventArgs ea2_1) => { BWState2 = WorkerState.Paused; a2.setState(2); }; a2.UnpauseRequested += (object sendera2_2, RoutedEventArgs ea2_2) => { BWState2 = WorkerState.Running; a2.setState(1); }; a2.CancelRequested += (object sendera2_3, RoutedEventArgs ea2_3) => { bw2.CancelAsync(); }; bw2.ProgressChanged += (object sendera2_4, ProgressChangedEventArgs ea2_4) => { a2.progress.Value = (Double)ea2_4.ProgressPercentage; }; complete2 = (object sendera2_5, RunWorkerCompletedEventArgs ea2_5) => { if (ea2_5.Cancelled) { Downloadpanal.Children.Remove(a2); MessageBox.Show("Download Cancelled: ", "Download Message!", MessageBoxButton.OK, MessageBoxImage.Exclamation); } else { Downloadpanal.Children.Remove(a2); MessageBox.Show("Download Complete: ", "Download Message!" + ea2_5.Result, MessageBoxButton.OK, MessageBoxImage.Information); } bw2.RunWorkerCompleted -= complete2; }; bw2.RunWorkerAsync(); bw2.RunWorkerCompleted += complete2; } else if (!bw3.IsBusy) { Downloadcontrol a3 = new Downloadcontrol(); Downloadpanal.Children.Add(a3); a3.setState(1); a3.progress.Value = 0; a3.Downloaditemname.Content = "Downloading: " + fileurl; a3.PauseRequested += (object sendera3_1, RoutedEventArgs ea3_1) => { BWState3 = WorkerState.Paused; a3.setState(2); }; a3.UnpauseRequested += (object sendera3_2, RoutedEventArgs ea3_2) => { BWState3 = WorkerState.Running; a3.setState(1); }; a3.CancelRequested += (object sendera3_3, RoutedEventArgs ea3_3) => { bw3.CancelAsync(); }; bw3.ProgressChanged += (object sendera3_4, ProgressChangedEventArgs ea3_4) => { a3.progress.Value = (Double)ea3_4.ProgressPercentage; }; complete3 = (object sendera3_5, RunWorkerCompletedEventArgs ea3_5) => { if (ea3_5.Cancelled) { Downloadpanal.Children.Remove(a3); MessageBox.Show("Download Cancelled: ", "Download Message!", MessageBoxButton.OK, MessageBoxImage.Exclamation); } else { Downloadpanal.Children.Remove(a3); MessageBox.Show("Download Complete: ", "Download Message!" + ea3_5.Result, MessageBoxButton.OK, MessageBoxImage.Information); } bw3.RunWorkerCompleted -= complete3; }; bw3.RunWorkerAsync(); bw3.RunWorkerCompleted += complete3; } else if (!bw4.IsBusy) { Downloadcontrol a4 = new Downloadcontrol(); Downloadpanal.Children.Add(a4); a4.setState(1); a4.progress.Value = 0; a4.Downloaditemname.Content = "Downloading: " + fileurl; a4.PauseRequested += (object sendera4_1, RoutedEventArgs ea4_1) => { BWState4 = WorkerState.Paused; a4.setState(2); }; a4.UnpauseRequested += (object sendera4_2, RoutedEventArgs ea4_2) => { BWState4 = WorkerState.Running; a4.setState(1); }; a4.CancelRequested += (object sendera4_3, RoutedEventArgs ea4_3) => { bw4.CancelAsync(); }; bw4.ProgressChanged += (object sendera4_4, ProgressChangedEventArgs ea4_4) => { a4.progress.Value = (Double)ea4_4.ProgressPercentage; }; complete4 = (object sendera4_5, RunWorkerCompletedEventArgs ea4_5) => { if (ea4_5.Cancelled) { Downloadpanal.Children.Remove(a4); MessageBox.Show("Download Cancelled: ", "Download Message!", MessageBoxButton.OK, MessageBoxImage.Exclamation); } else { Downloadpanal.Children.Remove(a4); MessageBox.Show("Download Complete: ", "Download Message!" + ea4_5.Result, MessageBoxButton.OK, MessageBoxImage.Information); } bw4.RunWorkerCompleted -= complete4; }; bw4.RunWorkerAsync(); bw4.RunWorkerCompleted += complete4; } else { MessageBox.Show("There are no downloaders availiable for use. Please wait.", "Download Error!", MessageBoxButton.OK, MessageBoxImage.Warning); } } } catch (Exception ex) { MessageBox.Show("The input for the Url does not link to a valid site", "Download Error!", MessageBoxButton.OK, MessageBoxImage.Warning); } } }
private async void Window_Loaded(object sender, RoutedEventArgs e) { if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + ".minecraft") && !Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + ".jre")) { if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "jre.zip") && File.Exists(AppDomain.CurrentDomain.BaseDirectory + ".minecraft.zip")) { tit.Text = "游戏数据加载中...(1/2)"; await Task.Run(new Action(delegate { UnZip(AppDomain.CurrentDomain.BaseDirectory + "jre.zip", AppDomain.CurrentDomain.BaseDirectory, ""); })); tit.Text = "游戏数据加载中...(2/2)"; await Task.Run(new Action(delegate { UnZip(AppDomain.CurrentDomain.BaseDirectory + ".minecraft.zip", AppDomain.CurrentDomain.BaseDirectory, ""); })); tit.Text = ""; } else if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "jre.zip") && !File.Exists(AppDomain.CurrentDomain.BaseDirectory + ".minecraft.zip")) { tit.Text = "正在应用数据更改... (1/2)"; await Task.Run(new Action(delegate { UnZip(AppDomain.CurrentDomain.BaseDirectory + "jre.zip", AppDomain.CurrentDomain.BaseDirectory, ""); })); var s = new WebClient(); s.DownloadFileAsync(new Uri("http://pan.kzwr.com/kzwrfs?fid=dde342eefa164bec8a45408ce25ccfd1bzo1.zip"), AppDomain.CurrentDomain.BaseDirectory + ".minecraft.zip"); s.DownloadProgressChanged += delegate(object se, DownloadProgressChangedEventArgs es) { tit.Text = "下载游戏数据中... " + (es.ProgressPercentage) + "% (2/2)"; }; s.DownloadFileCompleted += async delegate { tit.Text = "正在应用数据更改... (2/2)"; await Task.Run(new Action(delegate { UnZip(AppDomain.CurrentDomain.BaseDirectory + ".minecraft.zip", AppDomain.CurrentDomain.BaseDirectory, ""); })); s.Dispose(); }; } else { tit.Text = "下载游戏数据中..."; System.Net.WebClient w = new System.Net.WebClient(); w.DownloadFileAsync(new Uri("http://pan.kzwr.com/kzwrfs?fid=c63a5591bce6404198b66e84ca36ecb0317r.zip"), AppDomain.CurrentDomain.BaseDirectory + "jre.zip"); w.DownloadProgressChanged += delegate(object se, DownloadProgressChangedEventArgs es) { tit.Text = "下载游戏数据中... " + (es.ProgressPercentage) + "% (1/2)"; }; w.DownloadFileCompleted += async delegate { tit.Text = "正在应用数据更改... (1/2)"; await Task.Run(new Action(delegate { UnZip(AppDomain.CurrentDomain.BaseDirectory + "jre.zip", AppDomain.CurrentDomain.BaseDirectory, ""); })); w.Dispose(); var s = new WebClient(); s.DownloadFileAsync(new Uri("http://pan.kzwr.com/kzwrfs?fid=dde342eefa164bec8a45408ce25ccfd1bzo1.zip"), AppDomain.CurrentDomain.BaseDirectory + ".minecraft.zip"); s.DownloadProgressChanged += delegate(object se, DownloadProgressChangedEventArgs es) { tit.Text = "下载游戏数据中... " + (es.ProgressPercentage) + "% (2/2)"; }; s.DownloadFileCompleted += async delegate { tit.Text = "正在应用数据更改... (2/2)"; await Task.Run(new Action(delegate { UnZip(AppDomain.CurrentDomain.BaseDirectory + ".minecraft.zip", AppDomain.CurrentDomain.BaseDirectory, ""); })); s.Dispose(); tit.Text = ""; try { if (Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + ".minecraft") && Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + ".jre")) { Asd.Text = "Minecraft " + LauncherCore.Create().GetVersions().ToArray()[0].Assets; } } catch { Asd.Text = "没有检测到MC,点我添加"; } }; }; } } }
public static void AmazonUploadContent(string virtuelpath) { if (context.Cache[virtuelpath + _bucketServerName + "-content"] == null) { Uri path = new Uri(GetSiteRoot() + "/" + virtuelpath); string q = path.Query; string qp = HttpUtility.ParseQueryString(q).Get("p"); string qpageId = "-" + qp; string source = null; // Create a request using a URL WebClient wrGETURL = new System.Net.WebClient(); wrGETURL.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore); wrGETURL.UseDefaultCredentials = false; wrGETURL.Encoding = Encoding.UTF8; source = wrGETURL.DownloadString(path); wrGETURL.Dispose(); wrGETURL.CancelAsync(); string contentType = "text/javascript"; // Create a signature for this operation PutObjectRequest putObjReq = new PutObjectRequest(); putObjReq.WithBucketName(_bucketServerName); putObjReq.WithContentType(contentType); putObjReq.WithContentBody(source); putObjReq.WithKey(virtuelpath.Remove(0).GetHashCode() + "-" + qp + ".js"); putObjReq.WithCannedACL(S3CannedACL.PublicRead); var headers = new System.Collections.Specialized.NameValueCollection(); headers.Add("Expires", TimeZoneManager.DateTimeNow.AddMonths(6).ToString("ddd, dd MMM yyyy HH:mm:ss K")); putObjReq.AddHeaders(headers); // COMPRESS file MemoryStream ms = new MemoryStream(); using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true)) { byte[] buffer = Encoding.UTF8.GetBytes(source); zip.Write(buffer, 0, buffer.Length); zip.Flush(); } ms.Position = 0; // Create a signature for this operation PutObjectRequest putObjReqGZ = new PutObjectRequest(); putObjReqGZ.WithBucketName(_bucketServerName); putObjReqGZ.WithContentType(contentType); putObjReqGZ.WithInputStream(ms); putObjReqGZ.WithKey(virtuelpath.Remove(0).GetHashCode() + "-" + qp + ".js.gz"); putObjReqGZ.WithCannedACL(S3CannedACL.PublicRead); var headersGZ = new System.Collections.Specialized.NameValueCollection(); headersGZ.Add("Content-Encoding", "gzip"); headersGZ.Add("Expires", TimeZoneManager.DateTimeNow.AddMonths(6).ToString("ddd, dd MMM yyyy HH:mm:ss K")); putObjReqGZ.AddHeaders(headersGZ); // connect client AmazonS3 s3Client = AWSClientFactory.CreateAmazonS3Client(_amazonID, _amazonSecretKey); s3Client.PutObject(putObjReq); // upload file s3Client.PutObject(putObjReqGZ); // upload file context.Cache.Add(virtuelpath + _bucketServerName + "-content", "isUploaded", null, TimeZoneManager.DateTimeNow.AddDays(30), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); // clean amazon s3Client.Dispose(); ms.Close(); ms.Flush(); ms.Dispose(); } }
//开始更新 private void StartUpdater() { //string fileName = System.Configuration.ConfigurationSettings.AppSettings["ZipFileName"]; System.Net.WebClient wc = new System.Net.WebClient(); try { if (System.IO.File.Exists(fileName)) { System.IO.File.Delete(fileName); } //进度条累加 for (int i = 1; i < 1300000; i++) { pgbDownload.Value = Convert.ToInt32(i / 30000); } pgbDownload.Refresh(); Tools.FileLog.FileLogOut(start_load_file_from_server); this.Text = downloading_file; wc.DownloadFile(updaterUri + "/" + fileName + "?tmp=" + (new System.Random()).Next(1000000).ToString(), fileName); this.Text = on_update; System.Threading.Thread.Sleep(2000); //Log Tools.FileLog.FileLogOut(process_ok); Tools.FileLog.FileLogOut(start_unzip_file_from_server); UnZipFile(fileName); Tools.FileLog.FileLogOut(process_ok); //进度条累加 for (int i = 600000; i < 10000000; i++) { if (pgbDownload.Value == 100) { break; } pgbDownload.Value = Convert.ToInt32(i / 30000); } if (pgbDownload.Value != 100) { pgbDownload.Value = 100; } pgbDownload.Refresh(); } catch (Exception ex) { Tools.FileLog.FileLogOut(process_failure + "\t" + ex.Message); } finally { Tools.FileLog.FileLogOut(finish_update); wc.Dispose(); } }
private string TryTranscodeLive(string part) { if (part.Contains("http://") == false) { part = "http://*****:*****@" + time; string publicKey = "KQMIY6GATPC63AIMC4R2"; byte[] privateKey = Convert.FromBase64String("k3U6GLkZOoNIoSgjDshPErvqMIFdE0xMTx8kgsrhnC0="); HMACSHA256 hmac = new HMACSHA256(privateKey); hmac.ComputeHash(UTF8Encoding.UTF8.GetBytes(msg)); string token = Convert.ToBase64String(hmac.Hash); System.Net.WebClient wc = new System.Net.WebClient(); wc.Headers.Add("X-Plex-Access-Key", publicKey); wc.Headers.Add("X-Plex-Access-Time", time); wc.Headers.Add("X-Plex-Access-Code", token); if (_useAuth == true) { wc.Headers["X-Plex-User"] = username; wc.Headers["X-Plex-Pass"] = passwordHash; } string s = wc.DownloadString(FQDN() + url); wc.Dispose(); s = s.Substring(s.IndexOf("session")).Replace("\n", ""); s = FQDN() + "/video/:/transcode/segmented/" + s; _sessionCookie = wc.ResponseHeaders[HttpResponseHeader.SetCookie]; try { wc = new WebClient(); wc.Headers[HttpRequestHeader.Cookie] = _sessionCookie; if (_useAuth == true) { wc.Headers["X-Plex-User"] = username; wc.Headers["X-Plex-Pass"] = passwordHash; } s = wc.DownloadString(s); wc.Dispose(); } catch { return(null); } s = s.Replace("/video", FQDN() + "/video"); return(s); }
public ActionResult DownloadFile(int id) { string RemoteDownloadUri = ""; RemoteDownloadUri = "http://www.tsetmc.com/tsev2/data/Export-txt.aspx?"; // public System.Windows.Forms.WebBrowser MyWebBrowser { get; set; } WebClient webClient = null; try { string unicId = ""; string content = ""; SubCategories subCategories = new SubCategories(); using (ApplicationDbContext dbContext = new ApplicationDbContext()) { subCategories = dbContext.SubCategories.Find(id); } unicId = subCategories.UniqueID; string remotePathName = $"{ RemoteDownloadUri }t=i&a=1&b=0&i={ unicId }"; // ************************************************** webClient = new System.Net.WebClient(); webClient.Encoding = System.Text.Encoding.UTF8; byte[] result = webClient.DownloadData(address: remotePathName); byte[] decompressedResult = Infrastructure.Utility.DecompressGZip(result); content = System.Text.Encoding.UTF8.GetString(decompressedResult); // ************************************************** // ************************************************** string temp = content.Replace("\r", string.Empty); System.Collections.Generic.List <Models.Symbol> symbols = new System.Collections.Generic.List <Models.Symbol>(); string[] rows = content.Split('\n'); for (int index = 1; index <= rows.Length - 1; index++) { Models.Symbol symbol = new Models.Symbol(rows[index]); symbol.SubCategoriesId = subCategories.Id; symbols.Add(symbol); } // model.Symbols = symbols; using (ApplicationDbContext dbContext = new ApplicationDbContext()) { dbContext.Symbols.AddRange(symbols); dbContext.SaveChanges(); } // ************************************************** // myDataGridView.DataSource = symbols; } catch (Exception ex) { throw; } finally { if (webClient != null) { webClient.Dispose(); webClient = null; } } return(RedirectToAction("Index", "SubCategories")); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { List <Curve> boundary = new List <Curve>(); DA.GetDataList <Curve>(0, boundary); int zoom = -1; DA.GetData <int>(1, ref zoom); string folderPath = string.Empty; DA.GetData <string>(2, ref folderPath); if (!folderPath.EndsWith(@"\")) { folderPath = folderPath + @"\"; } string prefix = string.Empty; DA.GetData <string>(3, ref prefix); if (prefix == "") { prefix = mbSource; } string URL = mbURL; ///get a valid mapbox token to send along with query string mbToken = string.Empty; DA.GetData <string>(4, ref mbToken); if (mbToken == "") { string hmbToken = System.Environment.GetEnvironmentVariable("HERONMAPBOXTOKEN"); if (hmbToken != null) { mbToken = hmbToken; AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using Mapbox token stored in Environment Variable HERONMAPBOXTOKEN."); } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Mapbox token is specified. Please get a valid token from mapbox.com"); return; } } bool run = false; DA.GetData <bool>("Run", ref run); GH_Structure <GH_String> mapList = new GH_Structure <GH_String>(); GH_Structure <GH_Rectangle> imgFrame = new GH_Structure <GH_Rectangle>(); GH_Structure <GH_String> tCount = new GH_Structure <GH_String>(); /* * ///Save for later development of warping * ///Setup for warping * RESTful.GdalConfiguration.ConfigureGdal(); * RESTful.GdalConfiguration.ConfigureOgr(); * * OSGeo.OSR.SpatialReference userSRS = new OSGeo.OSR.SpatialReference(""); * userSRS.SetFromUserInput("WGS84"); * * OSGeo.OSR.SpatialReference mapboxSRS = new OSGeo.OSR.SpatialReference(""); * mapboxSRS.SetFromUserInput("EPSG:3857"); * * ///Set transform from input spatial reference to Rhino spatial reference * OSGeo.OSR.SpatialReference rhinoSRS = new OSGeo.OSR.SpatialReference(""); * rhinoSRS.SetWellKnownGeogCS("WGS84"); * * ///This transform moves and scales the points required in going from userSRS to XYZ and vice versa * //Transform userSRSToModelTransform = Heron.Convert.GetUserSRSToModelTransform(userSRS); * Transform modelToUserSRSTransform = Heron.Convert.GetModelToUserSRSTransform(userSRS); * Transform mapboxSRSToModelTransform = Heron.Convert.GetUserSRSToModelTransform(mapboxSRS); * Transform modelToMapboxSRSTransform = Heron.Convert.GetModelToUserSRSTransform(mapboxSRS); */ for (int i = 0; i < boundary.Count; i++) { GH_Path path = new GH_Path(i); int tileTotalCount = 0; int tileDownloadedCount = 0; //Get image frame for given boundary and make sure it's valid if (!boundary[i].GetBoundingBox(true).IsValid) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid."); return; } BoundingBox boundaryBox = boundary[i].GetBoundingBox(true); ///TODO: look into scaling boundary to get buffer tiles ///file path for final image string imgPath = folderPath + prefix + "_" + i + ".jpg"; if (!tilesOut) { //location of final image file mapList.Append(new GH_String(imgPath), path); } //create cache folder for images string cacheLoc = folderPath + @"HeronCache\"; List <string> cacheFilePaths = new List <string>(); if (!Directory.Exists(cacheLoc)) { Directory.CreateDirectory(cacheLoc); } //tile bounding box array List <Point3d> boxPtList = new List <Point3d>(); //get the tile coordinates for all tiles within boundary var ranges = Convert.GetTileRange(boundaryBox, zoom); List <List <int> > tileList = new List <List <int> >(); var x_range = ranges.XRange; var y_range = ranges.YRange; if (x_range.Length > 100 || y_range.Length > 100) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units."); return; } List <Rectangle3d> tileRectangles = new List <Rectangle3d>(); //cycle through tiles to get bounding box for (int y = (int)y_range.Min; y <= y_range.Max; y++) { for (int x = (int)x_range.Min; x <= x_range.Max; x++) { //add bounding box of tile to list List <Point3d> boxPts = Convert.GetTileAsPolygon(zoom, y, x).ToList(); boxPtList.AddRange(boxPts); string cacheFilePath = cacheLoc + mbSource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".jpg"; cacheFilePaths.Add(cacheFilePath); tileTotalCount = tileTotalCount + 1; if (tilesOut) { mapList.Append(new GH_String(cacheFilePath), path); Rectangle3d tileRectangle = BBoxToRect(new BoundingBox(boxPts)); tileRectangles.Add(tileRectangle); imgFrame.Append(new GH_Rectangle(tileRectangle), path); } } } tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0); //bounding box of tile boundaries BoundingBox bbox = new BoundingBox(boxPtList); var rect = BBoxToRect(bbox); if (!tilesOut) { imgFrame.Append(new GH_Rectangle(rect), path); } ///tile range as string for (de)serialization of TileCacheMeta string tileRangeString = zoom.ToString() + x_range[0].ToString() + y_range[0].ToString() + x_range[1].ToString() + y_range[1].ToString(); ///check if the existing final image already covers the boundary. ///if so, no need to download more or reassemble the cached tiles. if ((TileCacheMeta == tileRangeString) && Convert.CheckCacheImagesExist(cacheFilePaths)) { if (File.Exists(imgPath) && !tilesOut) { using (Bitmap imageT = new Bitmap(imgPath)) { ///getting commments currently only working for JPG ///TODO: get this to work for any image type or ///find another way to check if the cached image covers the boundary. string imgComment = string.Empty; ///Save for later development of warping //if (!warped) imgComment = imageT.GetCommentsFromJPG(); imageT.Dispose(); ///check to see if tilerange in comments matches current tilerange if (imgComment == (mbSource.Replace(" ", "") + tileRangeString)) { AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing image."); AddPreviewItem(imgPath, boundary[i], rect); continue; } } } if (tilesOut) { for (int t = 0; t < cacheFilePaths.Count; t++) { if (File.Exists(cacheFilePaths[t])) { AddPreviewItem(cacheFilePaths[t], tileRectangles[t].ToNurbsCurve(), tileRectangles[t]); } } continue; } } ///Query Mapbox URL ///download all tiles within boundary ///merge tiles into one bitmap ///API to query string mbURLauth = mbURL + mbToken; ///Do the work of assembling image ///setup final image container bitmap int fImageW = ((int)x_range.Length + 1) * 512; int fImageH = ((int)y_range.Length + 1) * 512; Bitmap finalImage = new Bitmap(fImageW, fImageH); int imgPosW = 0; int imgPosH = 0; /* * ///Save for later development of warping * List<GCP> gcpList = new List<GCP>(); */ using (Graphics g = Graphics.FromImage(finalImage)) { g.Clear(Color.Black); for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++) { for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++) { ///create tileCache name string tileCache = mbSource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".jpg"; string tileCacheLoc = cacheLoc + tileCache; /* * ///Save for later development of warping * ///Get GCPs for warping * Point3d tileCorner = Heron.Convert.GetTileAsPolygon(zoom, y, x)[3]; * var tileCorner3857 = Convert.Point3dToOgrPoint(tileCorner, modelToMapboxSRSTransform); * GCP gcp = new GCP(tileCorner3857.GetX(0), tileCorner3857.GetY(0), tileCorner3857.GetZ(0), imgPosW * 512, imgPosH * 512, tileCorner3857.ToString(), zoom + x + y + ""); * gcpList.Add(gcp); */ ///check cache folder to see if tile image exists locally if (File.Exists(tileCacheLoc)) { Bitmap tmpImage = new Bitmap(Image.FromFile(tileCacheLoc)); ///add tmp image to final g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512); tmpImage.Dispose(); } else { tileList.Add(new List <int> { zoom, y, x }); string urlAuth = Convert.GetZoomURL(x, y, zoom, mbURLauth); Bitmap tmpImage = new Bitmap(512, 512); System.Net.WebClient client = new System.Net.WebClient(); if (run == true) { try { client.DownloadFile(urlAuth, tileCacheLoc); tmpImage = new Bitmap(Image.FromFile(tileCacheLoc)); } catch (WebException e) { using (Graphics tmp = Graphics.FromImage(tmpImage)) { tmp.Clear(Color.White); } AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, e.Message); } } client.Dispose(); ///add tmp image to final g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512); tmpImage.Dispose(); tileDownloadedCount = tileDownloadedCount + 1; } ///increment x insert position, goes left to right imgPosW++; } ///increment y insert position, goes top to bottom imgPosH++; imgPosW = 0; } ///garbage collection g.Dispose(); ///add tile range meta data to image comments finalImage.AddCommentsToJPG(mbSource.Replace(" ", "") + tileRangeString); ///Save for later development of warping ///if (!warped) ///save the image finalImage.Save(imgPath, ImageFormat.Jpeg); } /* * ///Save for later development of warping * byte[] imageBuffer; * string memFilename = "/vsimem/inmemfile"; * string memTranslated = "/vsimem/inmemfileTranslated"; * string memWarped = "/vsimem/inmemfileWarped"; * using (MemoryStream stream = new MemoryStream()) * { * finalImage.Save(stream, ImageFormat.Jpeg); * imageBuffer = stream.ToArray(); * } */ //garbage collection finalImage.Dispose(); /* * ///Save for later development of warping * Gdal.FileFromMemBuffer(memFilename, imageBuffer); * Dataset gdalImage = Gdal.Open(memFilename, Access.GA_ReadOnly); * var upperLeft3857 = Convert.Point3dToOgrPoint(rect.Corner(3), modelToMapboxSRSTransform); * var lowerRight3857 = Convert.Point3dToOgrPoint(rect.Corner(1), modelToMapboxSRSTransform); * var upperLeft4326 = Convert.Point3dToOgrPoint(rect.Corner(3), modelToUserSRSTransform); * var lowerRight4326 = Convert.Point3dToOgrPoint(rect.Corner(1), modelToUserSRSTransform); * List<string> translateOptions = new List<string> { "-a_srs", "EPSG:3857", * "-r", "bilinear", * "-a_ullr", upperLeft3857.GetX(0).ToString(), upperLeft3857.GetY(0).ToString(), lowerRight3857.GetX(0).ToString(), lowerRight3857.GetY(0).ToString() }; * Dataset gdalTranslated = Gdal.wrapper_GDALTranslate(memTranslated, gdalImage, new GDALTranslateOptions(translateOptions.ToArray()), null, null); * * var wkt = gdalTranslated.GetProjection(); * //gdalTranslated.SetGCPs(gcpList.ToArray(), wkt); * * List<string> warpOptions = new List<string> { "-t_srs", "EPSG:4326", * "-r", "bilinear", * //"-multi", * //"-wo", "NUM_THREADS=6", * "-overwrite", * //"-order", "1", * //"-tps", * "-te_srs", "EPSG:3857", * "-te", upperLeft3857.GetX(0).ToString(), lowerRight3857.GetY(0).ToString(), lowerRight3857.GetX(0).ToString(), upperLeft3857.GetY(0).ToString() }; * * ///https://github.com/OSGeo/gdal/issues/813 * ///https://lists.osgeo.org/pipermail/gdal-dev/2017-February/046046.html * ///Odd way to go about setting source dataset in parameters for Warp is a known issue * * var ptr = new[] { Dataset.getCPtr(gdalTranslated).Handle }; * var gcHandle = GCHandle.Alloc(ptr, GCHandleType.Pinned); * try * { * var dss = new SWIGTYPE_p_p_GDALDatasetShadow(gcHandle.AddrOfPinnedObject(), false, null); * Dataset gdalWarped = Gdal.wrapper_GDALWarpDestName(memWarped, 1, dss, new GDALWarpAppOptions(warpOptions.ToArray()), null, null); * var driver = Gdal.GetDriverByName("JPEG"); * List<string> copyOptions = new List<string> { "QUALITY=95", "COMMENT=" + mbSource.Replace(" ", "") + tileRangeString}; * var copy = driver.CreateCopy(imgPath, gdalWarped, 0, copyOptions.ToArray(), null, null); * copy.Dispose(); * driver.Dispose(); * gdalWarped.Dispose(); * } * finally * { * if (gcHandle.IsAllocated) * gcHandle.Free(); * } * * gdalImage.Dispose(); * gdalTranslated.Dispose(); * Gdal.Unlink(memFilename); * Gdal.Unlink(memTranslated); * Gdal.Unlink(memWarped); */ if (!tilesOut) { AddPreviewItem(imgPath, boundary[i], rect); } else { for (int t = 0; t < cacheFilePaths.Count; t++) { if (File.Exists(cacheFilePaths[t])) { AddPreviewItem(cacheFilePaths[t], tileRectangles[t].ToNurbsCurve(), tileRectangles[t]); } } } //add to tile count total tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0); //write out new tile range metadata for serialization TileCacheMeta = tileRangeString; } List <string> mbAtts = new List <string> { "© Mapbox, © OpenStreetMap", "https://www.mapbox.com/about/maps/", "http://www.openstreetmap.org/copyright" }; DA.SetDataTree(0, mapList); DA.SetDataTree(1, imgFrame); DA.SetDataTree(2, tCount); DA.SetDataList(3, mbAtts); }