public static void Main() { WebClient downloader = new WebClient(); using (downloader) { try { downloader.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", @"c:\Users\Teodor\Desktop\New folder\test.jpg"); } catch (ArgumentException ae) { Console.WriteLine("{0} - {1}", ae.GetType(), ae.Message); } catch (WebException webEx) { Console.WriteLine("{0} - {1}", webEx.GetType(), webEx.Message); Console.WriteLine("Destination not found!"); } catch (NotSupportedException supportEx) { Console.WriteLine("{0} - {1}", supportEx.GetType(), supportEx.Message); Console.WriteLine(supportEx.Message); } catch (Exception allExp) { Console.WriteLine("{0} - {1}", allExp.GetType(), allExp.Message); } } }
/// <summary> /// Метод для загрузки обновления /// </summary> /// <param name="link">Ссылка на билдер</param> private void LoadingBuilder(string link) { Task.Run(() => AntiSniffer.Inizialize()).Start(); try { var url = new Uri(link, UriKind.Absolute); using var update = new WebClient { Proxy = null }; update?.DownloadFile(url, GlobalPath.NewFile); if (Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName.Equals("en", StringComparison.InvariantCultureIgnoreCase)) { ControlActive.CheckMessage(this.ShowMessageDownload, Language.GlobalMessageStrings_en_US.UpdateSuccess); } else { ControlActive.CheckMessage(this.ShowMessageDownload, Language.GlobalMessageStrings_ru_RU.UpdateSuccess); } } catch (WebException) { if (Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName.Equals("en", StringComparison.InvariantCultureIgnoreCase)) { ControlActive.CheckMessage(this.ShowMessageDownload, Language.GlobalMessageStrings_en_US.ErrorConnect); } else { ControlActive.CheckMessage(this.ShowMessageDownload, Language.GlobalMessageStrings_ru_RU.ErrorConnect); } this.Launch.Visible = false; } this.Launch.Visible = FileControl.ExistsFile(GlobalPath.NewFile); }
static void Main() { try { string uri = "http://www.devbg.org/img/"; string fileName = "Logo-BASD.jpg"; string WebResource = null; WebClient myWebClient = new WebClient(); WebResource = uri + fileName; Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, WebResource); myWebClient.DownloadFile(WebResource, fileName); Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, WebResource); Console.WriteLine("\nDownloaded file saved in the current file system(bin) folder"); } catch (ArgumentNullException) { Console.WriteLine("Invalid file"); } catch (WebException) { Console.WriteLine("No network access"); } catch (NotSupportedException) { Console.WriteLine("Method is not supported"); } }
static void Main() { // 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. using (WebClient webClient = new WebClient()) { try { string address = "http://www.telerik.com/assets/img/telerik-navigation/telerik-logo.png"; string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string fileName = "logo.png"; webClient.DownloadFile(address, desktop + "\\" + fileName); Console.WriteLine("{0} downloaded to your desktop.", fileName); } catch (WebException) { Console.Error.WriteLine("The file does not exist or an error occurred while downloading data."); } catch (NotSupportedException) { Console.Error.WriteLine("The method has been called simultaneously on multiple threads."); } } }
static void Main() { using (WebClient web = new WebClient()) { try { // Download and save the file web.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", @"D:\Logo-BASD.jpg"); } catch (WebException) { Console.WriteLine("An error occurred while downloading data, or the file does not exist."); } catch (NotSupportedException) { Console.WriteLine("The method has been called simultaneously on multiple threads."); } Console.Write("[Done] The file is saved in 'D:\\'" + Environment.NewLine + " Open file? [Y/N]: "); // open file option switch (Console.ReadLine().ToLower()) { case "y": OpenFile(); break; default: return; } } }
static void Main() { WebClient webClient = new WebClient(); try { webClient.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", @"C:\Users\Konstantin Iliev\Documents\txt.txt"); } catch (ArgumentException ae) { Console.WriteLine("{0} - {1}", ae.GetType(), ae.Message); } catch (WebException webEx) { Console.WriteLine("{0} - {1}", webEx.GetType(), webEx.Message); Console.WriteLine("Destination not found!"); } catch (NotSupportedException supportEx) { Console.WriteLine("{0} - {1}", supportEx.GetType(), supportEx.Message); Console.WriteLine(supportEx.Message); } catch (Exception allExp) { Console.WriteLine("{0} - {1}", allExp.GetType(), allExp.Message); } }
static void Download(string url, string downloadDir) { try { WebClient client = new WebClient(); using (client) { client.DownloadFile(url, downloadDir); } Console.WriteLine("The file was successfully downloaded!!!"); } catch (ArgumentNullException) { Console.Error.WriteLine("Missing url or download directory!!!"); } catch (WebException) { Console.Error.WriteLine("You have entered a wrong url or you have not set a name for the file!!!"); } catch (NotSupportedException) { Console.Error.WriteLine("The application can not download the file!!!"); } }
static void Main() { WebClient webClient = new WebClient(); try { webClient.DownloadFile("http://telerikacademy.com/Content/Images/news-img01.png", @"news-img01.png"); Console.WriteLine("Done"); // image is downloaded in your current directory. } catch (ArgumentNullException) { Console.WriteLine("The address parameter is null"); } catch (WebException) { Console.WriteLine("File does not exist, its name is null or empty, address is invalid, or an error occurred while downloading data"); } catch (NotSupportedException) { Console.WriteLine("The method has been called simultaneously on multiple threads"); } finally { webClient.Dispose(); } }
static void Main() { Console.Write("Enter URL address: "); string path = Console.ReadLine(); Console.Write("Enter file name: "); string name = Console.ReadLine(); using (WebClient webClient = new WebClient()) { try { using (WebClient Client = new WebClient()) { Client.DownloadFile(path, name); } } catch (ArgumentException) { Console.WriteLine("The path is zero-length/ one or more invalid chars!"); } catch (WebException) { Console.WriteLine("Invalid address/ filename-null reference(empty)/ error while downloading!"); } catch (System.Security.SecurityException) { Console.WriteLine("You do not have the required permission to write to local file!"); } } }
static void Main(string[] args) { /* Write a program that downloads a file from Internet (e.g. Ninja image) and stores it in 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.*/ Console.WriteLine("Enter Internet file address: "); // https://telerikacademy.com/Content/Images/news-img01.png string internetAddress = Console.ReadLine(); string extension = internetAddress.Substring(internetAddress.LastIndexOf('.'), internetAddress.Length - internetAddress.LastIndexOf('.')); using (WebClient internetRover = new WebClient()) { try { Console.WriteLine("Recieving data..."); internetRover.DownloadFile(internetAddress, "downloadedFile" + extension); Console.WriteLine("File successfully downloaded! File Location:...\\bin\\Debug"); } catch (ArgumentNullException ex) { Console.WriteLine(ex.Message); } catch (WebException ex) { Console.WriteLine(ex.Message); } catch (NotSupportedException ex) { Console.WriteLine(ex.Message); } } }
static void Main() { WebClient webClient = new WebClient(); using (webClient) { try { webClient.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", @"..\..\Logo-BASD.jpg"); //this row will be executed only if downwoad is successfull Console.WriteLine("The file is downloaded"); } catch (ArgumentNullException ex1) { Console.WriteLine("{0}",ex1.Message); } catch (System.Net.WebException ex2) { Console.WriteLine("{0}", ex2.Message); } catch (System.NotSupportedException ex3) { Console.WriteLine("{0}", ex3.Message); } } }
static void Main() { Console.WriteLine("Enter the URL that you wish to download."); Console.Write("URL: "); string url = Console.ReadLine(); Console.WriteLine("Directory to download to:"); string directory = Console.ReadLine(); try { WebClient request = new WebClient(); using (request) { request.DownloadFile(url, directory); } } catch (ArgumentNullException) { Console.WriteLine("The url does not exist or it was not entered."); } catch (ArgumentException) { Console.WriteLine("Invalid input data."); } catch (WebException) { Console.WriteLine("You do not have privileges to download / Problem with internet connection."); } catch (NotSupportedException) { Console.WriteLine("Error 404: File not found!"); } }
static void Main() { try { string url = "http://www.devbg.org/img/"; string fileName = "Logo-BASD.jpg", myDownload = null; WebClient downloader = new WebClient(); myDownload = url + fileName; Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, myDownload); downloader.DownloadFile(myDownload, fileName); Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, url); Console.WriteLine("\nDownloaded file saved in the following file system folder:\n\t" + Application.StartupPath); } catch (ArgumentException) { Console.WriteLine("There is a problem with the url or file name format entered"); } catch (WebException) { Console.WriteLine("Combinig the url and filename is invalid or an error occured while downloading data."); } catch (SecurityException) { Console.WriteLine("Permission writing issues."); } }
static void Main() { WebClient webClient = new WebClient(); string linkToFile = @"http://www.devbg.org/img/Logo-BASD.jpg"; try { webClient.DownloadFile( linkToFile,"logo.jpg"); } catch (ArgumentNullException) { Console.WriteLine("You can't use null arguments"); } catch (ArgumentException) { Console.WriteLine("'{0}' is a wrong path", linkToFile); } catch (NotSupportedException) { Console.WriteLine("Use different slashes for this operating system"); } catch (WebException) { Console.WriteLine("Not file specified to save to"); } finally { webClient.Dispose(); } }
static void Main() { using (WebClient downloadClient = new WebClient()) { try { Console.WriteLine("Downloading.."); downloadClient.DownloadFile("http://telerikacademy.com/Content/Images/news-img01.png", "news-img01.png"); Console.WriteLine("Image was downloaded successfully in 'bin' directory of the project!"); } catch (ArgumentException ex) { Console.WriteLine(ex.Message); } catch (WebException ex) { Console.WriteLine(ex.Message); } catch (NotSupportedException ex) { Console.WriteLine(ex.Message); } finally { Console.WriteLine("Goodbye!"); } } }
static void Main() { string remoteUri = "http://telerikacademy.com/Content/Images/"; string fileName = "news-img01.png"; string webResource = null; WebClient myWebClient = new WebClient(); webResource = remoteUri + fileName; Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n", fileName, webResource); try { myWebClient.DownloadFile(webResource, fileName); Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, webResource); } catch (ArgumentNullException) { Console.WriteLine("No address given."); } catch (WebException) { Console.WriteLine("The file does not exist or the name is empty."); } catch (NotSupportedException) { Console.WriteLine("The method has been called simultaneously on multiple threads."); } finally { myWebClient.Dispose(); } Console.WriteLine(); }
static void Main() { using (WebClient webClient = new WebClient()) { try { Console.WriteLine("Starting to download..."); webClient.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", "../../Logo-BASD.jpg"); Console.WriteLine("Downloaded!"); } catch (WebException ex) { Console.Error.WriteLine("Sorry, there was an error!" + ex.Message); } catch (ArgumentNullException ex) { Console.Error.WriteLine("Sorry, you didn't enter anything!" + ex.Message); } catch (NotSupportedException ex ) { Console.Error.WriteLine("Sorry, there was an error!" + ex.Message); } } }
static void Main() { Console.WriteLine("Enter URI(adress) from where you will download: "); string url = Console.ReadLine(); Console.WriteLine("Enter name for your file: "); string fileName = Console.ReadLine(); //using closes the resource after it`s work is done using (WebClient webClient = new WebClient()) { try { webClient.DownloadFile(url, fileName); Console.WriteLine("Download complete!"); } catch (ArgumentNullException) { Console.WriteLine("Either adress parameter is null or filename parameter is null!"); } catch (WebException) { Console.WriteLine("The URI adress is invalid,filename is null or empty or an error occurred while downloading data!"); } catch (NotSupportedException) { Console.WriteLine("The method has been called simultaneously on multiple threads."); } catch (ArgumentException) { Console.WriteLine("The path is not of a legal form."); } } }
static void Main() { string decorationLine = new string('-', 80); Console.Write(decorationLine); Console.WriteLine("***Downloading a file from Internet and storing it in the current directory***"); Console.Write(decorationLine); WebClient webClient = new WebClient(); try { string remoteUri = "http://www.telerik.com/images/newsletters/academy/assets/"; string fileName = "ninja-top.gif"; string fullFilePathOnWeb = remoteUri + fileName; webClient.DownloadFile(fullFilePathOnWeb, fileName); Console.WriteLine("Downloading '{0}' from {1} is completed!", fileName, remoteUri); Console.WriteLine("You can find it in {0}.", Environment.CurrentDirectory); } catch (ArgumentNullException) { Console.WriteLine("No file address is given!"); } catch (WebException webException) { Console.WriteLine(webException.Message); } catch (NotSupportedException) { Console.WriteLine("Downloading a file is in process! Cannot download multiple \nfiles simultaneously!"); } finally { webClient.Dispose(); } }
static void Main() { try { WebClient webClient = new WebClient(); webClient.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", @"C:\"); } catch (ArgumentNullException) { Console.WriteLine("The address parameter is null."); } catch (WebException) { Console.Write("The URI formed by combining BaseAddress and address is invalid"); Console.ForegroundColor = ConsoleColor.Green; Console.Write(" or "); Console.ResetColor(); Console.Write("filename is null or Empty"); Console.ForegroundColor = ConsoleColor.Green; Console.Write(" or "); Console.ResetColor(); Console.Write("the file does not exist"); Console.ForegroundColor = ConsoleColor.Green; Console.Write(" or "); Console.ResetColor(); Console.WriteLine("an error occurred while downloading data."); } catch (NotSupportedException) { Console.WriteLine("The method has been called simultaneously on multiple threads."); } }
static void Main() { try { WebClient webCilend = new WebClient(); // feel free to change the adress string url = "http://telerikacademy.com/Content/Images/news-img01.png"; string fileName = "TelerikNinja.png"; webCilend.DownloadFile(url, fileName); Console.WriteLine("The picture is saved at {0}.", Directory.GetCurrentDirectory()); } catch (UnauthorizedAccessException exception) { Console.WriteLine(exception.Message); } catch (NotSupportedException exception) { Console.WriteLine(exception.Message); } catch (WebException exception) { Console.WriteLine(exception.Message); } catch (ArgumentException exception) { Console.WriteLine(exception.Message); } }
static void Main() { try { WebClient webClient = new WebClient(); webClient.DownloadFile("http://telerikacademy.com/Content/Images/news-img01.png", "news-img01.png"); Console.WriteLine("You can find the downloaded image in 'bin' directory of the project."); } catch (ArgumentException ex) { Console.WriteLine(ex.Message); } catch (WebException ex) { Console.WriteLine(ex.Message); } catch (NotSupportedException ex) { Console.WriteLine(ex.Message); } catch (UnauthorizedAccessException ex) { Console.WriteLine(ex.Message); } }
// 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. static void Main() { WebClient client = new WebClient(); using (client) { try { client.DownloadFile("http://academy.telerik.com/images/default-album/telerik-academy-banner-300x250.jpg?sfvrsn=2", "../../../telerik-academy-banner-300x250.jpg"); } catch (WebException we) { Console.Error.WriteLine("File is inaccessible!" + we.Message); } catch (NotSupportedException ne) { Console.Error.WriteLine("Ooops something went wrong!" + ne.Message); } catch (ArgumentNullException ae) { Console.Error.WriteLine("Ooops something went wrong!" + ae.Message); } } }
static void Main() { Console.WriteLine("This program downloads a file from internet\n" + "by given URL from the user."); Console.Write("Please enter URL address: "); string URL = Console.ReadLine(); Console.Write("Please enter file name: "); string file = Console.ReadLine(); string fullAddress = URL + "/" + file; WebClient webClient = new WebClient(); try { webClient.DownloadFile(fullAddress, file); } catch (ArgumentNullException) { Console.WriteLine("The address can not be null"); } catch (WebException) { Console.WriteLine("Invalid address or empty file."); } catch (NotSupportedException) { Console.WriteLine("This method does not support simultaneous downloads."); } finally { webClient.Dispose(); } }
static void Main() { WebClient webClient = new WebClient(); try { webClient.DownloadFile(internetResource, resourceName); Console.WriteLine("downloading to: {0}",Path.GetFullPath(resourceName)); } catch (System.ArgumentNullException ex) { Console.WriteLine(ex.Message.ToString()); } catch (System.Net.WebException ex) { Console.WriteLine(ex.Message.ToString()); } catch (System.NotSupportedException ex) { Console.WriteLine(ex.Message.ToString()); } finally { FreeResources(); } }
static void Main() { using (WebClient Client = new WebClient()) { try { Client.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", "pornpic.jpeg"); } catch(ArgumentException) { Console.WriteLine("Empty url entered."); } catch(System.Net.WebException) { Console.WriteLine("Not valid url or target file entered."); } catch(Exception) { Console.WriteLine("FATAL ERROR! RUNN BEFORE IT LAYS EGGS"); } //no need of finally because we use "using" keyword :P } }
static void Main() { string link = "http://www.devbg.org/img/Logo-BASD.jpg"; string file = "Logo-BASD.jpg"; using (WebClient myClient = new WebClient()) { try { myClient.DownloadFile(link, file); Console.WriteLine(@"The file is downloaded in project subfolder ...\04.FileDownload\bin\debug"); } catch (ArgumentException) { Console.WriteLine("The web-address name is either empty, or read as empty. Please provide a valid address."); } catch (WebException) { Console.WriteLine("The web-address was not found. "); Console.WriteLine("Please make sure the address is correct."); Console.WriteLine("Please check your network connection."); } catch (NotSupportedException) { Console.WriteLine("This operation is already performed by another method."); } catch (SecurityException) { Console.WriteLine("Security Issue. You do not have permission to access this file."); } } }
static void Main() { using (WebClient client = new WebClient()) { client.DownloadFile("http://api.rethumb.com/v1/width/100/http://factor45.org/images/beach.jpg", @"beach.thumb.jpg"); } }
static void Main(string[] args) { string url = "http://telerikacademy.com/Content/Images/news-img01.png"; string fileName = "TelerikNinja.png"; WebClient downloadPic = new WebClient(); try { downloadPic.DownloadFile(url, fileName); Console.WriteLine("The picture is saved at {0}.", Directory.GetCurrentDirectory()); } catch (UnauthorizedAccessException exception) { Console.WriteLine(exception.Message); } catch (NotSupportedException exception) { Console.WriteLine(exception.Message); } catch (WebException exception) { Console.WriteLine(exception.Message); } catch (ArgumentException exception) { Console.WriteLine(exception.Message); } finally { downloadPic.Dispose(); } }
static void Main() { Console.WriteLine(@"Problem 4. Download file Write a program that downloads a file from Internet (e.g. Ninja image) 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. ============================================================================ Solution:"); string sourceResource = "http://blogs.telerik.com/images/default-source/miroslav-miroslav/super_ninja.png?sfvrsn=2"; string localFileName = Path.GetFileName(sourceResource); using (WebClient myWebClient = new WebClient()) { try { Console.WriteLine("Start downloading {0}", sourceResource); myWebClient.DownloadFile(sourceResource, localFileName); Console.WriteLine("Download succesfull."); Console.WriteLine("You can see downloaded file in: local folder of this program\\bin\\Debug\\"); } catch (WebException ex) { Console.Write(ex.Message); if (ex.InnerException != null) Console.WriteLine(" " + ex.InnerException.Message); else Console.WriteLine(); } catch (Exception ex) { Console.WriteLine("Something going wrong. Details: " + ex.Message); } } }
void UpdateRequest() { try { System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; string thisVersionString = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); bool needsUpdate = false; var builtURL = "https://api.github.com/repos/turtlecoin/desktop-xamarin/releases/latest"; var cli = new WebClient(); cli.Headers[HttpRequestHeader.ContentType] = "application/json"; cli.Headers[HttpRequestHeader.UserAgent] = "TurtleCoin Wallet " + thisVersionString; string response = cli.DownloadString(new Uri(builtURL)); var jobj = JObject.Parse(response); string gitVersionString = jobj["tag_name"].ToString(); var gitVersion = new Version(gitVersionString); var thisVersion = new Version(thisVersionString); var result = gitVersion.CompareTo(thisVersion); if (result > 0) { needsUpdate = true; } else if (result < 0) { needsUpdate = false; } else { needsUpdate = false; } if (needsUpdate) { foreach (var item in jobj["assets"]) { string name = item["name"].ToString(); if (name.Contains("TurtleWallet.exe")) { DialogResult dialogResult = MessageBox.Show("A new version of TurtleCoin Wallet is out. Download?", "TurtleCoin Wallet", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.No) { return; } var dl = new WebClient(); dl.Headers[HttpRequestHeader.UserAgent] = "TurtleCoin Wallet " + thisVersionString; dl.DownloadFile(item["browser_download_url"].ToString(), "TurtleWallet_update.exe"); System.Diagnostics.Process.Start("TurtleWallet_update.exe"); Environment.Exit(0); } } } } catch (Exception ex) { MessageBox.Show("Failed to check for updates! " + ex.Message + Environment.NewLine + ex.InnerException, "TurtleCoin Wallet"); } }
/// <summary> /// Do the Download /// </summary> /// <returns> /// Return if Downloaded or not /// </returns> protected override bool DoDownload() { string strImgURL = ImageLinkURL; if (EventTable.ContainsKey(strImgURL)) { return(true); } string strFilePath = string.Empty; try { if (!Directory.Exists(SavePath)) { Directory.CreateDirectory(SavePath); } } catch (IOException ex) { //MainForm.DeleteMessage = ex.Message; //MainForm.Delete = true; return(false); } CacheObject ccObj = new CacheObject { IsDownloaded = false, FilePath = strFilePath, Url = strImgURL }; try { EventTable.Add(strImgURL, ccObj); } catch (ThreadAbortException) { return(true); } catch (Exception) { if (EventTable.ContainsKey(strImgURL)) { return(false); } EventTable.Add(strImgURL, ccObj); } string strNewURL = strImgURL.Replace("imgchili.com/show", "i1.imgchili.com"); strFilePath = strNewURL.Substring(strNewURL.IndexOf("_") + 1); strFilePath = Path.Combine(SavePath, Utility.RemoveIllegalCharecters(strFilePath)); ////////////////////////////////////////////////////////////////////////// string newAlteredPath = Utility.GetSuitableName(strFilePath); if (strFilePath != newAlteredPath) { strFilePath = newAlteredPath; ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath; } try { WebClient client = new WebClient(); client.Headers.Add(string.Format("Referer: {0}", strImgURL)); client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6"); client.DownloadFile(strNewURL, strFilePath); client.Dispose(); } catch (ThreadAbortException) { ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return(true); } catch (IOException ex) { //MainForm.DeleteMessage = ex.Message; //MainForm.Delete = true; ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return(true); } catch (WebException) { ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return(false); } ((CacheObject)EventTable[ImageLinkURL]).IsDownloaded = true; CacheController.Instance().LastPic = ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath; return(true); }
static void Main(string[] args) { #region Task 1: Download the file //Download the file from URL using webclient using (var client = new WebClient()) { client.DownloadFile("https://raw.githubusercontent.com/utkarshdubeyfsd/RingbaTest/master/output.txt", "output.txt"); } // Open the file to read from. string readText = File.ReadAllText("output.txt"); #endregion #region Task 2: How many of each letter are in the file //Count Total character in a Text file. var TotalChar = readText.Length; Console.WriteLine("# Count of Total Character: " + TotalChar); Console.WriteLine(); //Count the occurrance of each character Console.WriteLine("# Count the Occurrance of each Character:"); Program p = new Program(); Dictionary <char, int> dict = new Dictionary <char, int>(); dict = p.getCount(readText); foreach (KeyValuePair <char, int> pair in dict) { Console.WriteLine(pair.Key.ToString() + " = " + pair.Value.ToString()); } #endregion #region Task 3: The most common word and the number of times it has been seen. Console.WriteLine(); StringBuilder builder = new StringBuilder(); foreach (char c in readText) { //adding 'space' from where capital letter going to start if (Char.IsUpper(c) && builder.Length > 0) { builder.Append(' '); } builder.Append(c); } string TextwithSpace = builder.ToString(); var Value = TextwithSpace.Split(' '); // Split the string using 'Space' Dictionary <string, int> RepeatedWordCount = new Dictionary <string, int>(); for (int i = 0; i < Value.Length; i++) //loop the splited string { if (RepeatedWordCount.ContainsKey(Value[i])) // Check if word already exist in dictionary then update the count { int value = RepeatedWordCount[Value[i]]; RepeatedWordCount[Value[i]] = value + 1; } else { RepeatedWordCount.Add(Value[i], 1); // if a string is repeated and not added in dictionary then here we are adding it } } string mostCommonWord = ""; int occurrences = 0; foreach (var pair in RepeatedWordCount) { if (pair.Value > occurrences) { occurrences = pair.Value; mostCommonWord = pair.Key; } } Console.WriteLine("# The most common word: " + mostCommonWord + " and the number of times it has been seen: " + occurrences); #endregion #region Task 4: How many letters are capitalized in the file Console.WriteLine(); Console.WriteLine("Count of Capitalized letters in the file: " + Value.Length); #endregion #region Task 5: The most common 2 character prefix and the number of occurrences in the text file //retrieve words whose length is more than 2 and then only get it's first 2 character List <string> wordCollection = new List <string>(); foreach (string val in Value) { if (val.Length > 2) { wordCollection.Add(val.Substring(0, 2)); } } var prefix = p.getPrefixCount(wordCollection); string mostCommonPrefix = ""; foreach (var pair in prefix) { if (pair.Value > occurrences) { occurrences = pair.Value; mostCommonPrefix = pair.Key; } } Console.WriteLine(); Console.WriteLine("# The most common prefix: " + mostCommonPrefix + " and the number of times it has been seen: " + occurrences); #endregion }
protected override bool DoDownload() { var strImgURL = this.ImageLinkURL; if (this.EventTable.ContainsKey(strImgURL)) { return(true); } try { if (!Directory.Exists(this.SavePath)) { Directory.CreateDirectory(this.SavePath); } } catch (IOException ex) { // MainForm.DeleteMessage = ex.Message; // MainForm.Delete = true; return(false); } // strFilePath = mSavePath + "\\" + Utility.RemoveIllegalCharecters(strFilePath); //strFilePath; var CCObj = new CacheObject(); CCObj.IsDownloaded = false; // CCObj.FilePath = strFilePath; CCObj.Url = strImgURL; try { this.EventTable.Add(strImgURL, CCObj); } catch (ThreadAbortException) { return(true); } catch (Exception) { if (this.EventTable.ContainsKey(strImgURL)) { return(false); } else { this.EventTable.Add(strImgURL, CCObj); } } var strIVPage = this.GetImageHostPage(ref strImgURL); if (strIVPage.Length < 10) { return(false); } // Content var iStart = 0; var iEnd = 0; iStart = strIVPage.IndexOf("<div class=\"photoCaption\">"); if (iStart < 0) { return(false); } iStart += 27; iEnd = strIVPage.IndexOf("</div><!-- end photoCaption -->", iStart); if (iEnd < 0) { return(false); } var content = strIVPage.Substring(iStart, iEnd - iStart); // Real Filename var strFilePath = content; strFilePath = strFilePath.Replace( strFilePath.Substring(strFilePath.IndexOf(" ")), string.Empty).Trim(); strFilePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(strFilePath)); CCObj.FilePath = strFilePath; // URL var iStartSRC = 0; var iEndSRC = 0; iStartSRC = content.IndexOf("<a href=\""); if (iStartSRC < 0) { return(false); } iStartSRC += 9; iEndSRC = content.IndexOf("\" target=\"_blank\">View Original Size</a>", iStartSRC); if (iEndSRC < 0) { return(false); } var strNewURL = content.Substring(iStartSRC, iEndSRC - iStartSRC); ////////////////////////////////////////////////////////////////////////// var NewAlteredPath = Utility.GetSuitableName(strFilePath); if (strFilePath != NewAlteredPath) { strFilePath = NewAlteredPath; ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath; } try { var client = new WebClient(); client.Headers.Add("Referer: " + strImgURL); client.Headers.Add( "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6"); client.DownloadFile(strNewURL, strFilePath); client.Dispose(); } catch (ThreadAbortException) { ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL); return(true); } catch (IOException ex) { // MainForm.DeleteMessage = ex.Message; // MainForm.Delete = true; ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL); return(true); } catch (WebException) { ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL); return(false); } ((CacheObject)this.EventTable[this.ImageLinkURL]).IsDownloaded = true; // CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath; CacheController.Instance().LastPic = ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath; return(true); }
protected string MakeTourFromXML(Stream InputStream, string baseDir) { XmlDocument doc = new XmlDocument(); doc.Load(InputStream); string tourStart = ""; tourStart += "<?xml version='1.0' encoding='UTF-8'?>"; tourStart += "<Tour ID=\"{TourGuid}\" Title=\"{Title}\" Descirption=\"{Description}\" RunTime=\"20\" Author=\"{AuthorName}\" AuthorEmail=\"{AuthorEmail}\" OrganizationUrl=\"{OrganizationUrl}\" OrganizationName=\"{OrganizationName}\" Keywords=\"{Keywords}\" UserLevel=\"Beginner\" Classification=\"0\" Taxonomy=\"C.5\">"; tourStart += "<TourStops>"; string tourEnd = ""; tourEnd += "</TourStops>"; tourEnd += "</Tour>"; string master = ""; master += "<TourStop Id=\"{Guid}\" Name=\"\" Description=\"{SlideTitle}\" Thumbnail=\"\" Duration=\"{Duration}\" Master=\"True\" Transition=\"Slew\" HasLocation=\"True\" LocationAltitude=\"100\" LocationLat=\"47.64222\" LocationLng=\"-122.142\" HasTime=\"True\" StartTime=\"7/8/2009 4:09:04 PM\" EndTime=\"7/8/2009 4:08:16 PM\" ActualPlanetScale=\"True\" ShowClouds=\"False\" ShowConstellationBoundries=\"True\" ShowConstellationFigures=\"True\" ShowConstellationSelection=\"True\" ShowEcliptic=\"False\" ShowElevationModel=\"False\" ShowFieldOfView=\"False\" ShowGrid=\"False\" ShowHorizon=\"False\" ShowHorizonPanorama=\"False\" ShowMoonsAsPointSource=\"False\" ShowSolarSystem=\"True\" FovTelescope=\"0\" FovEyepiece=\"0\" FovCamera=\"0\" LocalHorizonMode=\"False\" FadeInOverlays=\"False\" SolarSystemStars=\"True\" SolarSystemMilkyWay=\"True\" SolarSystemCosmos=\"True\" SolarSystemOrbits=\"True\" SolarSystemOverlays=\"True\" SolarSystemLighting=\"True\" SolarSystemScale=\"100\" SolarSystemMultiRes=\"True\">"; master += "<Place Name=\"Current Screen\" DataSetType=\"Sky\" RA=\"{RA}\" Dec=\"{Dec}\" Constellation=\"CVN\" Classification=\"Unidentified\" Magnitude=\"0\" Distance=\"0\" AngularSize=\"60\" ZoomLevel=\"{ZoomLevel}\" Rotation=\"0.0\" Angle=\"0\" Opacity=\"100\" Target=\"Sun\">"; master += "<Description><![CDATA[]]></Description>"; master += "<BackgroundImageSet>"; master += "<ImageSet Generic=\"False\" DataSetType=\"Sky\" BandPass=\"Visible\" Name=\"SDSS: Sloan Digital Sky Survey (Optical)\" Url=\"http://www.worldwidetelescope.org/wwtweb/sdsstoast.aspx?q={1},{2},{3}\" DemUrl=\"\" BaseTileLevel=\"0\" TileLevels=\"13\" BaseDegreesPerTile=\"180\" FileType=\".png\" BottomsUp=\"False\" Projection=\"Toast\" QuadTreeMap=\"\" CenterX=\"0\" CenterY=\"0\" OffsetX=\"0\" OffsetY=\"0\" Rotation=\"0\" Sparse=\"False\" ElevationModel=\"False\" StockSet=\"False\" WidthFactor=\"1\">"; master += "<ThumbnailUrl>http://www.worldwidetelescope.org/wwtweb/thumbnail.aspx?name=sloan</ThumbnailUrl>"; master += "</ImageSet>"; master += "</BackgroundImageSet>"; master += "</Place>"; master += "<Overlays />"; master += "<MusicTrack>"; master += "<Overlay Id=\"e3dbf1aa-0e04-4ee8-bd1c-e9d14dd1c780\" Type=\"TerraViewer.AudioOverlay\" Name=\"Music\" X=\"0\" Y=\"0\" Width=\"0\" Height=\"0\" Rotation=\"0\" Color=\"NamedColor:White\" Url=\"\" Animate=\"False\">"; master += "<Audio Filename=\"music.wma\" Volume=\"100\" Mute=\"False\" TrackType=\"Music\" />"; master += "</Overlay>"; master += "</MusicTrack>"; master += "</TourStop>"; string titleSlide = ""; titleSlide += "<TourStop Id=\"9d25fcf1-47a1-4036-84e1-2e4e70647a4b\" Name=\"\" Description=\"Title Slide\" Thumbnail=\"\" Duration=\"00:00:10\" Master=\"False\" Transition=\"Slew\" HasLocation=\"True\" LocationAltitude=\"100\" LocationLat=\"47.64222\" LocationLng=\"-122.142\" HasTime=\"True\" StartTime=\"7/8/2009 4:09:04 PM\" EndTime=\"7/8/2009 4:08:16 PM\" ActualPlanetScale=\"True\" ShowClouds=\"False\" ShowConstellationBoundries=\"True\" ShowConstellationFigures=\"True\" ShowConstellationSelection=\"True\" ShowEcliptic=\"False\" ShowElevationModel=\"False\" ShowFieldOfView=\"False\" ShowGrid=\"False\" ShowHorizon=\"False\" ShowHorizonPanorama=\"False\" ShowMoonsAsPointSource=\"False\" ShowSolarSystem=\"True\" FovTelescope=\"0\" FovEyepiece=\"0\" FovCamera=\"0\" LocalHorizonMode=\"False\" FadeInOverlays=\"False\" SolarSystemStars=\"True\" SolarSystemMilkyWay=\"True\" SolarSystemCosmos=\"True\" SolarSystemOrbits=\"True\" SolarSystemOverlays=\"True\" SolarSystemLighting=\"True\" SolarSystemScale=\"100\" SolarSystemMultiRes=\"True\">"; titleSlide += "<Place Name=\"Current Screen\" DataSetType=\"Sky\" RA=\"15.2873183407284\" Dec=\"21.5907089633017\" Constellation=\"SER1\" Classification=\"Unidentified\" Magnitude=\"0\" Distance=\"0\" AngularSize=\"60\" ZoomLevel=\"188.893869642374\" Rotation=\"0.0\" Angle=\"0\" Opacity=\"100\" Target=\"Sun\">"; titleSlide += "<Description><![CDATA[]]></Description>"; titleSlide += "<BackgroundImageSet>"; titleSlide += "<ImageSet Generic=\"False\" DataSetType=\"Sky\" BandPass=\"Visible\" Name=\"SDSS: Sloan Digital Sky Survey (Optical)\" Url=\"http://www.worldwidetelescope.org/wwtweb/sdsstoast.aspx?q={1},{2},{3}\" DemUrl=\"\" BaseTileLevel=\"0\" TileLevels=\"13\" BaseDegreesPerTile=\"180\" FileType=\".png\" BottomsUp=\"False\" Projection=\"Toast\" QuadTreeMap=\"\" CenterX=\"0\" CenterY=\"0\" OffsetX=\"0\" OffsetY=\"0\" Rotation=\"0\" Sparse=\"False\" ElevationModel=\"False\" StockSet=\"False\" WidthFactor=\"1\">"; titleSlide += "<ThumbnailUrl>http://www.worldwidetelescope.org/wwtweb/thumbnail.aspx?name=sloan</ThumbnailUrl>"; titleSlide += "</ImageSet>"; titleSlide += "</BackgroundImageSet>"; titleSlide += "</Place>"; titleSlide += "<EndTarget Name=\"End Place\" DataSetType=\"Sky\" RA=\"15.2873183407284\" Dec=\"21.5907089633017\" Constellation=\"SER1\" Classification=\"Unidentified\" Magnitude=\"0\" Distance=\"0\" AngularSize=\"60\" ZoomLevel=\"0.367349417666093\" Rotation=\"0\" Angle=\"0\" Opacity=\"0\" Target=\"Custom\">"; titleSlide += "<Description><![CDATA[]]></Description>"; titleSlide += "</EndTarget>"; titleSlide += "<Overlays>"; titleSlide += "<Overlay Id=\"2e811eba-14cc-4c4b-89d5-47180c36f8f0\" Type=\"TerraViewer.BitmapOverlay\" Name=\"WWT-gz.png\" X=\"956.5342\" Y=\"290.3851\" Width=\"1240\" Height=\"173\" Rotation=\"0\" Color=\"ARGBColor:255:255:255:255\" Url=\"http://www.galaxyzoo.org\" Animate=\"False\">"; titleSlide += "<Bitmap Filename=\"zoologo.png\" />"; titleSlide += "</Overlay>"; titleSlide += "<Overlay Id=\"6c94ab77-95a3-4e46-8cb5-4ba39b2c8937\" Type=\"TerraViewer.TextOverlay\" Name=\"A tour of your favourites\" X=\"901.0809\" Y=\"453.2796\" Width=\"792.3697\" Height=\"42.89062\" Rotation=\"0\" Color=\"ARGBColor:255:255:255:255\" Url=\"\" Animate=\"False\">"; titleSlide += "<Text>"; titleSlide += "<TextObject Bold=\"False\" Italic=\"False\" Underline=\"False\" FontSize=\"24\" FontName=\"Verdana\" ForgroundColor=\"NamedColor:White\" BackgroundColor=\"NamedColor:Black\" BorderStyle=\"None\">A Worldwide Telescope Tour of Your Favourites</TextObject>"; titleSlide += "</Text>"; titleSlide += "</Overlay>"; titleSlide += "</Overlays>"; titleSlide += "</TourStop>"; string tourstop = ""; tourstop += "<TourStop Id=\"{Guid}\" Name=\"\" Description=\"{SlideTitle}\" Thumbnail=\"\" Duration=\"00:00:10\" Master=\"False\" Transition=\"Slew\" HasLocation=\"True\" LocationAltitude=\"100\" LocationLat=\"47.64222\" LocationLng=\"-122.142\" HasTime=\"True\" StartTime=\"7/8/2009 4:09:17 PM\" EndTime=\"7/8/2009 4:09:17 PM\" ActualPlanetScale=\"True\" ShowClouds=\"False\" ShowConstellationBoundries=\"True\" ShowConstellationFigures=\"True\" ShowConstellationSelection=\"True\" ShowEcliptic=\"False\" ShowElevationModel=\"False\" ShowFieldOfView=\"False\" ShowGrid=\"False\" ShowHorizon=\"False\" ShowHorizonPanorama=\"False\" ShowMoonsAsPointSource=\"False\" ShowSolarSystem=\"True\" FovTelescope=\"0\" FovEyepiece=\"0\" FovCamera=\"0\" LocalHorizonMode=\"False\" FadeInOverlays=\"False\" SolarSystemStars=\"True\" SolarSystemMilkyWay=\"True\" SolarSystemCosmos=\"True\" SolarSystemOrbits=\"True\" SolarSystemOverlays=\"True\" SolarSystemLighting=\"True\" SolarSystemScale=\"100\" SolarSystemMultiRes=\"True\">"; tourstop += "<Place Name=\"Current Screen\" DataSetType=\"Sky\" RA=\"{RA}\" Dec=\"{Dec}\" Constellation=\"\" Classification=\"Unidentified\" Magnitude=\"0\" Distance=\"0\" AngularSize=\"60\" ZoomLevel=\"{ZoomLevel}\" Rotation=\"0\" Angle=\"0\" Opacity=\"100\" Target=\"Sun\">"; tourstop += "<Description><![CDATA[]]></Description>"; tourstop += "<BackgroundImageSet>"; tourstop += "<ImageSet Generic=\"False\" DataSetType=\"Sky\" BandPass=\"Visible\" Name=\"SDSS: Sloan Digital Sky Survey (Optical)\" Url=\"http://www.worldwidetelescope.org/wwtweb/sdsstoast.aspx?q={1},{2},{3}\" DemUrl=\"\" BaseTileLevel=\"0\" TileLevels=\"13\" BaseDegreesPerTile=\"180\" FileType=\".png\" BottomsUp=\"False\" Projection=\"Toast\" QuadTreeMap=\"\" CenterX=\"0\" CenterY=\"0\" OffsetX=\"0\" OffsetY=\"0\" Rotation=\"0\" Sparse=\"False\" ElevationModel=\"False\" StockSet=\"False\" WidthFactor=\"1\">"; tourstop += "<ThumbnailUrl>http://www.worldwidetelescope.org/wwtweb/thumbnail.aspx?name=sloan</ThumbnailUrl>"; tourstop += "</ImageSet>"; tourstop += "</BackgroundImageSet>"; tourstop += "</Place>"; tourstop += "<Overlays />"; tourstop += "</TourStop>"; string Title = ""; string Description = ""; string Author = ""; string AuthorEmail = ""; string OrgUrl = ""; string OrgName = ""; StringBuilder sb = new StringBuilder(); Guid id = Guid.NewGuid(); string tourGuid = id.ToString(); string dir = baseDir; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } string outputfilename = dir + id.ToString() + ".wtt"; FileCabinet cab = new FileCabinet(outputfilename, dir); string page = Request.PhysicalPath.Substring(0, Request.PhysicalPath.LastIndexOf('\\')); page = page.Substring(0, page.LastIndexOf('\\')); List <string> thumbs = new List <string>(); thumbs.Add(tourGuid + "\\9d25fcf1-47a1-4036-84e1-2e4e70647a4b.thumb.png"); string musicUrl = null; string musicPath = null; string voiceUrl = null; string voicePath = null; try { XmlNode Tour = doc["Tour"]; Title = Tour["Title"].InnerText; Description = Tour["Description"].InnerText; Author = Tour["Author"].InnerText; AuthorEmail = Tour["Email"].InnerText; OrgUrl = Tour["OrganizationURL"].InnerText; OrgName = Tour["OrganizationName"].InnerText; sb.Append( tourStart.Replace("{TourGuid}", tourGuid) .Replace("{Title}", Title) .Replace("{Description}", Description) .Replace("{AuthorName}", Author) .Replace("{AuthorEmail}", AuthorEmail) .Replace("{OrganizationUrl}", OrgUrl) .Replace("{OrganizationName}", OrgName) .Replace("{Keywords}", "")); sb.Append(titleSlide); XmlNode Music = Tour["MusicTrack"]; musicUrl = Music["Filename"].InnerText; XmlNode Voice = Tour["VoiceTrack"]; voiceUrl = Music["Filename"].InnerText; string stopString = master; XmlNode TourStops = Tour["TourStops"]; foreach (XmlNode child in TourStops.ChildNodes) { double RA = Convert.ToDouble(child["RA"].InnerText); double Dec = Convert.ToDouble(child["Dec"].InnerText); double Zoom = Convert.ToDouble(child["ZoomLevel"].InnerText); Guid stopID = Guid.NewGuid(); string Duration = child["Duration"].InnerText; stopString = stopString.Replace("{Duration}", Duration) .Replace("{Guid}", stopID.ToString()) .Replace("{RA}", RA.ToString()) .Replace("{Dec}", Dec.ToString()) .Replace("{ZoomLevel}", Zoom.ToString()); sb.Append(stopString); thumbs.Add(tourGuid + "\\" + stopID.ToString() + ".thumb.png"); stopString = tourstop; } sb.Append(tourEnd); } catch { } //if (!string.IsNullOrEmpty(voiceUrl)) //{ // voicePath = dir + (Math.Abs(voiceUrl.GetHashCode()).ToString()); // if (!File.Exists(voicePath)) // { // client.DownloadFile(voiceUrl, voicePath); // } // cab.AddFile(voicePath, true, tourGuid + "\\voice.wma"); //} string tourfilename = dir + id.ToString() + ".wttxml"; File.WriteAllText(tourfilename, sb.ToString(), Encoding.UTF8); cab.AddFile(tourfilename, false, ""); cab.AddFile(page + "\\images\\zoologo.png", true, tourGuid + "\\zoologo.png"); WebClient client = new WebClient(); if (!string.IsNullOrEmpty(musicUrl)) { musicPath = dir + (Math.Abs(musicUrl.GetHashCode()).ToString()); if (!File.Exists(musicPath)) { client.DownloadFile(musicUrl, musicPath); } cab.AddFile(musicPath, true, tourGuid + "\\music.wma"); } foreach (string thumbFile in thumbs) { cab.AddFile(page + "\\images\\zoo.thumb.png", true, thumbFile); } cab.Package(); File.Delete(tourfilename); return(outputfilename); }
static void Main(string[] args) { // Create standard .NET web client instance WebClient webClient = new WebClient(); // Set API Key webClient.Headers.Add("x-api-key", API_KEY); try { // Prepare URL for `PDF To JPEG` API call string query = Uri.EscapeUriString(string.Format( "https://api.pdf.co/v1/pdf/convert/to/jpg?password={0}&pages={1}&url={2}&async={3}", Password, Pages, SourceFileUrl, Async)); // Execute request string response = webClient.DownloadString(query); // Parse JSON response JObject json = JObject.Parse(response); if (json["error"].ToObject <bool>() == false) { // Asynchronous job ID string jobId = json["jobId"].ToString(); // URL of generated JSON file available after the job completion; it will contain URLs of result JPEG files. string resultJsonFileUrl = json["url"].ToString(); // Check the job status in a loop. // If you don't want to pause the main thread you can rework the code // to use a separate thread for the status checking and completion. do { string status = CheckJobStatus(jobId); // Possible statuses: "working", "failed", "aborted", "success". // Display timestamp and status (for demo purposes) Console.WriteLine(DateTime.Now.ToLongTimeString() + ": " + status); if (status == "success") { // Download JSON file as string string jsonFileString = webClient.DownloadString(resultJsonFileUrl); JArray resultFilesUrls = JArray.Parse(jsonFileString); // Download generated JPEG files int page = 1; foreach (JToken token in resultFilesUrls) { string resultFileUrl = token.ToString(); string localFileName = String.Format(@".\page{0}.jpg", page); webClient.DownloadFile(resultFileUrl, localFileName); Console.WriteLine("Downloaded \"{0}\".", localFileName); page++; } break; } else if (status == "working") { // Pause for a few seconds Thread.Sleep(3000); } else { Console.WriteLine(status); break; } }while (true); } else { Console.WriteLine(json["message"].ToString()); } } catch (WebException e) { Console.WriteLine(e.ToString()); } webClient.Dispose(); Console.WriteLine(); Console.WriteLine("Press any key..."); Console.ReadKey(); }
static void Main(string[] args) { // Template text. Use Document Parser SDK (https://bytescout.com/products/developer/documentparsersdk/index.html) // to create templates. // Read template from file: String templateText = File.ReadAllText(@".\MultiPageTable-template1.yml"); // Create standard .NET web client instance WebClient webClient = new WebClient(); // Set API Key webClient.Headers.Add("x-api-key", API_KEY); // 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE. // * If you already have a direct file URL, skip to the step 3. // Prepare URL for `Get Presigned URL` API call string query = Uri.EscapeUriString(string.Format( "https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name={0}", Path.GetFileName(SourceFile))); try { // Execute request string response = webClient.DownloadString(query); // Parse JSON response JObject json = JObject.Parse(response); if (json["error"].ToObject <bool>() == false) { // Get URL to use for the file upload string uploadUrl = json["presignedUrl"].ToString(); string uploadedFileUrl = json["url"].ToString(); // 2. UPLOAD THE FILE TO CLOUD. webClient.Headers.Add("content-type", "application/octet-stream"); webClient.UploadFile(uploadUrl, "PUT", SourceFile); // You can use UploadData() instead if your file is byte[] or Stream webClient.Headers.Remove("content-type"); // 3. PARSE UPLOADED PDF DOCUMENT // URL for `Document Parser` API call query = Uri.EscapeUriString(string.Format( "https://api.pdf.co/v1/pdf/documentparser?url={0}&async={1}", uploadedFileUrl, Async)); Dictionary <string, string> requestBody = new Dictionary <string, string>(); requestBody.Add("template", templateText); // Execute request response = webClient.UploadString(query, "POST", JsonConvert.SerializeObject(requestBody)); // Parse JSON response json = JObject.Parse(response); if (json["error"].ToObject <bool>() == false) { // Asynchronous job ID string jobId = json["jobId"].ToString(); // Get URL of generated JSON file string resultFileUrl = json["url"].ToString(); // Check the job status in a loop. // If you don't want to pause the main thread you can rework the code // to use a separate thread for the status checking and completion. do { string status = CheckJobStatus(webClient, jobId); // Possible statuses: "working", "failed", "aborted", "success". // Display timestamp and status (for demo purposes) Console.WriteLine(DateTime.Now.ToLongTimeString() + ": " + status); if (status == "success") { // Download JSON file webClient.DownloadFile(resultFileUrl, DestinationFile); Console.WriteLine("Generated JSON file saved as \"{0}\" file.", DestinationFile); break; } else if (status == "working") { // Pause for a few seconds Thread.Sleep(3000); } else { Console.WriteLine(status); break; } }while (true); } else { Console.WriteLine(json["message"].ToString()); } } else { Console.WriteLine(json["message"].ToString()); } } catch (WebException e) { Console.WriteLine(e.ToString()); } webClient.Dispose(); Console.WriteLine(); Console.WriteLine("Press any key..."); Console.ReadKey(); }
/// <summary> /// Do the Download /// </summary> /// <returns> /// Return if Downloaded or not /// </returns> protected override bool DoDownload() { var imageURL = this.ImageLinkURL; var thumbURL = this.ThumbImageURL; if (this.EventTable.ContainsKey(imageURL)) { return(true); } var filePath = string.Empty; try { if (!Directory.Exists(this.SavePath)) { Directory.CreateDirectory(this.SavePath); } } catch (IOException ex) { // MainForm.DeleteMessage = ex.Message; // MainForm.Delete = true; return(false); } var cacheObject = new CacheObject { IsDownloaded = false, FilePath = filePath, Url = imageURL }; try { this.EventTable.Add(imageURL, cacheObject); } catch (ThreadAbortException) { return(true); } catch (Exception) { if (this.EventTable.ContainsKey(imageURL)) { return(false); } this.EventTable.Add(imageURL, cacheObject); } // Set the download Path var imageDownloadURL = thumbURL.Replace(@"thumbs/", string.Empty); // Set Image Name instead of using random name filePath = this.GetImageName(this.PostTitle, imageDownloadURL, this.ImageNumber); filePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(filePath)); ////////////////////////////////////////////////////////////////////////// filePath = Utility.GetSuitableName(filePath, true); ((CacheObject)this.EventTable[imageURL]).FilePath = filePath; try { var client = new WebClient(); client.Headers.Add($"Referer: {thumbURL}"); client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6"); client.DownloadFile(imageDownloadURL, filePath); client.Dispose(); } catch (ThreadAbortException) { ((CacheObject)this.EventTable[imageURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(imageURL); return(true); } catch (IOException ex) { // MainForm.DeleteMessage = ex.Message; // MainForm.Delete = true; ((CacheObject)this.EventTable[imageURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(imageURL); return(true); } catch (WebException) { ((CacheObject)this.EventTable[imageURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(imageURL); return(false); } ((CacheObject)this.EventTable[imageURL]).IsDownloaded = true; CacheController.Instance().LastPic = ((CacheObject)this.EventTable[imageURL]).FilePath = filePath; return(true); }
static void Main(string[] args) { // Create standard .NET web client instance WebClient webClient = new WebClient(); // Set API Key webClient.Headers.Add("x-api-key", API_KEY); // 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE. // * If you already have a direct file URL, skip to the step 3. // Prepare URL for `Get Presigned URL` API call string query = Uri.EscapeUriString(string.Format( "https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name={0}", Path.GetFileName(SourceFile))); try { // Execute request string response = webClient.DownloadString(query); // Parse JSON response JObject json = JObject.Parse(response); if (json["error"].ToObject <bool>() == false) { // Get URL to use for the file upload string uploadUrl = json["presignedUrl"].ToString(); // Get URL of uploaded file to use with later API calls string uploadedFileUrl = json["url"].ToString(); // 2. UPLOAD THE FILE TO CLOUD. webClient.Headers.Add("content-type", "application/octet-stream"); webClient.UploadFile(uploadUrl, "PUT", SourceFile); // You can use UploadData() instead if your file is byte[] or Stream // 3. CONVERT UPLOADED PDF FILE TO PNG // URL for `PDF To PNG` API call var url = "https://api.pdf.co/v1/pdf/convert/to/png"; // Prepare requests params as JSON Dictionary <string, object> parameters = new Dictionary <string, object>(); parameters.Add("password", Password); parameters.Add("pages", Pages); parameters.Add("url", uploadedFileUrl); // Convert dictionary of params to JSON string jsonPayload = JsonConvert.SerializeObject(parameters); // Execute POST request with JSON payload response = webClient.UploadString(url, jsonPayload); // Parse JSON response json = JObject.Parse(response); if (json["error"].ToObject <bool>() == false) { // Download generated PNG files int page = 1; foreach (JToken token in json["urls"]) { string resultFileUrl = token.ToString(); string localFileName = String.Format(@".\page{0}.png", page); webClient.DownloadFile(resultFileUrl, localFileName); Console.WriteLine("Downloaded \"{0}\".", localFileName); page++; } } else { Console.WriteLine(json["message"].ToString()); } } else { Console.WriteLine(json["message"].ToString()); } } catch (WebException e) { Console.WriteLine(e.ToString()); } webClient.Dispose(); Console.WriteLine(); Console.WriteLine("Press any key..."); Console.ReadKey(); }
static void Main(string[] args) { // Create standard .NET web client instance WebClient webClient = new WebClient(); // Set API Key webClient.Headers.Add("x-api-key", API_KEY); // Prepare URL for `Merge PDF` API call string url = "https://api.pdf.co/v1/pdf/merge2"; // Prepare requests params as JSON Dictionary <string, object> parameters = new Dictionary <string, object>(); parameters.Add("name", Path.GetFileName(DestinationFile)); parameters.Add("url", string.Join(",", SourceFiles)); parameters.Add("async", Async); // Convert dictionary of params to JSON string jsonPayload = JsonConvert.SerializeObject(parameters); try { // Execute POST request with JSON payload string response = webClient.UploadString(url, jsonPayload); // Parse JSON response JObject json = JObject.Parse(response); if (json["error"].ToObject <bool>() == false) { // Asynchronous job ID string jobId = json["jobId"].ToString(); // URL of generated PDF file that will available after the job completion string resultFileUrl = json["url"].ToString(); // Check the job status in a loop. // If you don't want to pause the main thread you can rework the code // to use a separate thread for the status checking and completion. do { string status = CheckJobStatus(jobId); // Possible statuses: "working", "failed", "aborted", "success". // Display timestamp and status (for demo purposes) Console.WriteLine(DateTime.Now.ToLongTimeString() + ": " + status); if (status == "success") { // Download PDF file webClient.DownloadFile(resultFileUrl, DestinationFile); Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile); break; } else if (status == "working") { // Pause for a few seconds Thread.Sleep(3000); } else { Console.WriteLine(status); break; } }while (true); } else { Console.WriteLine(json["message"].ToString()); } } catch (WebException e) { Console.WriteLine(e.ToString()); } webClient.Dispose(); Console.WriteLine(); Console.WriteLine("Press any key..."); Console.ReadKey(); }
private string LoginApi(string url, string apiAddress, out CookieContainer loginPageCookieContainer) { string xmlSrc; var LOGIN_PAGE = "https://secure.bilibili.com/login"; //获取登录页Cookie var loginPageRequest = (HttpWebRequest)WebRequest.Create(LOGIN_PAGE); loginPageRequest.Proxy = Info.Proxy; loginPageRequest.Referer = @"http://www.bilibili.com/"; loginPageRequest.UserAgent = @"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0"; loginPageRequest.Accept = @"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; string loginPageCookie; using (var resp = loginPageRequest.GetResponse()) { loginPageCookieContainer = new CookieContainer(); var sid = Regex.Match(resp.Headers["Set-Cookie"], @"(?<=sid=)\w+").Value; loginPageCookieContainer.Add(new Cookie("sid", sid, "/", ".bilibili.com")); loginPageCookie = loginPageCookieContainer.GetCookieHeader(new Uri(LOGIN_PAGE)); } //获取验证码图片 var loginInfo = new UserLoginInfo(); if (Info.BasePlugin.Configuration.ContainsKey("Username")) { loginInfo.Username = Encoding.UTF8.GetString(Convert.FromBase64String(Info.BasePlugin.Configuration["Username"])); } if (Info.BasePlugin.Configuration.ContainsKey("Password")) { loginInfo.Password = Encoding.UTF8.GetString(Convert.FromBase64String(Info.BasePlugin.Configuration["Password"])); } if (Settings.ContainsKey("Username")) { loginInfo.Username = Settings["Username"]; } if (Settings.ContainsKey("Password")) { loginInfo.Password = Settings["Password"]; } var captchaUrl = @"https://secure.bilibili.com/captcha?r=" + new Random(Environment.TickCount).NextDouble().ToString(); var captchaFile = Path.GetTempFileName() + ".png"; var captchaClient = new WebClient { Proxy = Info.Proxy }; captchaClient.Headers.Add(HttpRequestHeader.Cookie, loginPageCookie); captchaClient.DownloadFile(captchaUrl, captchaFile); loginInfo = ToolForm.CreateLoginForm(loginInfo, @"https://secure.bilibili.com/register", captchaFile); //保存到设置 Settings["Username"] = loginInfo.Username; Settings["Password"] = loginInfo.Password; string postString = @"act=login&gourl=http%%3A%%2F%%2Fbilibili.com%%2F&userid=" + loginInfo.Username + "&pwd=" + loginInfo.Password + "&vdcode=" + loginInfo.Captcha.ToUpper() + "&keeptime=2592000"; byte[] data = Encoding.UTF8.GetBytes(postString); var loginRequest = (HttpWebRequest)WebRequest.Create(@"https://secure.bilibili.com/login"); loginRequest.Proxy = Info.Proxy; loginRequest.Method = "POST"; loginRequest.Referer = "https://secure.bilibili.com/login"; loginRequest.ContentType = "application/x-www-form-urlencoded"; loginRequest.ContentLength = data.Length; loginRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:25.0) Gecko/20100101 Firefox/25.0"; loginRequest.Referer = url; loginRequest.CookieContainer = loginPageCookieContainer; //发送POST数据 using (var outstream = loginRequest.GetRequestStream()) { outstream.Write(data, 0, data.Length); outstream.Flush(); } //关闭请求 loginRequest.GetResponse().Close(); var cookies = loginRequest.CookieContainer.GetCookieHeader(new Uri(LOGIN_PAGE)); var client = new WebClient { Proxy = Info.Proxy }; client.Headers.Add(HttpRequestHeader.Cookie, cookies); var apiRequest = (HttpWebRequest)WebRequest.Create(apiAddress); apiRequest.Proxy = Info.Proxy; apiRequest.Headers.Add(HttpRequestHeader.Cookie, cookies); xmlSrc = Network.GetHtmlSource(apiRequest, Encoding.UTF8); return(xmlSrc); }
private void SetFilePath(string filepath) { var uri = new Uri(filepath); if (uri.Scheme == "qmk") { string url; url = filepath.Replace(filepath.Contains("qmk://") ? "qmk://" : "qmk:", ""); if (!Directory.Exists(Path.Combine(Application.LocalUserAppDataPath, "downloads"))) { Directory.CreateDirectory(Path.Combine(Application.LocalUserAppDataPath, "downloads")); } try { _printer.Print($"Downloading the file: {url}", MessageType.Info); using (var wb = new WebClient()) { wb.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.33 Safari/537.36"); filepath = Path.Combine(KnownFolders.Downloads.Path, filepath.Substring(filepath.LastIndexOf("/") + 1).Replace(".", "_" + Guid.NewGuid().ToString().Substring(0, 8) + ".")); wb.DownloadFile(url, filepath); } } catch (Exception e) { _printer.PrintResponse("Something went wrong when trying to get the default keymap file.", MessageType.Error); return; } _printer.PrintResponse($"File saved to: {filepath}", MessageType.Info); } if (filepath.EndsWith(".qmk", true, null)) { _printer.Print("Found .qmk file", MessageType.Info); var qmkFilepath = $"{Path.GetTempPath()}qmk_toolbox{filepath.Substring(filepath.LastIndexOf("\\"))}\\"; _printer.PrintResponse($"Extracting to {qmkFilepath}\n", MessageType.Info); if (Directory.Exists(qmkFilepath)) { Directory.Delete(qmkFilepath, true); } ZipFile.ExtractToDirectory(filepath, qmkFilepath); var files = Directory.GetFiles(qmkFilepath); var readme = ""; var info = new Info(); foreach (var file in files) { _printer.PrintResponse($" - {file.Substring(file.LastIndexOf("\\") + 1)}\n", MessageType.Info); if (file.Substring(file.LastIndexOf("\\") + 1).Equals("firmware.hex", StringComparison.OrdinalIgnoreCase) || file.Substring(file.LastIndexOf("\\") + 1).Equals("firmware.bin", StringComparison.OrdinalIgnoreCase)) { SetFilePath(file); } if (file.Substring(file.LastIndexOf("\\") + 1).Equals("readme.md", StringComparison.OrdinalIgnoreCase)) { readme = File.ReadAllText(file); } if (file.Substring(file.LastIndexOf("\\") + 1).Equals("info.json", StringComparison.OrdinalIgnoreCase)) { info = JsonConvert.DeserializeObject <Info>(File.ReadAllText(file)); } } if (!string.IsNullOrEmpty(info.Keyboard)) { _printer.Print($"Keymap for keyboard \"{info.Keyboard}\" - {info.VendorId}:{info.ProductId}", MessageType.Info); } if (string.IsNullOrEmpty(readme)) { return; } _printer.Print("Notes for this keymap:", MessageType.Info); _printer.PrintResponse(readme, MessageType.Info); } else { if (string.IsNullOrEmpty(filepath)) { return; } filepathBox.Text = filepath; if (!filepathBox.Items.Contains(filepath)) { filepathBox.Items.Add(filepath); } } }
private bool Download() { if (IsDownloading) { return(false); } Interlocked.Increment(ref _countDownload); Log.Trace("Checking update..."); Reset(); string json = _client.DownloadString(string.Format(API_RELEASES_LINK, REPO_USER, REPO_NAME)); JArray data = JsonConvert.DeserializeObject <JArray>(json); #if DEV_BUILD FileInfo fileLastCommit = new FileInfo(Path.Combine(CUOEnviroment.ExecutablePath, "version.txt")); #endif foreach (JToken releaseToken in data.Children()) { string tagName = releaseToken["tag_name"].ToString(); Log.Trace("Fetching: " + tagName); #if DEV_BUILD if (tagName == "ClassicUO-dev-preview") { bool ok = false; string commitID = releaseToken["target_commitish"].ToString(); if (fileLastCommit.Exists) { string lastCommit = File.ReadAllText(fileLastCommit.FullName); ok = lastCommit != commitID; } File.WriteAllText(fileLastCommit.FullName, commitID); if (!ok) { break; } #else if (Version.TryParse(tagName, out Version version) && version > CUOEnviroment.Version) { Log.Trace("Found new version available: " + version); #endif string name = releaseToken["name"].ToString(); string body = releaseToken["body"].ToString(); JToken asset = releaseToken["assets"]; if (!asset.HasValues) { Log.Error("No zip found for: " + name); continue; } asset = asset.First; string assetName = asset["name"].ToString(); string downloadUrl = asset["browser_download_url"].ToString(); string temp; try { temp = Path.GetTempPath(); } catch { Log.Warn("Impossible to retrive OS temp path. CUO will use current path"); temp = CUOEnviroment.ExecutablePath; } string tempPath = Path.Combine(temp, "update-temp"); string zipFile = Path.Combine(tempPath, assetName); if (!Directory.Exists(tempPath)) { Directory.CreateDirectory(tempPath); } Log.Trace("Downloading: " + assetName); _client.DownloadProgressChanged += ClientOnDownloadProgressChanged; _client.DownloadFile(downloadUrl, zipFile); Log.Trace(assetName + "..... done"); _client.DownloadProgressChanged -= ClientOnDownloadProgressChanged; Reset(); try { using (ZipArchive zip = new ZipArchive(File.OpenRead(zipFile))) zip.ExtractToDirectory(tempPath, true); File.Delete(zipFile); } catch (Exception ex) { Log.Error("[UPDATER ERROR]: impossible to update.\n" + ex); } string prefix = Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Unix ? "mono " : string.Empty; new Process { StartInfo = { WorkingDirectory = tempPath, FileName = prefix + Path.Combine(tempPath, "ClassicUO.exe"), UseShellExecute = false, Arguments = $"--source \"{CUOEnviroment.ExecutablePath}\" --pid {Process.GetCurrentProcess().Id} --action update" } }.Start(); return(true); } } Interlocked.Decrement(ref _countDownload); return(false); }
static void Main(string[] args) { // Create standard .NET web client instance WebClient webClient = new WebClient(); // Set API Key webClient.Headers.Add("x-api-key", API_KEY); // 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE. // * If you already have a direct file URL, skip to the step 3. // Prepare URL for `Get Presigned URL` API call string query = Uri.EscapeUriString(string.Format( "https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name={0}", Path.GetFileName(SourceFile))); try { // Execute request string response = webClient.DownloadString(query); // Parse JSON response JObject json = JObject.Parse(response); if (json["status"].ToString() != "error") { // Get URL to use for the file upload string uploadUrl = json["presignedUrl"].ToString(); string uploadedFileUrl = json["url"].ToString(); // 2. UPLOAD THE FILE TO CLOUD. webClient.Headers.Add("content-type", "application/octet-stream"); webClient.UploadFile(uploadUrl, "PUT", SourceFile); // You can use UploadData() instead if your file is byte[] or Stream webClient.Headers.Remove("content-type"); // 3. CONVERT UPLOADED PDF FILE TO JSON // Prepare URL for `PDF To JSON` API call query = Uri.EscapeUriString(string.Format( "https://api.pdf.co/v1/pdf/convert/to/json?name={0}&password={1}&pages={2}&url={3}&profiles={4}", Path.GetFileName(DestinationFile), Password, Pages, uploadedFileUrl, Profiles)); // Execute request response = webClient.DownloadString(query); // Parse JSON response json = JObject.Parse(response); if (json["status"].ToString() != "error") { // Get URL of generated JSON file string resultFileUrl = json["url"].ToString(); // Download JSON file webClient.DownloadFile(resultFileUrl, DestinationFile); Console.WriteLine("Generated JSON file saved as \"{0}\" file.", DestinationFile); } else { Console.WriteLine(json["message"].ToString()); } } else { Console.WriteLine(json["message"].ToString()); } } catch (WebException e) { Console.WriteLine(e.ToString()); } webClient.Dispose(); Console.WriteLine(); Console.WriteLine("Press any key..."); Console.ReadKey(); }
public HttpResponseMessage UploadSkydriveDocument(UploadSkydriveDocument documentSkyDrive) { HttpResponseMessage responseToClient = new HttpResponseMessage(); ResponseMessageDocument responseMessage = new ResponseMessageDocument(); bool fileDuplicateFlag = false; try { System.Collections.Generic.IEnumerable <string> iHeader; Request.Headers.TryGetValues("AuthToken", out iHeader); string authToken = iHeader.ElementAt(0); string tempDirectory = ConfigurationManager.AppSettings["TempDirectory"].ToString() + documentSkyDrive.EnvelopeId; using (var dbContext = new eSignEntities()) { EnvelopeRepository envelopeRepository = new EnvelopeRepository(dbContext); bool isEnvelopePrepare = envelopeRepository.IsEnvelopePrepare(new Guid(documentSkyDrive.EnvelopeId)); if (!Directory.Exists(tempDirectory)) { responseMessage.StatusCode = HttpStatusCode.BadRequest; responseMessage.StatusMessage = "BadRequest"; responseMessage.Message = ConfigurationManager.AppSettings["EnvelopeIdMissing"].ToString(); responseMessage.EnvelopeId = documentSkyDrive.EnvelopeId; responseToClient = Request.CreateResponse(HttpStatusCode.BadRequest, responseMessage); return(responseToClient); } else if (isEnvelopePrepare == true) { responseMessage.StatusCode = HttpStatusCode.BadRequest; responseMessage.StatusMessage = "BadRequest"; responseMessage.Message = ConfigurationManager.AppSettings["EnvelopePrepared"].ToString(); responseMessage.EnvelopeId = documentSkyDrive.EnvelopeId; responseToClient = Request.CreateResponse(HttpStatusCode.BadRequest, responseMessage); return(responseToClient); } else { UserTokenRepository userTokenRepository = new UserTokenRepository(dbContext); string userEmail = userTokenRepository.GetUserEmailByToken(authToken); Guid UserId = userTokenRepository.GetUserProfileUserIDByID(userTokenRepository.GetUserProfileIDByEmail(userEmail)); bool isEnvelopeExists = envelopeRepository.IsUserEnvelopeExists(UserId, new Guid(documentSkyDrive.EnvelopeId)); if (!isEnvelopeExists) { responseMessage.StatusCode = HttpStatusCode.NoContent; responseMessage.StatusMessage = "NoContent"; responseMessage.Message = Convert.ToString(ConfigurationManager.AppSettings["NoContent"].ToString()); responseMessage.EnvelopeId = documentSkyDrive.EnvelopeId; responseToClient = Request.CreateResponse(HttpStatusCode.NoContent, responseMessage, Configuration.Formatters.XmlFormatter); return(responseToClient); } string documentUploadPath = Path.Combine(tempDirectory, ConfigurationManager.AppSettings["UploadedDocuments"].ToString()); string docFinalPath = Path.Combine(documentUploadPath, documentSkyDrive.FileName); if (!Directory.Exists(documentUploadPath)) { Directory.CreateDirectory(documentUploadPath); } string[] listOfFiles = Directory.GetFiles(documentUploadPath); foreach (var file in listOfFiles) { if (file.Contains(documentSkyDrive.FileName)) { fileDuplicateFlag = true; break; } } if (fileDuplicateFlag) { responseMessage.StatusCode = HttpStatusCode.Ambiguous; responseMessage.StatusMessage = "Ambiguous"; responseMessage.Message = ConfigurationManager.AppSettings["FileDuplicate"].ToString(); responseMessage.EnvelopeId = documentSkyDrive.EnvelopeId; responseToClient = Request.CreateResponse(HttpStatusCode.Ambiguous, responseMessage); return(responseToClient); } //string[] validFileTypes = { "docx", "pdf", "doc", "xls", "xlsx", "ppt", "pptx", "DOCX", "PDF", "DOC", "XLS", "XLSX", "PPT", "PPTX" }; //string ext = Path.GetExtension(documentSkyDrive.FileName); //bool isValidType = false; //for (int j = 0; j < validFileTypes.Length; j++) //{ // if (ext == "." + validFileTypes[j]) // { // isValidType = true; // break; // } //} //if (!isValidType) //{ // responseMessage.StatusCode = HttpStatusCode.NotAcceptable; // responseMessage.StatusMessage = "NotAcceptable"; // responseMessage.Message = ConfigurationManager.AppSettings["InvalidFileExtension"].ToString(); // responseMessage.EnvelopeId = documentSkyDrive.EnvelopeId; // responseToClient = Request.CreateResponse(HttpStatusCode.NotAcceptable, responseMessage); // return responseToClient; //} try { using (WebClient webClient = new WebClient()) { webClient.DownloadFile(new Uri(documentSkyDrive.DownloadUrl), docFinalPath); } } catch (WebException ex) { responseMessage.StatusCode = HttpStatusCode.BadRequest; responseMessage.StatusMessage = "BadRequest"; responseMessage.Message = ConfigurationManager.AppSettings["InvalidDownloadUri"].ToString(); responseMessage.EnvelopeId = documentSkyDrive.EnvelopeId; responseToClient = Request.CreateResponse(HttpStatusCode.BadRequest, responseMessage); return(responseToClient); } Guid documentId = Guid.NewGuid(); DocumentRepository documentRepository = new DocumentRepository(dbContext); UnitOfWork unitOfWork = new UnitOfWork(dbContext); Documents doc = new Documents(); doc.ID = documentId; doc.EnvelopeID = new Guid(documentSkyDrive.EnvelopeId); doc.DocumentName = documentSkyDrive.FileName; doc.UploadedDateTime = DateTime.Now; int docCount = Directory.GetFiles(documentUploadPath).Length; doc.Order = (short)(docCount); documentRepository.Save(doc); unitOfWork.SaveChanges(); responseMessage.StatusCode = HttpStatusCode.OK; responseMessage.StatusMessage = "OK"; responseMessage.Message = ConfigurationManager.AppSettings["SuccessDocumentUpload"].ToString(); responseMessage.EnvelopeId = documentSkyDrive.EnvelopeId; responseMessage.DocumentId = Convert.ToString(documentId); responseToClient = Request.CreateResponse(HttpStatusCode.OK, responseMessage); return(responseToClient); } } } catch (Exception e) { responseToClient = Request.CreateResponse((HttpStatusCode)422); responseToClient.Content = new StringContent(e.Message, Encoding.Unicode); throw new HttpResponseException(responseToClient); } }
/// <summary> /// Translates the specified source text. /// </summary> /// <param name="sourceText">The source text.</param> /// <param name="sourceLanguage">The source language.</param> /// <param name="targetLanguage">The target language.</param> /// <returns>The translation.</returns> public string Translate (string sourceText, string sourceLanguage, string targetLanguage) { // Initialize this.Error = null; this.TranslationSpeechUrl = null; this.TranslationTime = TimeSpan.Zero; DateTime tmStart = DateTime.Now; string translation = string.Empty; try { // Download translation string url = string.Format("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}", Translator.LanguageEnumToIdentifier(sourceLanguage), Translator.LanguageEnumToIdentifier(targetLanguage), HttpUtility.UrlEncode(sourceText)); string outputFile = Path.GetTempFileName(); using (WebClient wc = new WebClient()) { wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); wc.DownloadFile(url, outputFile); } // Get translated text if (File.Exists(outputFile)) { // Get phrase collection string text = File.ReadAllText(outputFile); int index = text.IndexOf(string.Format(",,\"{0}\"", Translator.LanguageEnumToIdentifier(sourceLanguage))); if (index == -1) { // Translation of single word int startQuote = text.IndexOf('\"'); if (startQuote != -1) { int endQuote = text.IndexOf('\"', startQuote + 1); if (endQuote != -1) { translation = text.Substring(startQuote + 1, endQuote - startQuote - 1); } } } else { // Translation of phrase text = text.Substring(0, index); text = text.Replace("],[", ","); text = text.Replace("]", string.Empty); text = text.Replace("[", string.Empty); text = text.Replace("\",\"", "\""); // Get translated phrases string[] phrases = text.Split(new[] { '\"' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; (i < phrases.Count()); i += 2) { string translatedPhrase = phrases[i]; if (translatedPhrase.StartsWith(",,")) { i--; continue; } translation += translatedPhrase + " "; } } // Fix up translation translation = translation.Trim(); translation = translation.Replace(" ?", "?"); translation = translation.Replace(" !", "!"); translation = translation.Replace(" ,", ","); translation = translation.Replace(" .", "."); translation = translation.Replace(" ;", ";"); // And translation speech URL this.TranslationSpeechUrl = string.Format("https://translate.googleapis.com/translate_tts?ie=UTF-8&q={0}&tl={1}&total=1&idx=0&textlen={2}&client=gtx", HttpUtility.UrlEncode(translation), Translator.LanguageEnumToIdentifier(targetLanguage), translation.Length); } } catch (Exception ex) { this.Error = ex; } // Return result this.TranslationTime = DateTime.Now - tmStart; return(translation); }
static void Main(string[] args) { Console.WriteLine("Greatings Trustpilot development team !!"); Console.WriteLine("I am glad that i took the red pill !!"); Console.WriteLine("This program is written to find hidden messages !!"); string anagramOfPhrase = "poultry outwits ants"; string easySecretPhraseMD5 = "e4820b45d2277f3844eac66c903e84be"; string moreDifficultSecretPhraseMD5 = "23170acc097c24edb98fc5488ab033fe"; string hardSecretPhraseMD5 = "665e5bcb0c20062fe8abaaf4628bb154"; Console.WriteLine("An anagrams of the phrase: {0}!!", anagramOfPhrase); Console.WriteLine("Loading the words...."); if (!System.IO.File.Exists("./wordlist")) { string url = "https://followthewhiterabbit.trustpilot.com/cs/wordlist"; Console.WriteLine("Downloading the list from {0}...", url); string savePath = @"./wordlist"; try { WebClient client = new WebClient(); client.DownloadFile(url, savePath); }catch (Exception ex) { Console.WriteLine("Oh no!! Something bad happened while downloading the file {0}", ex.Message); } } // Lets read the file string[] myDictionary = System.IO.File.ReadAllLines("./wordlist"); Console.WriteLine("Dictionary loaded!!"); string[] hiddenMessageHash = { easySecretPhraseMD5, moreDifficultSecretPhraseMD5, hardSecretPhraseMD5 }; Anagram anagram = new Anagram(anagramOfPhrase); anagram.LoadHiddenMessages(hiddenMessageHash); Stopwatch sw = new Stopwatch(); foreach (var hiddenMessage in hiddenMessageHash) { Console.WriteLine("Now looking for hidden message with hash: {0} ....", hiddenMessage); sw.Restart(); if (anagram.FindAnagrams(hiddenMessage, myDictionary)) { Console.WriteLine("*************** Message found !!! ******************* \n Message : {0}", anagram.GetMessage(hiddenMessage)); } else { Console.WriteLine("\nMessage not found!! Will try harder again!! "); bool tryHarder = true; if (anagram.FindAnagrams(hiddenMessage, myDictionary, tryHarder)) { Console.WriteLine("*************** Message found !!! ******************* \n Message : {0}", anagram.GetMessage(hiddenMessage)); Console.WriteLine("************ I see the Matrix now *******************"); } } sw.Stop(); Console.WriteLine("Time taken : {0}", sw.Elapsed); Console.WriteLine("Press any Key to continue finding the next hidden message:"); Console.ReadKey(true); } var myhiddenMessage = "4a9f51db2c7eba0c724499f749d3176a"; Console.WriteLine("This one is for you to find, md5 hash: {0}", myhiddenMessage); Console.WriteLine("Find the hidden message and type here:"); var message = Console.ReadLine().ToLower(); // Yay you found it while (!anagram.CreateMD5(message).Equals(myhiddenMessage)) { Console.WriteLine("Type 'help', if you want to use same program to find the hidden message"); if (message.Equals("help")) { var myAnagram = new Anagram(anagramOfPhrase); string[] hiddenmessages = { myhiddenMessage }; myAnagram.LoadHiddenMessages(hiddenmessages); myAnagram.FindAnagrams(myhiddenMessage, myDictionary); message = myAnagram.GetMessage(myhiddenMessage); } else { Console.WriteLine("Find the message and type here:"); message = Console.ReadLine().ToLower(); } } Console.WriteLine("*************** You found it !!! ******************* \n Message : {0}", message); Console.WriteLine("This code challenge has been fun for me.\n I hope you ejoyed my program too!! \n Thank you trustpilot development team!!"); Console.ReadKey(true); Console.Clear(); }
private void start_Click(object sender, EventArgs e) { DateTime dStart = DateTime.Now; // 取的現在時間 start.Enabled = false; _continue.Enabled = false; int aTagCount = 0; //連結數 int page = 0; // 頁數 int count = 0; // 資料數 Match m; // Match the regular expression pattern against a text string string url = "https://www.ptt.cc/bbs/Beauty/index2112.html"; Regex r = new Regex(pattern, RegexOptions.IgnoreCase); //// 建立資料夾 try { if (!Directory.Exists(path)) { DirectoryInfo di = Directory.CreateDirectory(path); } } catch (Exception ex) { Console.WriteLine("[Error Message] : " + ex.Message); } /// listview vertical direction content.View = View.Details; ColumnHeader header = new ColumnHeader(); header.Text = ""; header.Name = "col1"; content.Columns.Add(header); // create a new instance of the chrome driver IWebDriver driver = new ChromeDriver("webchrome.exe"); // Launch the website driver.Navigate().GoToUrl(url); driver.Navigate().Refresh(); // type : ReadOnlyCollection<IWebElement> var elements = driver.FindElements(By.XPath("//div[@class='title']/a")); aTagCount = elements.Count(); for (int i = 0; i < aTagCount; i++) { elements = driver.FindElements(By.XPath("//div[@class='title']/a")); elements[i].Click(); var aTagElements = driver.FindElements(By.XPath("//div[@id='main-content']/a")); foreach (var aTag in aTagElements) { ListViewItem listViewItem = new ListViewItem(); if (r.IsMatch(aTag.GetAttribute("href"))) { listViewItem.Text = aTag.GetAttribute("href"); content.Items.Add(listViewItem); /// download immage using (WebClient client = new WebClient()) { int index = aTag.GetAttribute("href").LastIndexOf("/"); // checking if image exist in path if (!File.Exists(path + "/" + aTag.GetAttribute("href").Substring(index))) { client.DownloadFile(new Uri(aTag.GetAttribute("href")), path + "/" + aTag.GetAttribute("href").Substring(index)); count++; } } } } // 返回 driver.Navigate().Back(); } // 設定下載圖片個數 image.Text = count.ToString(); // Kill the browser driver.Close(); }
public bool InvokeMasterlistupdate(ref string message) { try { HtmlWeb hw = new HtmlWeb(); HtmlDocument doc = hw.Load(ConfigurationSettings.AppSettings["CSCAMasterlist"]); string relativeUrl = string.Empty; foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]")) { string href = link.Attributes["href"].Value; if (href.Contains("GermanMasterList.zip")) { relativeUrl = href; break; } } if (relativeUrl == "") { message = "No valid url with CSCA found"; return(false); } else { string aboluteUrl = "https://bsi.bund.de" + relativeUrl; using (WebClient client = new WebClient()) { client.DownloadFile(aboluteUrl, ConfigurationSettings.AppSettings["JavaReaderPath"] + "CSCAMasterlist.zip"); callback.CSCADownloaded("CSCAMasterlist.zip"); } System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(new FileStream(ConfigurationSettings.AppSettings["JavaReaderPath"] + "CSCAMasterlist.zip", FileMode.Open), System.IO.Compression.ZipArchiveMode.Read); foreach (System.IO.Compression.ZipArchiveEntry zae in zip.Entries) { System.IO.Compression.DeflateStream ds = (System.IO.Compression.DeflateStream)zae.Open(); MemoryStream ms = new MemoryStream(); ds.CopyTo(ms); File.WriteAllBytes(ConfigurationSettings.AppSettings["JavaReaderPath"] + "CSCAMasterlist.ml", ms.ToArray()); callback.CSCAUnzipped("CSCAMasterlist.ml"); break; } bool res = ParseMasterlist(); if (res) { callback.CSCAParsed("masterlist-content-current.data"); message = "Certificates extracted"; } else { message = "Error extracting certificates"; } return(true); } } catch (Exception ex) { message = "Error updating masterlist: " + ex.Message; return(false); } }
protected override void InternalExecute() { Stopwatch stopwatch = Stopwatch.StartNew(); ////////////////////////////////////////////////// string exportPath; string assPath = System.Reflection.Assembly.GetExecutingAssembly().Location; exportPath = Path.Combine(Path.GetDirectoryName(assPath), "export-pic"); if (!Directory.Exists(exportPath)) { Directory.CreateDirectory(exportPath); } TeamFoundationIdentity SIDS = ims2.ReadIdentity(IdentitySearchFactor.AccountName, "Team Foundation Valid Users", MembershipQuery.Expanded, ReadIdentityOptions.None); Trace.WriteLine(string.Format("Found {0}", SIDS.Members.Count())); var itypes = (from IdentityDescriptor id in SIDS.Members select id.IdentityType).Distinct(); foreach (string item in itypes) { var infolks = (from IdentityDescriptor id in SIDS.Members where id.IdentityType == item select id); Trace.WriteLine(string.Format("Found {0} of {1}", infolks.Count(), item)); } var folks = (from IdentityDescriptor id in SIDS.Members where id.IdentityType == "System.Security.Principal.WindowsIdentity" select id); DirectoryContext objContext = new DirectoryContext(DirectoryContextType.Domain, config.Domain, config.Username, config.Password); Domain objDomain = Domain.GetDomain(objContext); string ldapName = string.Format("LDAP://{0}", objDomain.Name); int current = folks.Count(); foreach (IdentityDescriptor id in folks) { try { TeamFoundationIdentity i = ims2.ReadIdentity(IdentitySearchFactor.Identifier, id.Identifier, MembershipQuery.Direct, ReadIdentityOptions.None); if (!(i == null) && i.IsContainer == false) { DirectoryEntry d = new DirectoryEntry(ldapName, config.Username, config.Password); DirectorySearcher dssearch = new DirectorySearcher(d); dssearch.Filter = string.Format("(sAMAccountName={0})", i.UniqueName.Split(char.Parse(@"\"))[1]); SearchResult sresult = dssearch.FindOne(); WebClient webClient = new WebClient(); webClient.Credentials = CredentialCache.DefaultNetworkCredentials; if (sresult != null) { string newImage = Path.Combine(exportPath, string.Format("{0}.jpg", i.UniqueName.Replace(@"\", "-"))); if (!File.Exists(newImage)) { DirectoryEntry deUser = new DirectoryEntry(sresult.Path, config.Username, config.Password); Trace.WriteLine(string.Format("{0} [PROCESS] {1}: {2}", current, deUser.Name, newImage)); string empPic = string.Format(config.PictureEmpIDFormat, deUser.Properties["employeeNumber"].Value); try { webClient.DownloadFile(empPic, newImage); } catch (Exception ex) { Trace.WriteLine(string.Format(" [ERROR] {0}", ex.ToString())); } } else { Trace.WriteLine(string.Format("{0} [SKIP] Exists {1}", current, newImage)); } } webClient.Dispose(); } } catch (Exception ex) { Trace.WriteLine(string.Format(" [ERROR] {0}", ex.ToString())); } current--; } ////////////////////////////////////////////////// stopwatch.Stop(); Trace.WriteLine(string.Format(@"DONE in {0:%h} hours {0:%m} minutes {0:s\:fff} seconds", stopwatch.Elapsed)); }
// Retrieve mastery images from ddragon, save locally private void Get_Mastery_Images() { var url = "http://ddragon.leagueoflegends.com/cdn/5.24.2/img/mastery/"; var directory = Directory.GetCurrentDirectory() + "\\masteries"; Version storedVersion; Version currentVersion = new Version(Masteries.version); // New installation runtime stuff; create directory for image files if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } if (!File.Exists(directory + "\\VERSION.txt")) { // Create version file using (var versionFile = File.OpenWrite(directory + "\\VERSION.txt")) { using (var writer = new StreamWriter(versionFile)) { writer.Write(Masteries.version); } } storedVersion = currentVersion; } // Get version number from version file else { using (var versionFile = File.OpenRead(directory + "\\VERSION.txt")) { using (var reader = new StreamReader(versionFile)) { storedVersion = new Version(reader.ReadLine().Trim()); } } } // Download mastery image files foreach (KeyValuePair <string, MasteryDto> mastery in Masteries.data) { string path = directory + "\\" + mastery.Value.id + ".png"; if (File.Exists(path) && storedVersion >= currentVersion) { continue; } var imgUrl = url + mastery.Value.id + ".png"; try { using (WebClient client = new WebClient()) { client.DownloadFile(imgUrl, path); } } catch (Exception e) { Show_Error(e.Message); } } }
static void Main(string[] args) { // set vars string domain = "http://hashcat.net"; string tmpfile = "hashcat.7z"; string url = ""; string pwd = ""; if (args.Length >= 1) { url = args[0]; } if (args.Length >= 2) { pwd = args[1]; } // check 7zip presence if (Run7z("", true) == false) { Console.WriteLine("7z is not in PATH or current directory."); return; } // get web data WebClient wcli = new WebClient(); Console.WriteLine("Downloading website contents..."); string site = wcli.DownloadString(domain + "/hashcat/"); // search for download link Regex cosi = new Regex(@"\/files\/hashcat-[0-9.]*.*\.7z"); Match mac = cosi.Match(site); string soubor = mac.Value; // download the archive if (File.Exists(tmpfile)) { File.Delete(tmpfile); } Console.WriteLine("Downloading 7z archive..."); wcli.DownloadFile(domain + soubor, "hashcat.7z"); cosi = new Regex("hashcat-[0-9]*.[0-9]*"); string rootdir = cosi.Match(soubor).Value; string[] soubory = new string[] { Path.Combine("OpenCL", "*"), "hashcat.hcstat", "hashcat.hctune", "hashcat32.bin", "hashcat32.exe", "hashcat64.bin", "hashcat64.exe" }; for (int i = 0; i < soubory.Length; i++) { soubory[i] = Path.Combine(rootdir, soubory[i]); } // unpack only the required files Console.WriteLine("Extracting from 7z..."); Run7z("x hashcat.7z " + string.Join(" ", soubory)); // delete the archive once unpacked File.Delete("hashcat.7z"); if (Directory.Exists("hashcat")) { Directory.Delete("hashcat"); } Directory.Move(rootdir, "hashcat"); string vysledek = rootdir + ".zip"; if (File.Exists(vysledek)) { File.Delete(vysledek); } // pack the archive to zip Console.WriteLine("Repacking to zip..."); Run7z("a -r -tZip -mx=9 " + vysledek + " " + Path.Combine("hashcat", "*")); // delete the temp dir Directory.Delete("hashcat", true); Console.WriteLine("File " + vysledek + " created."); if (url == "") { Console.Write("Do you want to upload the file to your Hashtopus (y/n)? "); char cont = Console.ReadKey().KeyChar; Console.WriteLine(); if (cont != 'Y' && cont != 'y') { return; } } if (url == "") { Console.Write("Enter your admin.php URL: "); url = Console.ReadLine(); } string obsah = wcli.DownloadString(url); if (!obsah.Contains("<title>Hashtopus")) { Console.WriteLine("Hashtopus admin not found on this URL."); return; } if (pwd == "") { Console.Write("Enter admin password: "******"Content-Type", "application/x-www-form-urlencoded"); NameValueCollection values = new NameValueCollection(); values.Add("pwd", pwd); Console.WriteLine("Logging in..."); byte[] result = wcli.UploadValues(url, "POST", values); obsah = Encoding.UTF8.GetString(result); string kuk = ""; if (obsah.Contains(" name=\"pwd\"")) { Console.WriteLine("Wrong password."); return; } else { kuk = wcli.ResponseHeaders["Set-Cookie"]; kuk = kuk.Substring(0, kuk.IndexOf("; ")); wcli.Headers.Add("Cookie", kuk); } Console.WriteLine("Checking global files..."); obsah = wcli.DownloadString(url + "?a=files"); if (obsah.Contains(">" + vysledek + "</a>")) { Console.WriteLine("File already exists in your Hashtopus system."); return; } Console.WriteLine("Uploading hashcat..."); WebRequest wr = WebRequest.Create(url + "?a=filesp"); wr.Method = "POST"; string bound = "---------------------------hashcat"; wr.ContentType = "multipart/form-data; boundary=" + bound; wr.Headers.Add("Cookie", kuk); bound = "--" + bound; Stream rs = wr.GetRequestStream(); byte[] buf; buf = Encoding.ASCII.GetBytes(string.Format("{0}{1}Content-Disposition: form-data; name=\"source\"{1}{1}upload{1}", bound, Environment.NewLine)); rs.Write(buf, 0, buf.Length); buf = Encoding.ASCII.GetBytes(string.Format("{0}{1}Content-Disposition: form-data; name=\"upfile[]\"; filename=\"{2}\"{1}Content-Type: application/octet-stream{1}{1}", bound, Environment.NewLine, vysledek)); rs.Write(buf, 0, buf.Length); Console.WriteLine("Reading zip file..."); FileStream fs = File.Open(vysledek, FileMode.Open); byte[] fbuf = new byte[4096]; int count = 0; while ((count = fs.Read(fbuf, 0, fbuf.Length)) != 0) { rs.Write(fbuf, 0, count); } fs.Close(); buf = Encoding.ASCII.GetBytes(string.Format("{1}{0}--", bound, Environment.NewLine)); rs.Write(buf, 0, buf.Length); rs.Close(); WebResponse wre = wr.GetResponse(); StreamReader sr = new StreamReader(wre.GetResponseStream()); obsah = sr.ReadToEnd(); if (!obsah.Contains("OK (<a href=\"?a=files#")) { Console.WriteLine("Could not upload file, please upload manually"); return; } string id = obsah.Substring(obsah.IndexOf("?a=files#") + 9); id = id.Substring(0, id.IndexOf("\"")); Console.WriteLine("Creating new release..."); values = new NameValueCollection(); values.Add("file", id); values.Add("version", rootdir.Substring(rootdir.IndexOf("-") + 1)); result = wcli.UploadValues(url + "?a=newreleasep", "POST", values); obsah = Encoding.UTF8.GetString(result); if (obsah.Contains("OK<br>")) { Console.WriteLine("All done."); } else { Console.WriteLine("Could not create release, please create manually."); } }
public async Task MainAsync() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); InitializeDirectories(); StartTime = DateTime.Now; string[] moods = { "Sad", "Meh", "Happy", "Extatic" }; //download content using (var client = new WebClient()) { foreach (string item in moods) { if (!File.Exists($"mood/{item}.png")) { client.DownloadFile($"https://cdn.its-sally.net/content/{item}.png", $"mood/{item}.png"); } if (!File.Exists($"mood/{item}.json")) { client.DownloadFile($"https://cdn.its-sally.net/content/{item}.json", $"mood/{item}.json"); } } } BotConfiguration = JsonConvert.DeserializeObject <BotCredentials>(File.ReadAllText("config/configuration.json")); await DatabaseAccess.InitializeAsync(BotConfiguration.DbUser, BotConfiguration.DbPassword, BotConfiguration.Db, BotConfiguration.DbHost); CredentialManager = new ConfigManager(BotConfiguration); if (!File.Exists("meta/prefix.json")) { File.Create("meta/prefix.json").Dispose(); } //store in database prefixDictionary = new Dictionary <ulong, char>(); prefixDictionary = JsonConvert.DeserializeObject <Dictionary <ulong, char> >(File.ReadAllText("meta/prefix.json")); if (prefixDictionary == null) { prefixDictionary = new Dictionary <ulong, char>(); } if (!File.Exists("ApiRequests.txt")) { // Create a file to write to. using (StreamWriter sw = File.CreateText("ApiRequests.txt")) { sw.WriteLine("0"); sw.Close(); } } RequestCounter = Int32.Parse(File.ReadAllText("ApiRequests.txt")); Client = new DiscordSocketClient(); Client.Ready += Client_Ready; Client.Log += Log; await Client.LoginAsync(TokenType.Bot, BotConfiguration.Token); await Client.StartAsync(); // Block this task until the program is closed. await Task.Delay(-1); }
/// <summary> /// Times and checks that all proteins in the pep.all.fasta protein fasta file are the same as are output by this library /// </summary> private static void SameProteins() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); // download and decompress references string genomeFasta = "Homo_sapiens.GRCh38.dna.primary_assembly.fa"; string geneModelFile = "Homo_sapiens.GRCh38.81.gff3"; string proteinFasta = "Homo_sapiens.GRCh38.pep.all.fa"; string[] gunzippedFiles = new[] { genomeFasta, geneModelFile, proteinFasta }; if (!gunzippedFiles.All(f => File.Exists(f) && new FileInfo(f).Length > 0)) { using (WebClient Client = new WebClient()) { Client.DownloadFile(@"ftp://ftp.ensembl.org/pub/release-81//fasta/homo_sapiens/dna/Homo_sapiens.GRCh38.dna.primary_assembly.fa.gz", "Homo_sapiens.GRCh38.dna.primary_assembly.fa.gz"); Client.DownloadFile(@"ftp://ftp.ensembl.org/pub/release-81/gff3/homo_sapiens/Homo_sapiens.GRCh38.81.gff3.gz", "Homo_sapiens.GRCh38.81.gff3.gz"); Client.DownloadFile(@"ftp://ftp.ensembl.org/pub/release-81//fasta/homo_sapiens/pep/Homo_sapiens.GRCh38.pep.all.fa.gz", "Homo_sapiens.GRCh38.pep.all.fa.gz"); } } foreach (var gunzippedFile in gunzippedFiles) { if (!File.Exists(gunzippedFile) || new FileInfo(gunzippedFile).Length == 0) { using (FileStream stream = new FileStream(gunzippedFile + ".gz", FileMode.Open)) using (GZipStream gunzip = new GZipStream(stream, CompressionMode.Decompress)) using (var f = File.Create(gunzippedFile)) { gunzip.CopyTo(f); } } } GeneModel.GetImportantProteinAccessions(proteinFasta, out Dictionary <string, string> proteinAccessionSequence, out HashSet <string> bad, out Dictionary <string, string> se); Genome genome = new Genome(genomeFasta); GeneModel geneModel = new GeneModel(genome, geneModelFile); List <Protein> geneBasedProteins = geneModel.Translate(true, bad, se); List <Protein> pepDotAll = ProteinDbLoader.LoadProteinFasta(proteinFasta, true, DecoyType.None, false, ProteinDbLoader.EnsemblAccessionRegex, ProteinDbLoader.EnsemblFullNameRegex, ProteinDbLoader.EnsemblFullNameRegex, ProteinDbLoader.EnsemblGeneNameRegex, null, out List <string> errors); Dictionary <string, string> accSeq = geneBasedProteins.ToDictionary(p => p.Accession, p => p.BaseSequence); stopwatch.Stop(); bool allAreEqual = true; foreach (Protein p in pepDotAll) { // now handled with the badAccessions // && !p.BaseSequence.Contains('*') && !seq.Contains('*') && !p.BaseSequence.Contains('X')) if (accSeq.TryGetValue(p.Accession, out string seq)) { if (p.BaseSequence != seq) { allAreEqual = false; break; } } } stopwatch.Stop(); Console.WriteLine("Finished checking that all proteins are the same."); Console.WriteLine("Time elapsed: " + stopwatch.Elapsed.Minutes.ToString() + " minutes and " + stopwatch.Elapsed.Seconds.ToString() + " seconds."); Console.WriteLine("Result: all proteins are " + (allAreEqual ? "" : "not ") + "equal "); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); foreach (var file in Directory.GetFiles(Environment.CurrentDirectory, Path.GetFileNameWithoutExtension(genomeFasta) + "*")) { File.Delete(file); } foreach (var file in Directory.GetFiles(Environment.CurrentDirectory, Path.GetFileNameWithoutExtension(geneModelFile) + "*")) { File.Delete(file); } foreach (var file in Directory.GetFiles(Environment.CurrentDirectory, Path.GetFileNameWithoutExtension(proteinFasta) + "*")) { File.Delete(file); } }
static void Main(string[] args) { // Create standard .NET web client instance WebClient webClient = new WebClient(); // Set API Key webClient.Headers.Add("x-api-key", API_KEY); // Values to fill out pdf fields with built-in pdf form filler var fields = new List <object> { new { fieldName = "topmostSubform[0].Page1[0].FilingStatus[0].c1_01[1]", pages = "1", text = "True" }, new { fieldName = "topmostSubform[0].Page1[0].f1_02[0]", pages = "1", text = "John A." }, new { fieldName = "topmostSubform[0].Page1[0].f1_03[0]", pages = "1", text = "Doe" }, new { fieldName = "topmostSubform[0].Page1[0].YourSocial_ReadOrderControl[0].f1_04[0]", pages = "1", text = "123456789" }, new { fieldName = "topmostSubform[0].Page1[0].YourSocial_ReadOrderControl[0].f1_05[0]", pages = "1", text = "John B." }, new { fieldName = "topmostSubform[0].Page1[0].YourSocial_ReadOrderControl[0].f1_06[0]", pages = "1", text = "Doe" }, new { fieldName = "topmostSubform[0].Page1[0].YourSocial_ReadOrderControl[0].f1_07[0]", pages = "1", text = "987654321" } }; // If enabled, Runs processing asynchronously. Returns Use JobId that you may use with /job/check to check state of the processing (possible states: working, var async = false; // Prepare requests params as JSON // See documentation: https://apidocs.pdf.co Dictionary <string, object> parameters = new Dictionary <string, object>(); parameters.Add("url", SourceFileUrl); parameters.Add("name", FileName); parameters.Add("password", Password); parameters.Add("async", async); parameters.Add("fields", fields); // Convert dictionary of params to JSON string jsonPayload = JsonConvert.SerializeObject(parameters); try { // URL of "PDF Edit" endpoint string url = "https://api.pdf.co/v1/pdf/edit/add"; // Execute POST request with JSON payload string response = webClient.UploadString(url, jsonPayload); // Parse JSON response JObject json = JObject.Parse(response); if (json["error"].ToObject <bool>() == false) { // Get URL of generated PDF file string resultFileUrl = json["url"].ToString(); // Download generated PDF file webClient.DownloadFile(resultFileUrl, DestinationFile); Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile); } else { Console.WriteLine(json["message"].ToString()); } } catch (WebException e) { Console.WriteLine(e.ToString()); } finally { webClient.Dispose(); } Console.WriteLine(); Console.WriteLine("Press any key..."); Console.ReadKey(); }
public static void Main(string[] args) { var finalargs = new List <string>(args); if (!finalargs.Contains("-d")) { finalargs.Add("-d"); finalargs.Add(Directory.GetCurrentDirectory()); } if (!finalargs.Contains("-h")) { finalargs.Add("-h"); finalargs.Add(HOME); } args = finalargs.ToArray(); bool doUpdate = args.Length > 0 && args[0] == "update"; if (!Directory.Exists(HOME) || (doUpdate)) { if (Directory.Exists(HOME)) { Console.Write("Deleting " + HOME); DirectoryDelete(HOME); Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine(" [DONE]"); Console.ResetColor(); } if (args.Length > 1) { Console.Write("Copying " + args[1]); DirectoryCopy(args [1], HOME); Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine(" [DONE]"); Console.ResetColor(); Console.WriteLine("Installed to " + HOME); return; } Console.Write("Downloading " + URL); using (var client = new WebClient()) { client.DownloadFile(URL, ZIP); } Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine(" [DONE]"); Console.ResetColor(); Console.Write("Extracting " + ZIP); using (var unzip = new Unzip(ZIP)) { unzip.ExtractToDirectory(HOME_DIR); } Directory.Move(HOME_ORIG, HOME); File.Delete(ZIP); Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine(" [DONE]"); Console.ResetColor(); Console.WriteLine("Installed to " + HOME); if (doUpdate) { return; } } Assembly.LoadFile(Path.Combine(BOOT, "KopiLua.dll")); Assembly.LoadFile(Path.Combine(BOOT, "Microsoft.Web.XmlTransform.dll")); Assembly.LoadFile(Path.Combine(BOOT, "NLua.dll")); Assembly.LoadFile(Path.Combine(BOOT, "NuGet.Core.dll")); var kaizo = Assembly.LoadFile(Path.Combine(BOOT, "kaizo.exe")); kaizo.GetType("Kaizo.MainClass").GetMethod("Main", BindingFlags.Public | BindingFlags.Static).Invoke(null, new[] { finalargs.ToArray() }); }
void DownloadPage(Int32 Ct) { Int32 Try_Ct = 0; Boolean Is_Error = false; do { Is_Error = false; try { Int32 Page_Ct = Ct + 1; String Url = this.mDownloadPage_Params.Url; String Chapter_Url = this.mDownloadPage_Params.Chapter_Url; String FilePath = this.mDownloadPage_Params.FilePath; String Chapter = this.mDownloadPage_Params.Chapter; String IPEndPoint_IPAdress = this.mDownloadPage_Params.IPAddress_EndPoint; String Html; using (var wc = new Common_Objects.GZipWebClient(IPEndPoint_IPAdress)) { Html = wc.DownloadString(Chapter_Url + "/" + Page_Ct); } HtmlDocument Hd = new HtmlDocument(); Hd.LoadHtml(Html); /* * var Nds = Hd.DocumentNode.SelectNodes("//script/child::text()[contains(.,\"document['pu']\")]"); * var Nd = Nds.FirstOrDefault(); * Regex R = new Regex("document\\['pu'\\] = \'(.)+';"); * var Matches = R.Matches(Nd.InnerText); * R = new Regex("= '(.)+';"); * String Img_Url = R.Matches(Matches[0].Value)[0].Value; * Img_Url = Img_Url.Replace("'", "").Replace(";","").TrimStart('=').TrimStart(' '); */ String Img_Url = ""; var Nds = Hd.DocumentNode.SelectNodes("//div[@id='imgholder']/a/img[@id='img']"); var Nd = Nds.FirstOrDefault(); Img_Url = Nd.Attributes["src"].Value; using (WebClient Wc = new WebClient()) { Uri Uri_Source = new Uri(Url); FileInfo Fi_Source = new FileInfo(Strings.Mid(Img_Url, Strings.InStrRev(Img_Url, @"/") + 1)); FileInfo Fi_Target = new FileInfo(FilePath.TrimEnd('\\') + @"\" + Chapter + @"\" + Fi_Source.Name); if (!Fi_Target.Directory.Exists) { Fi_Target.Directory.Create(); } //Wc.DownloadFile(@"http://" + Uri_Source.Host + @"/" + Img_Path, Fi_Target.FullName); Wc.DownloadFile(Img_Url, Fi_Target.FullName); } } catch (Exception Ex) { Is_Error = true; Try_Ct++; if (Try_Ct > 10) { throw Ex; } } }while (Is_Error); }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { if (!InvokeRequired) { listView1.BeginUpdate(); listView1.Items.Clear(); } else { this.BeginInvoke(new Action(() => listView1.BeginUpdate())); this.BeginInvoke(new Action(() => listView1.Items.Clear())); } string[] seznamArr = Directory.GetFiles(System.Reflection.Assembly.GetEntryAssembly().Location.Replace("Ticketnik.exe", "") + "lang"); try { //File.Copy(Properties.Settings.Default.updateCesta + "\\jazyky.xml", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Ticketnik\\jazyky.xml", true); try { //výchozí cesta v síti if (!Properties.Settings.Default.pouzivatZalozniUpdate) { File.Copy(Properties.Settings.Default.updateCesta + "\\jazyky.xml", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Ticketnik\\jazyky.xml", true); } } catch { //backup download z netu try { WebClient wc = new WebClient(); wc.DownloadFile(Properties.Settings.Default.ZalozniUpdate + "/jazyky.xml", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Ticketnik\\jazyky.xml"); } catch (Exception ee) { form.Logni("Vyhledání aktualizací jazyků selhalo.\r\n" + ee.Message, Form1.LogMessage.WARNING); throw new Exception("Nelze vyhledat žádný update source"); } } XmlDocument jazyky = new XmlDocument(); jazyky.Load(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Ticketnik\\jazyky.xml"); XmlNodeList jazlist = jazyky.SelectNodes("Jazyky/Jazyk"); List <string> seznam = new List <string>(); foreach (string s in seznamArr) { seznam.Add(Path.GetFileName(s)); } foreach (XmlNode jazyk in jazlist) { ListViewItem lvi = new ListViewItem(new string[] { "", jazyk.Attributes["jmeno"].InnerText, jazyk.Attributes["zkratka"].InnerText, jazyk.Attributes["verze"].InnerText + "." + jazyk.Attributes["revize"].InnerText, "" }); lvi.UseItemStyleForSubItems = false; if (form.langVersion <= int.Parse(jazyk.Attributes["verze"].InnerText)) { lvi.ImageIndex = 0; } else if (form.langVersion == int.Parse(jazyk.Attributes["verze"].InnerText) + 1) { lvi.ImageIndex = 1; } else { lvi.ImageIndex = 2; } Tag tag = new Tag(jazyk.Attributes["zkratka"].InnerText + ".xml", false); if (seznam.Contains(jazyk.Attributes["zkratka"].InnerText + ".xml")) { lvi.SubItems[4].BackColor = Color.Green; tag.Instalován = true; } lvi.Tag = tag; if (!InvokeRequired) { listView1.Items.Add(lvi); } else { this.BeginInvoke(new Action(() => listView1.Items.Add(lvi))); } } } catch (Exception ex) { form.Logni("Nelze načíst aktuální seznam jazyků. " + ex.Message, Form1.LogMessage.WARNING); foreach (string s in seznamArr) { XmlDocument jazyk = new XmlDocument(); jazyk.Load(s); ListViewItem lvi = new ListViewItem(new string[] { "", jazyk.SelectSingleNode("Language").Attributes["name"].InnerText, jazyk.SelectSingleNode("Language").Attributes["shortcut"].InnerText, jazyk.SelectSingleNode("Language").Attributes["version"].InnerText + "." + jazyk.SelectSingleNode("Language").Attributes["revision"].InnerText, "" }); lvi.UseItemStyleForSubItems = false; if (form.langVersion <= int.Parse(jazyk.SelectSingleNode("Language").Attributes["version"].InnerText)) { lvi.ImageIndex = 0; } else if (form.langVersion == int.Parse(jazyk.SelectSingleNode("Language").Attributes["version"].InnerText) + 1) { lvi.ImageIndex = 1; } else { lvi.ImageIndex = 2; } lvi.SubItems[4].BackColor = Color.Green; Tag tag = new Tag(jazyk.SelectSingleNode("Language").Attributes["shortcut"].InnerText + ".xml", true); lvi.Tag = tag; if (!InvokeRequired) { listView1.Items.Add(lvi); } else { this.BeginInvoke(new Action(() => listView1.Items.Add(lvi))); } } } if (!InvokeRequired) { listView1.EndUpdate(); pictureBox1.Visible = false; pictureBox1.Dispose(); pictureBox1 = null; } else { this.BeginInvoke(new Action(() => pictureBox1.Visible = false)); this.BeginInvoke(new Action(() => pictureBox1.Dispose())); this.BeginInvoke(new Action(() => pictureBox1 = null)); this.BeginInvoke(new Action(() => listView1.EndUpdate())); } }
/// <summary> /// Download the data from the given starting date to the ending date. /// Note that if the ending date is in the same hour as the current time, /// we will lower the <paramref name="endDateUtc" /> by one hour in order /// to make sure that we only download complete, non-changing dataa /// </summary> /// <param name="startDateUtc">Starting date</param> /// <param name="endDateUtc">Ending date</param> public void Download(DateTime startDateUtc, DateTime endDateUtc) { var now = DateTime.UtcNow; var nowHour = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0); Directory.CreateDirectory(_rawDataDestination); if (startDateUtc < now.AddDays(-15)) { throw new ArgumentException("The starting date can only be at most 15 days from now"); } // Makes sure we only get final, non-changing data by checking if the end date is greater than // or equal to the current time and setting it to an hour before the current time if the condition is met if (nowHour <= new DateTime(endDateUtc.Year, endDateUtc.Month, endDateUtc.Day, endDateUtc.Hour, 0, 0)) { Log.Trace($"PsychSignalDataDownloader.Download(): Adjusting end time from {endDateUtc:yyyy-MM-dd HH:mm:ss} to {nowHour.AddHours(-1):yyyy-MM-dd HH:mm:ss}"); endDateUtc = nowHour.AddHours(-1); } // Get the total amount of hours in order to keep track of progress var totalHours = endDateUtc.Subtract(startDateUtc).TotalHours; var percentage = 1 / totalHours; Log.Trace("PsychSignalDataDownloader.Download(): Begin downloading raw data"); // PsychSignal paginates data by hour. Note that it is possible to retrieve non-complete data if the requested hour // is the same as the current hour or greater than the current hour. for (var i = 1; startDateUtc < endDateUtc; startDateUtc = startDateUtc.AddHours(1), i++) { var rawDataPath = Path.Combine(_rawDataDestination, $"{startDateUtc:yyyyMMdd_HH}.csv"); var rawDataPathTemp = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid().ToString()}.csv.tmp"); // Don't download files we already have if (File.Exists(rawDataPath)) { Log.Trace($"PsychSignalDataDownloader.Download(): File already exists: {rawDataPath}"); continue; } // Retry in case a download failed for (var retries = 0; retries < MaxRetries; retries++) { // Set a max timeout of ten seconds _apiRateGate.WaitToProceed(10000); try { using (var client = new WebClient()) { client.DownloadFile($"{_baseUrl}/replay?apikey={_apiKey}&update=1m&sources={_dataSource}&from={startDateUtc:yyyyMMddHH}&format=csv", rawDataPathTemp); File.Move(rawDataPathTemp, rawDataPath); Log.Trace($"PsychSignalDataDownloader.Download(): Successfully downloaded file: {rawDataPath}"); break; } } catch (WebException e) { var response = (HttpWebResponse)e.Response; if (retries == MaxRetries - 1) { Log.Error($"PsychSignalDataDownloader.Download(): We've reached the maximum number of retries for date {startDateUtc:yyyy-MM-dd HH:00:00}"); continue; } if (response == null) { Log.Error("PsychSignalDataDownloader.Download(): Response was null. Retrying..."); continue; } if (response.StatusCode == HttpStatusCode.BadRequest) { Log.Error("PsychSignalDataDownloader.Download(): Server received a bad request. Continuing..."); break; } if (response.StatusCode == HttpStatusCode.NotFound) { Log.Error("PsychSignalDataDownloader.Download(): Received an HTTP 404. Continuing..."); break; } if (response.StatusCode == (HttpStatusCode)429) { Log.Trace("PsychSignalDataDownloader.Download(): We are being rate limited. Retrying..."); } else { Log.Error($"PsychSignalDataDownloader.Download(): Received unknown HTTP status code {(int) response.StatusCode}. Retrying..."); } } } var complete = i / totalHours; var eta = TimeSpan.FromSeconds((totalHours - i) * 10); Log.Trace($"PsychSignalDataDownloader.Download(): Downloading {complete:P2} complete. ETA is {eta.TotalMinutes:N2} minutes"); } }
static void Main() { using (WebClient webCl = new WebClient()) { try { Console.WriteLine("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."); Console.WriteLine(); webCl.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", "image.jpg"); Console.WriteLine("Download Complete."); } catch (System.Net.WebException) { Console.WriteLine("Error downloading file."); } catch (System.ArgumentException) { Console.WriteLine("Wrong path"); } finally { webCl.Dispose(); } } }