public List <Satellite> GetSatellites(string[] Norad) { string predicateValues = "/class/tle_latest/ORDINAL/1/NORAD_CAT_ID/" + string.Join(",", Norad) + "/orderby/NORAD_CAT_ID%20ASC/format/3le"; string request = uriBase + requestController + requestAction + predicateValues; // Create new WebClient object to communicate with the service using (var client = new WebClientEx()) { if (Auth(client)) { var response4 = client.DownloadData(request); var stringData = (System.Text.Encoding.Default.GetString(response4)).Split('\n'); List <Satellite> result = new List <Satellite>(); for (Int32 i = 0; i < stringData.Length - 1; i += 3) { Tle tle = new Tle(stringData[i], stringData[i + 1], stringData[i + 2]); Satellite sat = new Satellite(tle); result.Add(sat); OnProgress(new ProgressEventArgs(i, stringData.Length - 1)); } return(result); } else { throw new NoAuthException(); } } }
public List <Satellite> GetSatellites(string LanuchYaer) { string predicateValues = "/class/tle_latest/LAUNCH_YEAR/=" + LanuchYaer + "/orderby/INTLDES asc/metadata/false"; string request = uriBase + requestController + requestAction + predicateValues; // Create new WebClient object to communicate with the service using (var client = new WebClientEx()) { if (Auth(client)) { var response4 = client.DownloadData(request); var stringData = (System.Text.Encoding.Default.GetString(response4)).Split('\n'); List <Satellite> result = new List <Satellite>(); for (Int32 i = 0; i < stringData.Length - 1; i += 3) { Tle tle = new Tle(stringData[i], stringData[i + 1], stringData[i + 2]); Satellite sat = new Satellite(tle); result.Add(sat); OnProgress(new ProgressEventArgs(i, stringData.Length - 1)); } return(result); } else { throw new NoAuthException(); } } }
public static string GetSpaceTrack(string[] noradId, string username, string password) { string uriBase = "https://www.space-track.org"; string requestController = "/basicspacedata"; string requestAction = "/query"; string predicateValues = "/class/tle_latest/ORDINAL/1/NORAD_CAT_ID/" + string.Join(",", noradId) + "/orderby/NORAD_CAT_ID/format/3le"; string request = uriBase + requestController + requestAction + predicateValues; // Create new WebClient object to communicate with the service using (var client = new WebClientEx()) { // Store the user authentication information var data = new NameValueCollection { { "identity", username }, { "password", password }, }; // Generate the URL for the API Query and return the response var response2 = client.UploadValues(uriBase + "/ajaxauth/login", data); var response4 = client.DownloadData(request); return (System.Text.Encoding.Default.GetString(response4)); } }
public static void Initialize() { ImageLoader.RegisterSpecialResolverTable("pixiv", uri => { try { var builder = new UriBuilder(uri) { Scheme = "http" }; uri = builder.Uri; using (var wc = new WebClientEx()) { wc.CookieContainer = new CookieContainer(); var src = wc.DownloadString(uri); var match = PixivRegex.Match(src); if (match.Success) { wc.Referer = uri.OriginalString; return(wc.DownloadData(match.Groups[1].Value)); } } } catch (Exception) { // ignored } return(new byte[0]); }); }
public DhtManager(int localServicePort, IDhtConnectionManager connectionManager, NetProxy proxy, IEnumerable <EndPoint> ipv4BootstrapNodes, IEnumerable <EndPoint> ipv6BootstrapNodes, IEnumerable <EndPoint> torBootstrapNodes, string torOnionAddress, bool enableTorMode) { _localServicePort = localServicePort; //init internet dht nodes _ipv4InternetDhtNode = new DhtNode(connectionManager, new IPEndPoint(IPAddress.Any, localServicePort)); _ipv6InternetDhtNode = new DhtNode(connectionManager, new IPEndPoint(IPAddress.IPv6Any, localServicePort)); //add known bootstrap nodes _ipv4InternetDhtNode.AddNode(ipv4BootstrapNodes); _ipv6InternetDhtNode.AddNode(ipv6BootstrapNodes); if (enableTorMode) { //init tor dht node _torInternetDhtNode = new DhtNode(connectionManager, new DomainEndPoint(torOnionAddress, localServicePort)); //add known bootstrap nodes _torInternetDhtNode.AddNode(torBootstrapNodes); //set higher timeout value for internet and tor DHT nodes since they will be using tor network _ipv4InternetDhtNode.QueryTimeout = 10000; _ipv6InternetDhtNode.QueryTimeout = 10000; _torInternetDhtNode.QueryTimeout = 10000; } else { //start network watcher _networkWatcher = new Timer(NetworkWatcherAsync, null, 1000, NETWORK_WATCHER_INTERVAL); } //add bootstrap nodes via web _bootstrapRetryTimer = new Timer(delegate(object state) { try { using (WebClientEx wC = new WebClientEx()) { wC.Proxy = proxy; wC.Timeout = 10000; using (BinaryReader bR = new BinaryReader(new MemoryStream(wC.DownloadData(DHT_BOOTSTRAP_URL)))) { int count = bR.ReadByte(); for (int i = 0; i < count; i++) { AddNode(EndPointExtension.Parse(bR)); } } } //bootstrap success, stop retry timer _bootstrapRetryTimer.Dispose(); } catch (Exception ex) { Debug.Write(this.GetType().Name, ex); } }, null, BOOTSTRAP_RETRY_TIMER_INITIAL_INTERVAL, BOOTSTRAP_RETRY_TIMER_INTERVAL); }
} // END WebClient Class public static string GetSpaceTrack(string[] noradId, string username, string password) { string uriBase = "https://www.space-track.org"; string requestController = "/basicspacedata"; string requestAction = "/query"; string predicateValues = "/class/tle_latest/ORDINAL/1/NORAD_CAT_ID/" + string.Join(",", noradId) + "/orderby/NORAD_CAT_ID/format/3le"; string request = uriBase + requestController + requestAction + predicateValues; // Create new WebClient object to communicate with the service using (var client = new WebClientEx()) { // Store the user authentication information var data = new NameValueCollection { { "identity", username }, { "password", password }, }; // Generate the URL for the API Query and return the response var response2 = client.UploadValues(uriBase + "/ajaxauth/login", data); var response4 = client.DownloadData(request); return(System.Text.Encoding.Default.GetString(response4)); } }
private bool DoWebCheckIncomingConnection(int externalPort) { bool _webCheckError = false; bool _webCheckSuccess = false; try { using (WebClientEx client = new WebClientEx()) { client.Proxy = _profile.Proxy; client.QueryString.Add("port", externalPort.ToString()); client.Timeout = 30000; using (MemoryStream mS = new MemoryStream(client.DownloadData(CONNECTIVITY_CHECK_WEB_SERVICE))) { _webCheckError = false; _webCheckSuccess = (mS.ReadByte() == 1); switch (mS.ReadByte()) { case 1: //ipv4 { byte[] ipv4 = new byte[4]; byte[] port = new byte[2]; mS.Read(ipv4, 0, 4); mS.Read(port, 0, 2); _connectivityCheckExternalEP = new IPEndPoint(new IPAddress(ipv4), BitConverter.ToUInt16(port, 0)); } break; case 2: //ipv6 { byte[] ipv6 = new byte[16]; byte[] port = new byte[2]; mS.Read(ipv6, 0, 16); mS.Read(port, 0, 2); _connectivityCheckExternalEP = new IPEndPoint(new IPAddress(ipv6), BitConverter.ToUInt16(port, 0)); } break; default: _connectivityCheckExternalEP = null; break; } } } } catch { _webCheckError = true; _webCheckSuccess = false; _connectivityCheckExternalEP = null; } return(_webCheckSuccess || _webCheckError); }
public static bool IsRevoked(Certificate certToCheck, out RevocationCertificate revokeCert, NetProxy proxy = null, int timeout = 10000) { if (certToCheck.RevocationURL == null) { throw new CryptoException("Certificate does not support revocation."); } using (WebClientEx client = new WebClientEx()) { client.Proxy = proxy; client.Timeout = timeout; byte[] buffer = client.DownloadData(certToCheck.RevocationURL.AbsoluteUri + "?sn=" + certToCheck.SerialNumber); using (MemoryStream mS = new MemoryStream(buffer)) { switch (mS.ReadByte()) { case 0: //not found revokeCert = null; return(false); case 1: revokeCert = new RevocationCertificate(mS); break; default: throw new CryptoException("RevokedCertificate version not supported."); } } return(revokeCert.IsValid(certToCheck)); } }
public void DownloadSignedCertificate(Uri apiUri) { using (WebClientEx client = new WebClientEx()) { client.Proxy = _proxy; client.UserAgent = GetUserAgent(); byte[] data = client.DownloadData(apiUri.AbsoluteUri + "?cmd=dlc&email=" + _localCertStore.Certificate.IssuedTo.EmailAddress.Address); using (BinaryReader bR = new BinaryReader(new MemoryStream(data))) { int errorCode = bR.ReadInt32(); if (errorCode != 0) { string message = Encoding.UTF8.GetString(bR.ReadBytes(bR.ReadInt32())); string remoteStackTrace = Encoding.UTF8.GetString(bR.ReadBytes(bR.ReadInt32())); throw new BitChatException(message); } Certificate cert = new Certificate(bR.BaseStream); if (!cert.IssuedTo.EmailAddress.Equals(_localCertStore.Certificate.IssuedTo.EmailAddress) || (cert.PublicKeyEncryptionAlgorithm != _localCertStore.PrivateKey.Algorithm) || (cert.PublicKeyXML != _localCertStore.PrivateKey.GetPublicKey())) { throw new BitChatException("Invalid signed certificate received. Please try again."); } _localCertStore = new CertificateStore(cert, _localCertStore.PrivateKey); } } }
} // END WebClient Class // Get the TLEs based of an array of NORAD CAT IDs, start date, and end date public string GetSpaceTrack(string[] norad, DateTime dtstart, DateTime dtend) { string uriBase = "https://www.space-track.org"; string requestController = "/basicspacedata"; string requestAction = "/query"; // URL to retrieve all the latest tle's for the provided NORAD CAT // IDs for the provided Dates //string predicateValues = "/class/tle_latest/ORDINAL/1/NORAD_CAT_ID/" + string.Join(",", norad) + "/orderby/NORAD_CAT_ID%20ASC/format/tle"; // URL to retrieve all the latest 3le's for the provided NORAD CAT // IDs for the provided Dates string predicateValues = "/class/tle/EPOCH/" + dtstart.ToString("yyyy-MM-dd--") + dtend.ToString("yyyy-MM-dd") + "/NORAD_CAT_ID/" + string.Join(",", norad) + "/orderby/NORAD_CAT_ID%20ASC/format/3le"; string request = uriBase + requestController + requestAction + predicateValues; // Create new WebClient object to communicate with the service using (var client = new WebClientEx()) { // Store the user authentication information var data = new NameValueCollection { { "identity", "myUserName" }, { "password", "myPassword" }, }; // Generate the URL for the API Query and return the response var response2 = client.UploadValues(uriBase + "/ajaxauth/login", data); var response4 = client.DownloadData(request); return(System.Text.Encoding.Default.GetString(response4)); } } // END GetSpaceTrack()
public TestResultBase Test(Options o) { var res = new GenericTestResult { ShortDescription = "Sanity light check", Status = TestResult.INCONCLUSIVE }; try { WebClientEx webClient = SetupWebClient(o); string responseData = Encoding.UTF8.GetString(webClient.DownloadData(o.Url + RelativeUrl)); if (responseData == "[]" || webClient.StatusCode == HttpStatusCode.NoContent) { res.Status = TestResult.INCONCLUSIVE; res.ExtraInformation = "NO DATA at " + RelativeUrl; return(res); } var responseObj = ServiceStack.Text.JsonSerializer.DeserializeFromString(responseData, TypeToDeserialize); // check if response is ok according to the handler res.Status = CheckValidDataInsideFunctionHandler(responseObj) ? TestResult.OK : TestResult.FAIL; } catch (Exception ex) { res.Status = TestResult.FAIL; res.CauseOfFailure = ex.Message; } finally { res.ExtraInformation += " Url: " + RelativeUrl; } return(res); }
private static Stream GetStreamFromUrl(string url) { if (string.IsNullOrEmpty(url)) { return(null); } if (url.StartsWith("//")) { url = "http:" + url; } if (!Uri.IsWellFormedUriString(url, UriKind.Absolute)) { return(new MemoryStream()); } byte[] imageData = null; try { using (var wc = new WebClientEx()) imageData = wc.DownloadData(url); } catch { return(null); } return(new MemoryStream(imageData)); }
private bool CheckUrlContent() { bool isok = true; System.Threading.Thread.Sleep(1000); try { var webClient = new WebClientEx(); foreach (var checkUrl in CheckUrls) { webClient.ResetHeaders(); if (string.IsNullOrEmpty(checkUrl.ContainString)) { webClient.DownloadData(checkUrl.Url); } else { var str = webClient.DownloadString(checkUrl.Url); if (str.Contains(checkUrl.ContainString) == false) { isok = false; break; } } } } catch (Exception e) { isok = false; } return(isok); }
public static byte[] DownloadSymbols() { using (var client = new WebClientEx { Timeout = TimeSpan.FromMinutes(3), DecompressionMethods = DecompressionMethods.Deflate | DecompressionMethods.GZip }) { return client.DownloadData("http://www.dtniq.com/product/mktsymbols_v2.zip"); } }
public static byte[] DownloadSymbols() { using (var client = new WebClientEx { Timeout = TimeSpan.FromMinutes(3), DecompressionMethods = DecompressionMethods.Deflate | DecompressionMethods.GZip }) { return(client.DownloadData("http://www.dtniq.com/product/mktsymbols_v2.zip")); } }
public WebDatabase(Uri webDatabaseUri, string sharedSecret) { _webDatabaseUri = webDatabaseUri; _webClient = new WebClientEx(); //get server challenge byte[] challenge; _webClient.QueryString.Add("cmd", "challenge"); using (BinaryReader bR = new BinaryReader(new MemoryStream(_webClient.DownloadData(_webDatabaseUri)))) { int errorCode = bR.ReadInt32(); if (errorCode != 0) { string message = Encoding.UTF8.GetString(bR.ReadBytes(bR.ReadInt32())); string remoteStackTrace = Encoding.UTF8.GetString(bR.ReadBytes(bR.ReadInt32())); throw new WebDatabaseException(message, errorCode, remoteStackTrace); } challenge = bR.ReadBytes(32); } //authenticate _webClient.QueryString.Clear(); _webClient.QueryString.Add("cmd", "login"); using (HMAC hmac = new HMACSHA256(Encoding.UTF8.GetBytes(sharedSecret))) { _webClient.QueryString.Add("code", BitConverter.ToString(hmac.ComputeHash(challenge)).Replace("-", "").ToLower()); } using (BinaryReader bR = new BinaryReader(new MemoryStream(_webClient.DownloadData(_webDatabaseUri)))) { int errorCode = bR.ReadInt32(); if (errorCode != 0) { string message = Encoding.UTF8.GetString(bR.ReadBytes(bR.ReadInt32())); string remoteStackTrace = Encoding.UTF8.GetString(bR.ReadBytes(bR.ReadInt32())); throw new WebDatabaseException(message, errorCode, remoteStackTrace); } } }
private static bool DownloadAndSaveIntoResources(CsvOnlineSource csvOnlineSource, string directoryPath = "Assets/Resources/") { Debug.Log("Downloading " + csvOnlineSource + " as csv."); if (csvOnlineSource == null) { Debug.LogError("Trying to download the file of a 'null' csvOnlineSource"); return(false); } /* * INSTRUCTIONS: * In your Google Spread, go to: File > Publish to the Web > Link > CSV * You'll be given a link. Put that link into a WWW request and the text you get back will be your data in CSV form. * // Example URL * //string url = @"https://docs.google.com/spreadsheets/d/e/2PACX-1vQGs31fwKF9vuUg9uUOvgN8Jr7bVSQvDILQEMPk6xiKkzk3PDYosuOPMhd0FjrnKPzLkMA998tnZfGN/pub?output=csv"; //Published to the web */ WebClientEx wc = new WebClientEx(new CookieContainer()); wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0"); wc.Headers.Add("DNT", "1"); wc.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); wc.Headers.Add("Accept-Encoding", "deflate"); wc.Headers.Add("Accept-Language", "en-US,en;q=0.5"); wc.Headers.Add("Cache-Control", "no-cache"); wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore); if (string.IsNullOrEmpty(csvOnlineSource.url)) { Debug.LogError("The file referenced with the csvOnlineSource " + csvOnlineSource + " can not be downloaded because the 'url' is not valid."); return(false); } byte[] dt = wc.DownloadData(csvOnlineSource.url); if (dt.Length <= 0) { Debug.LogError("The downloaded data for the csvOnlineSource " + csvOnlineSource + " is empty."); return(false); } if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } File.WriteAllBytes(directoryPath + csvOnlineSource.downloadedFileName + ".csv", dt); //To convert it to string... //var outputCSVdata = System.Text.Encoding.UTF8.GetString(dt ?? new byte[] { }); Debug.Log(csvOnlineSource + " file has been downloaded successfully."); return(true); }
public static string WebClientGet(string gethost) { WebClientEx webClient = new WebClientEx { Timeout = 3000 }; byte[] result = webClient.DownloadData(gethost); return(Encoding.UTF8.GetString(result)); }
private static ResourceResult CheckResource() { var fileInfo = new FileInfo(ResourcePath); if (!fileInfo.Exists) { return(ResourceResult.NeedToDownload); } try { using (var wc = new WebClientEx()) { // 파일 사이즈 비교 wc.Method = "HEAD"; wc.DownloadData(ResourceUrl); if (fileInfo.Length != wc.ContentLength) { return(ResourceResult.NeedToDownload); } if (fileInfo.Exists) { // 파일 해싱 비교 string hashCurrent, hashRemote; using (var md5 = MD5.Create()) using (var file = File.OpenRead(ResourcePath)) hashCurrent = BitConverter.ToString(md5.ComputeHash(file)).Replace("-", "").ToLower(); wc.Method = null; hashRemote = wc.DownloadString(ResourceHash).ToLower(); if (!string.IsNullOrWhiteSpace(hashRemote) && hashRemote.StartsWith(hashCurrent)) { return(ResourceResult.Success); } } } } catch (WebException ex) { Sentry.Error(ex); return(ResourceResult.NetworkError); } catch (Exception ex) { Sentry.Error(ex); return(ResourceResult.UnknownError); } return(ResourceResult.NeedToDownload); }
private List <Satellite> GetSatellites(bool Cache = true) { var CurDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); string predicateValues = "/class/tle_latest/ORDINAL/1/EPOCH/%3Enow-30/orderby/APOGEE%20desc/format/3le/distinct/true"; string request = uriBase + requestController + requestAction + predicateValues; using (var client = new WebClientEx()) { if (Auth(client)) { var response4 = client.DownloadData(request); var stringData = System.Text.Encoding.Default.GetString(response4).Split('\n'); using (var sw = new StreamWriter(CurDir + "/lastrequest.dat")) { sw.Write(System.Text.Encoding.Default.GetString(response4)); } var sats = new List <Satellite>(); using (var sw = new StreamWriter(CurDir + "/satdata.dat")) { for (Int32 i = 0; i < stringData.Length - 1; i += 3) { try { if (stringData[i].Contains("DEB")) { continue; } //if (sats.Count > c_maxNumber) // break; Tle tle = new Tle(stringData[i], stringData[i + 1], stringData[i + 2]); sw.WriteLine(stringData[i]); sw.WriteLine(stringData[i + 1]); sw.WriteLine(stringData[i + 2]); Satellite sat = new Satellite(tle); sats.Add(sat); OnProgress(new ProgressEventArgs(i, stringData.Length - 1)); } catch { } } } SaveSats(sats); return(sats); } else { throw new NoAuthException(); } } }
public override DnsDatagram Query(DnsDatagram request) { //DoH JSON format request DateTime sentAt = DateTime.UtcNow; byte[] responseBuffer; using (WebClientEx wC = new WebClientEx()) { wC.AddHeader("accept", "application/dns-json"); wC.AddHeader("host", _server.DnsOverHttpEndPoint.Host + ":" + _server.DnsOverHttpEndPoint.Port); wC.UserAgent = "DoH client"; wC.Proxy = _proxy; wC.Timeout = _timeout; Uri queryUri; if (_proxy == null) { if (_server.IPEndPoint == null) { _server.RecursiveResolveIPAddress(new SimpleDnsCache()); } queryUri = new Uri(_server.DnsOverHttpEndPoint.Scheme + "://" + _server.IPEndPoint.ToString() + _server.DnsOverHttpEndPoint.PathAndQuery); } else { queryUri = _server.DnsOverHttpEndPoint; } wC.QueryString.Clear(); wC.QueryString.Add("name", request.Question[0].Name); wC.QueryString.Add("type", Convert.ToString(((int)request.Question[0].Type))); responseBuffer = wC.DownloadData(queryUri); } //parse response dynamic jsonResponse = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(responseBuffer)); DnsDatagram response = new DnsDatagram(jsonResponse); response.SetMetadata(new DnsDatagramMetadata(_server, _protocol, responseBuffer.Length, (DateTime.UtcNow - sentAt).TotalMilliseconds)); return(response); }
private void BtnDownload_Click(object sender, EventArgs e) { WebClientEx wc = new WebClientEx(new CookieContainer()); wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0"); wc.Headers.Add("DNT", "1"); wc.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); wc.Headers.Add("Accept-Encoding", "deflate"); wc.Headers.Add("Accept-Language", "en-US,en;q=0.5"); byte[] dt = wc.DownloadData(sheetUrl); //var outputCSVdata = System.Text.Encoding.UTF8.GetString(dt ?? new byte[] { }); string dataString = Encoding.ASCII.GetString(dt); string hashString = Encrypt(dataString); System.IO.File.WriteAllText(fileName, hashString); MessageBox.Show("Download Complete"); }
static void Main(string[] args) { string url = @"https://docs.google.com/spreadsheets/d/1OZS6mNqsjTfoxpHpbIYOUEmISALj1nBvFJ7Zxsk5VgY/edit?usp=sharing&output=csv"; WebClientEx wc = new WebClientEx(new CookieContainer()); wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0"); wc.Headers.Add("DNT", "1"); wc.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); wc.Headers.Add("Accept-Encoding", "deflate"); wc.Headers.Add("Accept-Language", "en-US,en;q=0.5"); byte[] dt = wc.DownloadData(url); var outputCSVdata = System.Text.Encoding.UTF8.GetString(dt ?? new byte[] { }); Console.WriteLine(outputCSVdata); }
public string GetSpaceTrack(string[] norad) { string predicateValues = "/class/tle_latest/ORDINAL/1/NORAD_CAT_ID/" + string.Join(",", norad) + "/orderby/NORAD_CAT_ID%20ASC/format/3le"; string request = uriBase + requestController + requestAction + predicateValues; using (var client = new WebClientEx()) { if (Auth(client)) { var response4 = client.DownloadData(request); return(System.Text.Encoding.Default.GetString(response4)); } else { throw new NoAuthException(); } } }
private List <Satellite> GetSatellites(Double Perigee, Double Apogee) { var CurDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); string predicateValues = "/class/tle_latest/ORDINAL/1/EPOCH/%3Enow-30/APOGEE/>" + Perigee.ToString() + "/PERIGEE/<" + Apogee.ToString() + "/orderby/APOGEE%20asc/format/3le/distinct/true"; string request = uriBase + requestController + requestAction + predicateValues; using (var client = new WebClientEx()) { OnStatus("Соединение с базой NORAD..."); if (Auth(client)) { OnStatus("Загрузка данных из базы..."); var response4 = client.DownloadData(request); var stringData = System.Text.Encoding.Default.GetString(response4).Split('\n'); using (var sw = new StreamWriter(CurDir + "/lastrequest.dat")) { sw.Write(System.Text.Encoding.Default.GetString(response4)); } OnStatus("Генерация орбитальных данных..."); var sats = new List <Satellite>(); for (Int32 i = 0; i < stringData.Length - 1; i += 3) { try { if (stringData[i].Contains("DEB")) { continue; } Tle tle = new Tle(stringData[i], stringData[i + 1], stringData[i + 2]); Satellite sat = new Satellite(tle); sats.Add(sat); OnProgress(new ProgressEventArgs(i, stringData.Length - 1)); } catch { } } OnStatus("Загрузка данных завершена!"); return(sats); } else { throw new NoAuthException(); } } }
public string GetSpaceTrack(string[] norad, DateTime dtstart, DateTime dtend) { string predicateValues = "/class/tle/EPOCH/" + dtstart.ToString("yyyy-MM-dd--") + dtend.ToString("yyyy-MM-dd") + "/NORAD_CAT_ID/" + string.Join(",", norad) + "/orderby/NORAD_CAT_ID%20ASC/format/3le"; string request = uriBase + requestController + requestAction + predicateValues; // Create new WebClient object to communicate with the service using (var client = new WebClientEx()) { if (Auth(client)) { var response4 = client.DownloadData(request); return(System.Text.Encoding.Default.GetString(response4)); } else { throw new NoAuthException(); } } }
private void ValidateGrantOnline(Grant grant) { Interlocked.Increment(ref totalProcessed); try { WebClientEx wc = new WebClientEx(); wc.Headers.Add(HttpRequestHeader.UserAgent, ConfigurationManager.AppSettings["GrantValidation.Header"]); using (MemoryStream ms = new MemoryStream(wc.DownloadData(string.Format(ValidationUrl, grant.ApplicationId)))) { ms.Seek(0, SeekOrigin.Begin); StreamReader sb = new StreamReader(ms); string doc = sb.ReadToEnd(); if (doc.IndexOf(RequiredKey) < 0) { throw new Exception("Server returned wrong response"); } grant.IsVerified = doc.IndexOf(ValidationPattern) < 0; ucsdDataContext.SubmitChanges(); if (grant.IsVerified == true) { log.InfoFormat("Grant ApplicationId {0} Validated", grant.ApplicationId); } else { Interlocked.Increment(ref invalidGrants); log.InfoFormat("Grant ApplicationId {0} Is not valid", grant.ApplicationId); } } } catch (Exception ex) { log.Error(String.Format("Grant validation error: {0}", ex.Message)); log.Debug("Error", ex); Interlocked.Increment(ref errorsCount); } }
/// <summary> /// 下载 /// </summary> /// <param name="eType">类型</param> /// <param name="sUrl">连接</param> /// <param name="sFilePathName">文件名</param> /// <param name="iTimeOut">超时时间</param> /// <returns></returns> private static object Download(DOWNLOAD_TYPE eType, string sUrl, string sFilePathName, int iTimeOut) { object aRet = null; WebClientEx aClient = new WebClientEx(iTimeOut); try { WebRequest myre = WebRequest.Create(sUrl); if (eType == DOWNLOAD_TYPE.FILE) { if (String.IsNullOrWhiteSpace(sFilePathName)) { return(null); } var di = new DirectoryInfo(Path.GetDirectoryName(sFilePathName)); if (!di.Exists) { di.Create(); } aClient.DownloadFile(sUrl, sFilePathName); aRet = 0; } if (eType == DOWNLOAD_TYPE.STIRNG) { aClient.Encoding = System.Text.Encoding.UTF8;//定义对象语言 aRet = aClient.DownloadString(sUrl); } if (eType == DOWNLOAD_TYPE.DATA) { aRet = aClient.DownloadData(sUrl); } } catch { aClient.Dispose(); return(aRet); } aClient.Dispose(); return(aRet); }
private BitmapImage GetImage(string url) { using (WebClient wc = new WebClientEx()) { Uri uri = new Uri(url); byte[] image_bytes; try { image_bytes = wc.DownloadData(uri); } catch { return(null); } MemoryStream img_stream = new MemoryStream(image_bytes, 0, image_bytes.Length); BitmapImage bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.StreamSource = img_stream; bitmap.EndInit(); bitmap.Freeze(); return(bitmap); } }
protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { if (_inTransaction) { Rollback(); } _webClient.QueryString.Clear(); _webClient.QueryString.Add("cmd", "logout"); _webClient.DownloadData(_webDatabaseUri); _webClient.Dispose(); } disposed = true; } }
public GameList() { InitializeComponent(); if (!App.IsWin10) { SourceChord.FluentWPF.AcrylicWindow.SetTintOpacity(this, 1.0); } string baseUrl = App.LoginRegion == "TW" ? "https://tw.images.beanfun.com/uploaded_images/beanfun_tw/game_zone/" : "http://hk.images.beanfun.com/uploaded_images/beanfun/game_zone/"; WebClient wc = new WebClientEx(); foreach (MainWindow.GameService game in App.MainWnd.gameList) { byte[] buffer = wc.DownloadData(baseUrl + game.large_image_name); BitmapImage large_image = new BitmapImage(); large_image.BeginInit(); large_image.StreamSource = new MemoryStream(buffer); large_image.EndInit(); l_GameList.Items.Add(new Game(large_image, game.name, game.service_code, game.service_region)); } }
public byte[] StartHistoricScrap(string sat_ID, uint dataset_lim) { try { System.Net.WebClient wc = new WebClient(); wc.Encoding = Encoding.UTF8; wc.UseDefaultCredentials = true; wc.Credentials = CredentialCache.DefaultCredentials; wc.Credentials = new NetworkCredential(@"*****@*****.**", "buroso89startrack"); wc.Headers[HttpRequestHeader.UserAgent] = @"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"; string uriBase = "https://www.space-track.org"; string request = string.Format("https://www.space-track.org/basicspacedata/query/class/tle/NORAD_CAT_ID/{0}/orderby/EPOCH desc/limit/{1}/format/tle", sat_ID, dataset_lim); // Create new WebClient object to communicate with the service using (var client = new WebClientEx()) { // Store the user authentication information var data = new NameValueCollection { { "identity", @"*****@*****.**" }, { "password", "buroso89startrack" }, }; // Generate the URL for the API Query and return the response var response2 = client.UploadValues(uriBase + "/ajaxauth/login", data); var response4 = client.DownloadData(request); wc.Dispose(); return(response4); } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); return(null); } }
private string getSpaceTrack(string predicateValues) { string requestController = "/basicspacedata"; string requestAction = "/query"; string request = uriBase + requestController + requestAction + predicateValues; // Create new WebClient object to communicate with the service using (var client = new WebClientEx(_cookies)) { // Generate the URL for the API Query and return the response var response = client.DownloadData(request); return (System.Text.Encoding.Default.GetString(response)); } }