Example #1
0
		private static bool CheckForinternetConnection() 
        {
            //this might be a possible way to check for internet connection, correct if wrong. 
			try 
            {
				using (var client = new WebClient())

                try
                {
					//this will be a test to see if it can establish an internet connection 
					using var stream = client.OpenRead("https://www.google.com") 
                    {
                      
                        {
                            result = (p.Send("8.8.8.8", 15000).Status == IPStatus.Success) ||
                                     (p.Send("8.8.4.4", 15000).Status == IPStatus.Success) ||
                                     (p.Send("4.2.2.1", 15000).Status == IPStatus.Success);
                        }
                    }
                }
                catch
                {
					return false; 
                }

                return result;
            }
        }
Example #2
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();
        //}
    }
    /// <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;
    }
 private static void Main(string[] args)
 {
     if (args.Length != 2) {
       Console.WriteLine("Usage: stacktrace_decoder <info_file_uri> <pdb_file>");
       return;
     }
     string info_file_uri = args[0];
     string pdb_file = args[1];
     var web_client = new WebClient();
     var stream = new StreamReader(web_client.OpenRead(info_file_uri));
     var version_regex = new Regex(
     @"^I.*\] Principia version " +
     @"([0-9]{10}-[A-Za-z]+)-[0-9]+-g([0-9a-f]{40}) built");
     Match version_match;
     do {
       version_match = version_regex.Match(stream.ReadLine());
     } while (!version_match.Success);
     string tag = version_match.Groups[1].ToString();
     string commit = version_match.Groups[2].ToString();
     var base_address_regex = new Regex(@"^I.*\] Base address is ([0-9A-F]+)$");
     string base_address_string =
     base_address_regex.Match(stream.ReadLine()).Groups[1].ToString();
     Int64 base_address = Convert.ToInt64(base_address_string, 16);
     var stack_regex = new Regex(
     @"^\[email protected]\s+[0-9A-F]+\s+\(No symbol\) \[0x([0-9A-F]+)\]");
     Match stack_match;
     do {
       stack_match = stack_regex.Match(stream.ReadLine());
     } while (!stack_match.Success);
     var file_regex = new Regex(
     @"file\s+:\s+.*\\principia\\([a-z_]+)\\([a-z_]+\.[ch]pp)");
     var line_regex = new Regex(@"line\s+:\s+([0-9]+)");
     for (;
      stack_match.Success;
      stack_match = stack_regex.Match(stream.ReadLine())) {
       Int64 address = Convert.ToInt64(stack_match.Groups[1].ToString(), 16);
       Int64 dbh_base_address = 0x1000000;
       string rebased_address =
       Convert.ToString(address - base_address + dbh_base_address, 16);
       var p = new Process();
       p.StartInfo.UseShellExecute = false;
       p.StartInfo.RedirectStandardOutput = true;
       p.StartInfo.FileName = kDBH;
       p.StartInfo.Arguments =
       '"' + pdb_file + "\" laddr \"" + rebased_address + '"';
       p.Start();
       string output = p.StandardOutput.ReadToEnd();
       p.WaitForExit();
       Match file_match = file_regex.Match(output);
       if (file_match.Success) {
     string file = file_match.Groups[1].ToString() + '/' +
           file_match.Groups[2].ToString();
     string line = line_regex.Match(output).Groups[1].ToString();
     string url = "https://github.com/mockingbirdnest/Principia/blob/" +
          commit + '/' + file + "#L" + line;
     Console.WriteLine("[`" + file + ":" + line + "`](" + url + ")");
       }
     }
 }
Example #5
0
public static void Main()
{
WebClient cl = new WebClient();
Stream str = cl.OpenRead("http://www.google.com");
StreamReader read = new StreamReader(str);
Console.WriteLine(read.ReadToEnd());
str.Close();

}
Example #6
0
    private static String getPage(String url)
    {
        using(WebClient cl = new WebClient())
        using(Stream data = cl.OpenRead(url))
        using(StreamReader r = new StreamReader(data))
        {
            return r.ReadToEnd();
        }

        
    }
Example #7
0
 public static bool CheckForInternetConnection()
 {
     try
     {
         using (var client = new WebClient())
         using (var stream = client.OpenRead("http://www.google.com"))
         {
             return true;
         }
     }
     catch
     {
         return false;
     }
 }
 static void Main()
 {
     using (WebClient download = new WebClient())
     {
         try
         {
             download.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", "../../AC.jpg");
             download.OpenRead("http://www.devbg.org/img/Logo-BASD.jpg");
         }
         catch (Exception Ex)
         {
             Console.WriteLine("invalid address!",Ex.Data);
         }
     }
 }
Example #9
0
    /// <summary>
    /// 读取网页内容
    /// </summary>
    /// <returns></returns>
    public static string ReadHtml()
    {
        WebClient client = new WebClient();
        Stream strm = client.OpenRead("http://www.baidu.com");
        StreamReader sr = new StreamReader(strm);
        string line = string.Empty;
        string message = string.Empty;

        while ((line = sr.ReadLine()) != null)
        {
            message += line;
        }
        strm.Close();
        return message;
    }
Example #10
0
    static void SendMessageWithHttpStream(IBus bus)
    {
        #region send-message-with-http-stream

        using (WebClient webClient = new WebClient())
        {
            MessageWithStream message = new MessageWithStream
            {
                SomeProperty = "This message contains a stream",
                StreamProperty = webClient.OpenRead("http://www.particular.net")
            };
            bus.Send("Sample.PipelineStream.Receiver", message);
        }
        #endregion

        Console.WriteLine();
        Console.WriteLine("Message with http stream sent");
    }
Example #11
0
 public static string API(string API)
 {
     try
     {
         WebClient Client = new WebClient();
         string baseurl = API;
         Stream data = Client.OpenRead(baseurl);
         StreamReader reader = new StreamReader(data);
         string s = reader.ReadToEnd();
         data.Close();
         reader.Close();
         return s;
     }
     catch (Exception ex)
     {
         return ex.Message.ToString();
     }
 }
Example #12
0
 public static void Main(String [] args)
 {
     WebClient client = new WebClient();
     client.BaseAddress = args[0];
     client.DownloadFile(args[1], args[2]);
     StreamReader input =
          new StreamReader(client.OpenRead(args[1]));
     Console.WriteLine(input.ReadToEnd());
     Console.WriteLine
       ("Request header count: {0}", client.Headers.Count);
     WebHeaderCollection header = client.ResponseHeaders;
     Console.WriteLine
       ("Response header count: {0}", header.Count);
     for (int i = 0; i < header.Count; i++)
       Console.WriteLine("   {0} : {1}",
                       header.GetKey(i), header[i]);
     input.Close();
 }
 public string GetLocation()
 {
     string wholePage = string.Empty;
     try
     {
         using (WebClient webClient = new WebClient())
         {
             Stream stream = webClient.OpenRead("https://freegeoip.net/json/");
             StreamReader streamReader = new StreamReader(stream);
             wholePage = streamReader.ReadToEnd();
             streamReader.Close();
             stream.Close();
         }
         return wholePage;
     }
     catch(Exception e)
     {
         return e.ToString();
     }
 }
    static void Main()
    {
        using (WebClient client = new WebClient())
        {
            try
            {
                // Reads some file address in Internet
                Console.WriteLine("Please, enter some file address in Internet: ");
                Console.ForegroundColor = ConsoleColor.Yellow;
                string uri = Console.ReadLine();
                Console.ResetColor();

                // Takes the name of the file
                Match filename = Regex.Match(uri, @"[^\/]+\.\w+$");

                // Checks the size of the file before to be downloaded
                client.OpenRead(uri);
                Int64 bytes = Convert.ToInt64(client.ResponseHeaders["Content-Length"]);
                Console.Write("\nThe size of the file is " + bytes.ToString() + " Bytes. Press <Enter> to start downloading");
                Console.ReadLine();

                // Downloads the file
                client.DownloadFile(uri, filename.ToString());
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("The file is successfully downloaded!");
                Console.ResetColor();
            }
            catch (WebException)
            {
                Error("File not found!");
            }
            catch (ArgumentException)
            {
                Error("The path is not of a legal form!");
            }
            catch (PathTooLongException)
            {
                Error("The specified path, file name, or both are too long!");
            }
        }
    }
    public string ReadFile()
    {
        String fileUrl = "http://marketinvoice.looker.com/looks/XN9ChdBFx4KMSBTMPzQK6P6k6p9FJGWv.txt";

        WebClient client = new WebClient();
        Stream data = client.OpenRead(fileUrl);

        StreamReader reader = new StreamReader(data);
        string text = reader.ReadToEnd();
        string[] contentCollection = text.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
        int length = contentCollection.Length;
        string result = "[ ";

        /** Headers **/
        string[] headers = new string[] { };
        int count = 0;
        string firstLine = contentCollection[0];
        if (firstLine != null)
        {
            headers = firstLine.Replace(" ", "").Replace("%", "Percent").Replace("(", "").Replace(")", "").Split('\t');
            count = headers.Length;
        }
        /** Values **/
        string[] row = new string[] { };
        for (int countLines = 1; countLines < length; countLines++)
        {
            row = contentCollection[countLines].Split('\t');
            result += "{";
            for (int countValues = 0; countValues < count; countValues++)
            {
                result += String.Format("{0}: \"{1}\", ", headers[countValues], row[countValues]);
            }
            result += "}, ";
        }

        result = result.Replace(@"\", "");
        result = result.Remove(result.Length - 1);
        result += "]";

        return result;
    }
 private void maxWins()
 {
     try
     {
         using (var client = new WebClient())
         {
             Stream stream = client.OpenRead("http://www.google.com");
             StreamReader reader = new StreamReader(stream);
             string response = reader.ReadToEnd();
             Debug.Log(response);
         }
     }
     catch (System.InvalidOperationException e)
     {
         if (e is WebException)
         {
             Debug.Log(e.Message);
             //Debug.Log (e.StackTrace);
             Debug.Log(e.GetBaseException());
         }
     }
 }
Example #17
0
    /// <summary>
    /// Extracts the single task data all.
    /// this method extracts all task data from job page 
    /// </summary>
    /// <param name="url">job page such as (base url + jobnumber)</param>
    /// <param name="jobnumber">Jobnumber. </param>
    public void extractSingleTaskDataAll(string url, int jobnumber)
    {
        try {

            WebClient client = new WebClient ();
            //html = client.DownloadString (pageUrl);

            Stream st = client.OpenRead (url);
            Encoding encode = Encoding.GetEncoding ("utf-8");
            StreamReader sr = new StreamReader (st, encode);
            string html = sr.ReadToEnd ();
            sr.Close ();
            st.Close ();

            extractJobData (html);
            insertToDatabase (extractJobData (html), extractAllTableRows (url), jobnumber);

        } catch (WebException e) {
            Debug.Log (e.ToString ());
            return;
        }
    }
    private void SavePicnikPhoto(Member member, Photo photo, String picnikPhotoUrl)
    {
        Debug.Assert(member != null, "member != null");
        Debug.Assert(photo != null, "photo != null");
        Debug.Assert(!String.IsNullOrEmpty(picnikPhotoUrl), "!String.IsNullOrEmpty(picnikPhotoUrl)");

        using (var client = new WebClient())
        using (var stream = client.OpenRead(picnikPhotoUrl))
        using (var largeImage = Image.FromStream(stream))
        {
            using (var mediumImage = Photo.Resize480x480(largeImage))
            {
                Photo.SaveToDiskRelativePath(mediumImage, GetMediumFullPath(member, photo));
            }

            using (var thumbImage = Photo.ResizeTo124x91(largeImage))
            {
                Photo.SaveToDiskRelativePath(thumbImage, GetThumbFullPath(member, photo));
            }

            Photo.SaveToDiskRelativePath(largeImage, GetLargeFullPath(member, photo));
        }
    }
Example #19
0
    /// <summary>
    /// Prepare Dictionary with requests for CSS validation
    /// </summary>
    /// <param name="parameter">Asynchronous parameter containing current url data to resolve absolute URL </param>
    private Dictionary<string, string> GetValidationRequests(string parameter)
    {
        string html = GetHtml(Url);
        Dictionary<string, string> cssRequests = null;
        string[] urlParams = parameter.Split(';');

        if (!String.IsNullOrEmpty(html))
        {
            cssRequests = new Dictionary<string, string>();

            // Get inline CSS
            AddLog(GetString("validation.css.preparinginline"));
            StringBuilder sbInline = new StringBuilder();
            foreach (Match m in InlineStylesRegex.Matches(html))
            {
                string captured = m.Groups["css"].Value;
                sbInline.Append(captured);
                sbInline.Append("\n");
            }

            cssRequests.Add(DocumentValidationHelper.InlineCSSSource, sbInline.ToString());

            // Get linked styles URLs
            WebClient client = new WebClient();
            foreach (Match m in LinkedStylesRegex.Matches(html))
            {
                string url = m.Groups["url"].Value;
                url = Server.HtmlDecode(url);

                string css = null;
                if (!String.IsNullOrEmpty(url))
                {
                    bool processCss = true;
                    string[] excludedCsss = mExcludedCSS.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                    // Check if CSS is not excluded (CMS stylesheets)
                    foreach (string excludedCss in excludedCsss)
                    {
                        if (url.EndsWith(excludedCss, StringComparison.InvariantCultureIgnoreCase))
                        {
                            processCss = false;
                            break;
                        }
                    }

                    if (processCss && !cssRequests.ContainsKey(url))
                    {
                        AddLog(String.Format(GetString("validation.css.preparinglinkedstyles"), url));

                        try
                        {
                            // Get CSS data from URL
                            StreamReader reader = StreamReader.New(client.OpenRead(DocumentValidationHelper.DisableMinificationOnUrl(URLHelper.GetAbsoluteUrl(url, urlParams[0], urlParams[1], urlParams[2]))));
                            css = reader.ReadToEnd();
                            if (!String.IsNullOrEmpty(css))
                            {
                                cssRequests.Add(url, css.Trim(new char[] { '\r', '\n' }));
                            }
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }

        return cssRequests;
    }
Example #20
0
 public static string GetHtmlFrom(string url)
 {
     var wc = new WebClient();
     var resStream = wc.OpenRead(url);
     if (resStream != null)
     {
         var sr = new StreamReader(resStream, System.Text.Encoding.Default);
         return sr.ReadToEnd();
     }
     return "null";
 }
Example #21
0
    public static string GetOriginalLink(string url)
    {
        using (WebClient client = new WebClient())
        {

            using (Stream stream = client.OpenRead(url))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    string content = reader.ReadToEnd();
                    int startindex = content.IndexOf("RD_PARM1") ;
                    if ( startindex > 0)
                    {
                        content = content.Substring(startindex + 9);
                        int endIndex = content.IndexOf("&amp;");
                        return content.Substring(0, endIndex);
                    }
                }
            }
        }
        return null;
    }
Example #22
0
 public static string SendSMSNEW(string API, string mobile)
 {
     try
     {
         WebClient Client = new WebClient();
         string baseurl = API;
         Stream data = Client.OpenRead(baseurl);
         StreamReader reader = new StreamReader(data);
         string s = reader.ReadToEnd();
         data.Close();
         reader.Close();
         insertDATA(s, mobile);
         return s;
     }
     catch (Exception ex)
     {
         insertDATA(ex.Message.ToString(), mobile);
         return ex.Message.ToString();
     }
 }
Example #23
0
 private static byte[] getUrlBinary(string url)
 {
     WebClient client = new WebClient();
     client.Headers["Accept-Language"] = "en";
     Stream datastream = client.OpenRead(url);
     MemoryStream bin = new MemoryStream();
     datastream.CopyTo(bin);
     return bin.ToArray();
 }
 /// <summary>
 /// Fires specific action and returns result provided by the parent control.
 /// </summary>
 /// <param name="dr">Data related to the action.</param>
 private string GetHtml(string url)
 {
     if (UseServerRequestType)
     {
         // Create web client and try to obatin HTML using it
         WebClient client = new WebClient();
         try
         {
             StreamReader reader = StreamReader.New(client.OpenRead(url));
             return reader.ReadToEnd();
         }
         catch
         {
             return null;
         }
     }
     else
     {
         // Get HTML stored using javascript
         return HttpUtility.UrlDecode(hdnHTML.Value);
     }
 }
Example #25
0
 /// <summary>
 /// Get HTML code using server or client method
 /// </summary>
 /// <param name="url">URL to obtain HTML from</param>
 private string GetHtml(string url)
 {
     if (UseServerRequestType)
     {
         // Create web client and try to obatin HTML using it
         WebClient client = new WebClient();
         try
         {
             StreamReader reader = StreamReader.New(client.OpenRead(url));
             return reader.ReadToEnd();
         }
         catch (Exception e)
         {
             lblError.Text = String.Format(ResHelper.GetString("validation.exception"), e.Message);
             lblError.Visible = true;
             return null;
         }
     }
     else
     {
         // Get HTML stored using javascript
         return ValidationHelper.Base64Decode(hdnHTML.Value);
     }
 }
    private XmlDocument RetrieveXml(string URLString)
    {
        WebClient webClient = new WebClient();
        webClient.Credentials = new System.Net.NetworkCredential(API_KEY, API_PASSWORD);
        XmlDocument xml = new XmlDocument();

        using (XmlTextReader xmlTextReader = new XmlTextReader(webClient.OpenRead(URLString))) {
            while (xmlTextReader.Read()) {
                xml.Load(xmlTextReader);
                xmlTextReader.Close();
            }
        }

        return xml;
    }
    //---------------------------------------------------------
    private string GetWebClientData(string targetUrl)
    {
        //Cmn.Log.WriteToFile("targetUrl", targetUrl);
        string _retVal = "";
        WebClient _webClient = new WebClient();

        //增加SessionID,为了解决当前用户登录问题
           // Cmn.Session.SetUserID("kdkkk"); //随便设置一个session 否则SessionID会变
        Cmn.Session.Set("cmn_ItfProxy_tmp","test");

        targetUrl = Cmn.Func.AddParamToUrl(targetUrl, "CurSessionID=" + Session.SessionID);

        Cmn.Log.WriteToFile("targetUrl", targetUrl);

        if (Request.Form.Count > 0) { //post方式
            string _postString = "";

            for (int _i = 0; _i < Request.Form.Count; _i++) {
                if (_postString != "") { _postString += "&"; }

                _postString += Request.Form.Keys[_i] + "=" + System.Web.HttpUtility.UrlEncode(Request.Form[_i].ToString(), Encoding.UTF8);
            }

            byte[] _postData = Encoding.GetEncoding("utf-8").GetBytes(_postString);
            _webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            byte[] _responseData = _webClient.UploadData(targetUrl, "POST", _postData);//得到返回字符流
            _retVal = Encoding.GetEncoding("utf-8").GetString(_responseData);//解码
        }
        else {
            Stream _stream = _webClient.OpenRead(targetUrl);

            StreamReader _rd = new StreamReader(_stream, Encoding.GetEncoding("utf-8"));
            _retVal = _rd.ReadToEnd();

            _stream.Close();

        }

        return _retVal;
    }
Example #28
0
 protected override Task<Stream> OpenReadAsync(WebClient wc, string address) => Task.Run(() => wc.OpenRead(address));
Example #29
0
        public static void OpenRead_InvalidArguments_ThrowExceptions()
        {
            var wc = new WebClient();

            Assert.Throws<ArgumentNullException>("address", () => { wc.OpenRead((string)null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.OpenRead((Uri)null); });
        }
Example #30
-1
    public static string ExecuteGetCommand(string url)
    {
        System.Net.ServicePointManager.Expect100Continue = false;
        using (WebClient client = new WebClient())
        {

            try
            {
                using (Stream stream = client.OpenRead(url))
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
            catch (WebException ex)
            {
                //
                // Handle HTTP 404 errors gracefully and return a null string to indicate there is no content.
                //
                if (ex.Response is HttpWebResponse)
                {
                    if ((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.NotFound)
                    {
                        return null;
                    }
                }

                //throw ex;
            }
        }

        return null;
    }