protected virtual string GetLoginToken() { HttpWebRequest webRequest = WebRequest.CreateHttp("https://login.microsoft.com/rst2.srf"); webRequest.ContentType = "application/soap+xml"; webRequest.Method = "POST"; string body = $@"<?xml version=""1.0"" encoding=""UTF-8""?> <S:Envelope xmlns:S=""http://www.w3.org/2003/05/soap-envelope"" xmlns:wsse=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"" xmlns:wsp=""http://schemas.xmlsoap.org/ws/2004/09/policy"" xmlns:wsu=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"" xmlns:wsa=""http://www.w3.org/2005/08/addressing"" xmlns:wst=""http://schemas.xmlsoap.org/ws/2005/02/trust""> <S:Header> <wsa:Action S:mustUnderstand=""1"">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</wsa:Action> <wsa:To S:mustUnderstand=""1"">https://login.microsoftonline.com/rst2.srf</wsa:To> <ps:AuthInfo xmlns:ps=""http://schemas.microsoft.com/LiveID/SoapServices/v1"" Id=""PPAuthInfo""> <ps:BinaryVersion>5</ps:BinaryVersion> <ps:HostingApp>Managed IDCRL</ps:HostingApp> </ps:AuthInfo> <wsse:Security> <wsse:UsernameToken wsu:Id=""user""> <wsse:Username>{Login}</wsse:Username> <wsse:Password>{Password}</wsse:Password> </wsse:UsernameToken> <wsu:Timestamp Id=""Timestamp""> <wsu:Created>2019-12-30T12:10:46.6281129Z</wsu:Created> <wsu:Expires>2019-12-31T12:10:46.6281129Z</wsu:Expires> </wsu:Timestamp> </wsse:Security> </S:Header> <S:Body> <wst:RequestSecurityToken xmlns:wst=""http://schemas.xmlsoap.org/ws/2005/02/trust"" Id=""RST0""> <wst:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</wst:RequestType> <wsp:AppliesTo> <wsa:EndpointReference> <wsa:Address>sharepoint.com</wsa:Address> </wsa:EndpointReference> </wsp:AppliesTo> <wsp:PolicyReference URI=""MBI""></wsp:PolicyReference> </wst:RequestSecurityToken> </S:Body> </S:Envelope>"; using (Stream requestStream = webRequest.GetRequestStream()) { using (StreamWriter writer = new StreamWriter(requestStream)) { writer.Write(body); } } WebResponse response = webRequest.GetResponse(); string responseString = ""; using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { responseString = reader.ReadToEnd(); } } XmlDocument xmlResponse = new XmlDocument(); xmlResponse.LoadXml(responseString); return(xmlResponse.GetElementsByTagName("wsse:BinarySecurityToken")[0].InnerText); }
/// <summary> /// Descargars the padron. /// </summary> /// <see href="http://www.arba.gov.ar/Informacion/IBrutos/LinksIIBB/RegimenSujeto.asp"/> /// <param name="usuario">Usuario.</param> /// <param name="clave">Clave.</param> /// <param name = "año">Año del padron a descargar</param> /// <param name = "mes">Mes del padron a descargar</param> /// <param name = "destino">Ruta destino de la descarga</param> public static void DescargarPadron(string usuario, string clave, int año, int mes, string destino) { const string serverURL = "http://dfe.arba.gov.ar/DomicilioElectronico/SeguridadCliente/dfeServicioDescargaPadron.do"; const string archivo = "DFEServicioDescargaPadron"; const string extension = "xml"; string archivoConExtension = string.Format("{0}{1}.{2}", Path.GetTempPath(), archivo, extension); var settings = new XmlWriterSettings(); settings.Indent = true; settings.Encoding = Encoding.GetEncoding("ISO-8859-1"); using (XmlWriter writer = XmlWriter.Create(archivoConExtension, settings)) { writer.WriteStartDocument(); writer.WriteStartElement("DESCARGA-PADRON"); writer.WriteStartElement("fechaDesde"); writer.WriteValue(string.Format("{0:yyyyMMdd}", new DateTime(año, mes, 1))); writer.WriteEndElement(); writer.WriteStartElement("fechaHasta"); writer.WriteValue(string.Format("{0:yyyyMMdd}", new DateTime(año, mes, 1).AddMonths(1).AddDays(-1))); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); } string hash = archivoConExtension.HashMD5(); string archivoConHash = string.Format("{0}{1}_{2}.{3}", Path.GetTempPath(), archivo, hash, extension); File.Copy(archivoConExtension, archivoConHash, true); string contenido = ContenidoDeArchivo(archivoConHash); const string boundary = "AaB03x"; string postdata = string.Format("--{0}\r\n" + "Content-Disposition: form-data; name=\"user\"\r\n\r\n{1}" + "\r\n" + "--{0}\r\n" + "Content-Disposition: form-data; name=\"password\"\r\n\r\n{2}" + "\r\n" + "--{0}\r\n" + "Content-Disposition: form-data; name=\"file\"; filename={3}" + "\r\n" + "Content-Type: text/xml\r\n\r\n{4}" + "--{0}--" , boundary , usuario , clave , archivoConHash , contenido ); byte[] buffer = Encoding.ASCII.GetBytes(postdata); HttpWebRequest consulta = WebRequest.CreateHttp(serverURL); consulta.Method = "POST"; consulta.ContentType = string.Format("multipart/form-data;boundary={0}", boundary); consulta.ContentLength = buffer.Length; Stream newStream = consulta.GetRequestStream(); if (newStream != null) { newStream.Write(buffer, 0, buffer.Length); newStream.Close(); var respuesta = (HttpWebResponse)consulta.GetResponse(); Stream streamRespuesta = respuesta.GetResponseStream(); string archivoRespuesta = string.Format("{0}ARBA-PadronRGS{1:D4}{2:D2}.zip", destino, año, mes); if (respuesta.ContentType.Contains(extension)) { archivoRespuesta = string.Format("{0}{1}-Error.xml", destino, archivo); } var streamWriter = new FileStream(archivoRespuesta, FileMode.Create, FileAccess.Write); var bufferRead = new byte[4096]; int bytesRead; do { bytesRead = streamRespuesta.Read(bufferRead, 0, 4096); streamWriter.Write(bufferRead, 0, bytesRead); } while (bytesRead > 0); streamWriter.Close(); streamRespuesta.Close(); respuesta.Close(); } }
public void HttpWebRequest_ConnectionTryAddCloseKeepAlive_Fails() { HttpWebRequest request = WebRequest.CreateHttp(Configuration.Http.RemoteEchoServer); Assert.Throws <ArgumentException>(() => { request.Connection = "Close;keep-alive"; }); }
/* * @author: https://github.com/WesleyVale99 * Sábado, 27 de março de 2021 */ static void Main() { try { Console.Title = "HttpWebRequest v0.1"; Console.WriteLine("@author: https://github.com/WesleyVale99"); Console.WriteLine("\n"); Console.WriteLine("x---------------------------------------------------------------------------------------x"); Console.WriteLine("[!] one of the methods to use the program is to leave g-recaptcha-response = null \n" + "[!] so that the program can automatically add"); Console.WriteLine("[!] Url example: https://test.com?user=12345&password=12345&g-recaptcha-response="); Console.WriteLine("x---------------------------------------------------------------------------------------x"); Console.WriteLine("[!] however in case you don't need captcha you can just skip the process.d"); Console.WriteLine("[!] Url example: https://test.com?user=12345&password=12345"); Console.WriteLine("x---------------------------------------------------------------------------------------x"); Console.WriteLine("\n"); Console.WriteLine("[x] Enter type [0]:[1] (0: recaptcha TRUE, 1: recaptcha FALSE)"); string type = Console.ReadLine(); if (type == "0") { Console.WriteLine("[x] Enter a URL: "); string Url = Console.ReadLine(); Console.WriteLine("[x] Enter a Token ReCaptcha: "); string Token = Console.ReadLine(); Console.WriteLine("[x] Enter Method: [0 POST, 1 GET]"); int method = int.Parse(Console.ReadLine()); if (Url != "" && (Url.Contains("https://") || Url.Contains("http://")) && Token != "" && (method == 0 || method == 1)) { string[] BreakPoint = Url.Split('?'); if (method == 0) { string addtoken = ReCaptcha(Token); if (addtoken == "404") { return; } string Mount = ""; string[] serialize = BreakPoint[1].Split('&'); for (int i = 0; i < serialize.Length; i++) { string spn = serialize[i]; if (spn == "g-recaptcha-response=") { spn = "g-recaptcha-response=" + addtoken; } Mount += i == 0 ? spn : "&" + spn; } HttpWebRequest request = WebRequest.CreateHttp(BreakPoint[0]); string breakPoint = string.Concat(Mount); byte[] data = Encoding.UTF8.GetBytes(breakPoint); request.Method = ((Method)method).ToString(); request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"; request.ContentLength = data.Length; request.ContentType = "application/x-www-form-urlencoded";//"multipart/form-data; boundary=----WebKitFormBoundaryZjAtXvxTO3xUgkEl"; request.Referer = BreakPoint[0]; request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36"; request.ContinueTimeout = 100; using Stream stream = request.GetRequestStream(); stream.Write(data, 0, data.Length); stream.Close(); string Format = JsonConvert.SerializeObject(request, Formatting.Indented); Console.WriteLine("\n"); Console.WriteLine("Breakpoint: " + breakPoint); Console.WriteLine(Format); using WebResponse response = request.GetResponse(); Stream streamDados = response.GetResponseStream(); StreamReader reader = new StreamReader(streamDados); object objResponse = reader.ReadToEnd(); if (objResponse != null) { Console.WriteLine(objResponse.ToString()); streamDados.Close(); response.Close(); } } else if (method == 1) { HttpWebRequest request = WebRequest.CreateHttp(BreakPoint[0]); request.Method = ((Method)method).ToString(); request.ContentType = "application/x-www-form-urlencoded"; request.Referer = BreakPoint[0]; request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36"; using WebResponse response = request.GetResponse(); Stream streamDados = response.GetResponseStream(); StreamReader reader = new StreamReader(streamDados); object objResponse = reader.ReadToEnd(); if (objResponse != null) { Console.WriteLine(objResponse.ToString()); streamDados.Close(); response.Close(); } } } else { Console.WriteLine("[x] Error requisition [!]"); } } else if (type == "1") { Console.WriteLine("[x] Enter a URL: "); string Url = Console.ReadLine(); Console.WriteLine("[x] Enter Method: [0 POST, 1 GET]"); int method = int.Parse(Console.ReadLine()); if (Url != "" && (Url.Contains("https://") || Url.Contains("http://")) && (method == 0 || method == 1)) { string[] BreakPoint = Url.Split('?'); if (method == 0) { HttpWebRequest request = WebRequest.CreateHttp(BreakPoint[0]); string breakPoint = BreakPoint[1]; byte[] data = Encoding.UTF8.GetBytes(breakPoint); request.Method = ((Method)method).ToString(); request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"; request.ContentLength = data.Length; request.ContentType = "application/x-www-form-urlencoded";//"multipart/form-data; boundary=----WebKitFormBoundaryZjAtXvxTO3xUgkEl"; request.Referer = BreakPoint[0]; request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36"; request.ContinueTimeout = 100; using Stream stream = request.GetRequestStream(); stream.Write(data, 0, data.Length); stream.Close(); string Format = JsonConvert.SerializeObject(request, Formatting.Indented); Console.WriteLine("\n"); Console.WriteLine("Breakpoint: " + breakPoint); Console.WriteLine(Format); using WebResponse response = request.GetResponse(); Stream streamDados = response.GetResponseStream(); StreamReader reader = new StreamReader(streamDados); object objResponse = reader.ReadToEnd(); if (objResponse != null) { Console.WriteLine(objResponse.ToString()); streamDados.Close(); response.Close(); } } else if (method == 1) { HttpWebRequest request = WebRequest.CreateHttp(BreakPoint[0]); request.Method = ((Method)method).ToString(); request.ContentType = "application/x-www-form-urlencoded"; request.Referer = BreakPoint[0]; request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36"; using WebResponse response = request.GetResponse(); Stream streamDados = response.GetResponseStream(); StreamReader reader = new StreamReader(streamDados); object objResponse = reader.ReadToEnd(); if (objResponse != null) { Console.WriteLine(objResponse.ToString()); streamDados.Close(); response.Close(); } } } else { Console.WriteLine("[x] Error requisition [!]"); } } } catch (FormatException ex) { Console.WriteLine("[x] FormatError: [ " + ex.Message + " ] [!]"); } catch (WebException ex) { Console.WriteLine("[x] WebException: [ " + ex.Message + " ] [!]"); } Process.GetCurrentProcess().WaitForExit(); }
private static System.DateTime denyTime; // to know when denyAdditionalRequests was switched, if we pass to another day, reset it /// <summary> /// Makes a request from MKM's API. /// If the daily request limit has been reached, does not send the request and instead throws an exception. /// </summary> /// <param name="url">The http URL of the API.</param> /// <param name="method">The name of the request method (PUT, GET, etc.).</param> /// <param name="body">The body containing parameters of the method if applicable.</param> /// <returns>Document containing the response from MKM. In some cases this can empty (when the response is "nothing matches your request").</returns> /// <exception cref="HttpListenerException">429 - Too many requests. Wait for 0:00 CET for request counter to reset.</exception> /// <exception cref="APIProcessingExceptions">Many different network-based exceptions.</exception> public static XmlDocument makeRequest(string url, string method, string body = null) { // throw the exception ourselves to prevent sending requests to MKM that would end with this error // because MKM tends to revoke the user's app token if it gets too many requests above the limit // the 429 code is the same MKM uses for this error if (denyAdditionalRequests) { // MKM resets the counter at 0:00 CET. CET is two hours ahead of UCT, so if it is after 22:00 of the same day // the denial was triggered, that means the 0:00 CET has passed and we can reset the deny if (System.DateTime.UtcNow.Date == denyTime.Date && System.DateTime.UtcNow.Hour < 22) { throw new HttpListenerException(429, "Too many requests. Wait for 0:00 CET for request counter to reset."); } else { denyAdditionalRequests = false; } } XmlDocument doc = new XmlDocument(); var request = WebRequest.CreateHttp(url); request.Method = method; var header = new MKMAuth.OAuthHeader(); request.Headers.Add(HttpRequestHeader.Authorization, header.getAuthorizationHeader(method, url)); request.Method = method; if (body != null) { request.ServicePoint.Expect100Continue = false; request.ContentLength = body.Length; request.ContentType = "text/xml"; var writer = new StreamWriter(request.GetRequestStream()); writer.Write(body); writer.Close(); } var response = request.GetResponse() as HttpWebResponse; // just for checking EoF, it is not accessible directly from the Stream object // Empty streams can be returned for example for article fetches that result in 0 matches (happens regularly when e.g. seeking nonfoils in foil-only promo sets). // Passing empty stream to doc.Load causes exception and also sometimes seems to screw up the XML parser // even when the exception is handled and it then causes problems for subsequent calls => first check if the stream is empty StreamReader s = new StreamReader(response.GetResponseStream()); if (!s.EndOfStream) { doc.Load(s); } s.Close(); int requestCount = int.Parse(response.Headers.Get("X-Request-Limit-Count")); int requestLimit = int.Parse(response.Headers.Get("X-Request-Limit-Max")); if (requestCount >= requestLimit) { denyAdditionalRequests = true; denyTime = System.DateTime.UtcNow; } MainView.Instance.Invoke(new MainView.updateRequestCountCallback(MainView.Instance.updateRequestCount), requestCount, requestLimit); return(doc); }
static void Main(string[] args) { var config = File.ReadAllLines("config"); long uid = long.Parse(config[0]); string cookie = config[1]; Directory.CreateDirectory(DATA_PATH); HttpWebRequest req = null; WebClient webClient = new WebClient(); int page = 0, post = 0; while (true) { string json = null; dynamic weiboPage = null; page += 1; try { json = GetWeiboPage(page); weiboPage = JObject.Parse(json); } catch (JsonException) { WriteLine("(JSON 语法错误)"); continue; } catch (Exception ex) { WriteLine(ex); break; } if (weiboPage?.data?.cards == null || weiboPage.data.cards.Count == 0) { WriteLine("完成"); break; } foreach (var card in weiboPage.data.cards) { post += 1; Write($"微博:{post}"); var mblog = card.mblog; Directory.CreateDirectory($@"{DATA_PATH}/{mblog.id}"); try { try { if ((bool)mblog.isLongText) { mblog.text = (JObject.Parse(GetLongText(mblog.id)) as dynamic) .data.longTextContent; Write(",长微博"); } if (mblog.retweeted_status != null) { if (mblog.retweeted_status.deleted > 0) { Write(",转发来源已删除"); } else { if ((bool)mblog.retweeted_status.isLongText) { mblog.retweeted_status.text = (JObject.Parse(GetLongText(mblog.retweeted_status.id)) as dynamic) .data.longTextContent; Write(",转发来源长微博"); } } } } catch (JsonException) { Write("(JSON 语法错误)"); } if (mblog.visible.type == 6) { Write(",好友圈"); } else if (mblog.visible.type == 1) { Write(",私密"); } else if (mblog.visible.type > 0) { Write(",可见性未知"); } if (mblog.pics != null) { GetPictures(mblog); } if (mblog.retweeted_status?.pics != null) { GetPictures(mblog.retweeted_status, mblog.id); } if (mblog.comments_count > 0) { File.WriteAllText( $@"{DATA_PATH}/{mblog.id}/comments.json", JsonConvert.SerializeObject(GetComments(mblog.id))); } if (mblog.reposts_count > 0) { File.WriteAllText( $@"{DATA_PATH}/{mblog.id}/reposts.json", JsonConvert.SerializeObject(GetReposts(mblog.id))); } } catch (Exception ex) { Write("(发生未知异常,详见该微博目录下 exception 文件)"); File.WriteAllText( $@"{DATA_PATH}/{mblog.id}/exception", ex.ToString()); } File.WriteAllText( $@"{DATA_PATH}/{mblog.id}/status.json", mblog.ToString()); WriteLine(" "); } } ReadKey(true); string GetWeiboPage(int id) { return(HttpGetString( $"https://m.weibo.cn/api/container/getIndex" + $"?type=uid" + $"&value={uid}" + $"&containerid=107603{uid}" + $"&page={id}")); } string GetLongText(long id) { return(HttpGetString( $"https://m.weibo.cn/statuses/extend" + $"?id={id}")); } void GetPictures(dynamic mblog, long id = 0) { if (id == 0) { id = mblog.id; } Write("," + (mblog.id == id ? "" : "转发来源") + "图片:0..."); var count = 0; foreach (var pic in mblog.pics) { try { HttpGetFile( pic.large.url.Value, $@"{DATA_PATH}/{id}/{Path.GetFileName(pic.large.url.Value)}"); count += 1; Write($"\b\b\b\b{count}..."); } catch { } } Write("\b\b\b"); } IEnumerable <object> GetComments(long id) { Write(",评论:0..."); var lastCount = 0; var commentPage = 1; var commentList = new List <object>(); do { try { var json = HttpGetString( $"https://m.weibo.cn/api/comments/show" + $"?id={id}" + $"&page={commentPage}"); dynamic data = JsonConvert.DeserializeObject(json); if (data?.ok.Type == JTokenType.Integer && data.ok > 0) { commentList.AddRange(data.data.data); Write($"\b\b\b{new string('\b', lastCount.ToString().Length)}{commentList.Count}..."); lastCount = commentList.Count; } else { break; } commentPage += 1; } catch { break; } } while (true); Write("\b\b\b"); return(commentList); } IEnumerable <object> GetReposts(long id) { Write(",转发:0..."); var lastCount = 0; var repostPage = 1; var repostList = new List <object>(); do { try { var json = HttpGetString( $"https://m.weibo.cn/api/statuses/repostTimeline" + $"?id={id}" + $"&page={repostPage}"); dynamic data = JsonConvert.DeserializeObject(json); if (data?.ok.Type == JTokenType.Integer && data.ok > 0) { repostList.AddRange(data.data.data); Write($"\b\b\b{new string('\b', lastCount.ToString().Length)}{repostList.Count}..."); lastCount = repostList.Count; } else { break; } repostPage += 1; } catch { break; } } while (true); Write("\b\b\b"); return(repostList); } string HttpGetString(string url) { var retryCount = 0; while (retryCount < RETRY_LIMIT) { var wait = random.Next(SLEEP_MIN, SLEEP_MAX); Thread.Sleep(wait); try { req = WebRequest.CreateHttp(url); var cookies = new CookieContainer(); cookies.SetCookies(new Uri(url), cookie.Replace(';', ',')); req.CookieContainer = cookies; return(new StreamReader( (req.GetResponse() as HttpWebResponse).GetResponseStream() ).ReadToEnd()); } catch (WebException ex) { Debug.WriteLine(ex); retryCount += 1; } } WriteLine($"已达到 {RETRY_LIMIT} 次重试的限制,跳过此请求"); return(null); } void HttpGetFile(string url, string savePath) { var retryCount = 0; while (retryCount < RETRY_LIMIT) { var wait = random.Next(SLEEP_MIN, SLEEP_MAX); Thread.Sleep(wait); try { webClient.DownloadFile(url, savePath); return; } catch (WebException ex) { Debug.WriteLine(ex); retryCount += 1; } } WriteLine($"已达到 {RETRY_LIMIT} 次重试的限制,跳过此请求"); } }
private void button2_Click(object sender, EventArgs e) { Int32.TryParse(DateTime.Now.Month.ToString(), out j); Int32.TryParse(DateTime.Now.Year.ToString(), out p); for (int k = j; k <= 12; k++) { var request = WebRequest.CreateHttp("https://asta.uni-paderborn.de/events/" + p.ToString() + "-" + k.ToString("00") + "/?ical=1"); request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = DATA.Length; StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII); requestWriter.Write(DATA); requestWriter.Close(); WebResponse webResponse = request.GetResponse(); Stream webStream = webResponse.GetResponseStream(); StreamReader responseReader = new StreamReader(webStream); string response = responseReader.ReadToEnd(); //MessageBox.Show(response.ToString()); responseReader.Close(); String[] splitText2; String[] splitText1 = response.Split(new string[] { "BEGIN" }, StringSplitOptions.None); for (int i = 2; i < splitText1.Length; i++) { Events ev = new Events(); splitText2 = splitText1[i].Split('\n'); for (int j = 0; j < splitText2.Length; j++) { if (splitText2[j].Contains("DESCRIPTION") == true) { try { ev.Description = splitText2[j].Split(new string[] { "DESCRIPTION:" }, StringSplitOptions.None)[1]; } catch { ev.Description = ""; } } else if (splitText2[j].Contains("DTEND") == true) { try { ev.End_date_time = splitText2[j].Split(new string[] { "DTEND;TZID=Europe/Berlin:" }, StringSplitOptions.None)[1]; } catch { ev.End_date_time = ""; } } else if (splitText2[j].Contains("URL") == true) { try { ev.Image_url = splitText2[j].Split(new string[] { "URL:" }, StringSplitOptions.None)[1]; } catch { ev.Image_url = ""; } } else if (splitText2[j].Contains("SUMMARY") == true) { try { ev.Name = splitText2[j].Split(new string[] { "SUMMARY:" }, StringSplitOptions.None)[1]; } catch { ev.Name = ""; } } else if (splitText2[j].Contains("DTSTART") == true) { try { ev.Start_date_time = splitText2[j].Split(new string[] { "DTSTART;TZID=Europe/Berlin:" }, StringSplitOptions.None)[1]; } catch { ev.Start_date_time = ""; } } } ev.Location = "ASTA Paderborn"; event_upb.Add(ev); } } MessageBox.Show("Events updated in Firebase successfully!"); sendResult(); }
public async Task CheckForUpdates() { try { await CheckForUpdatesLock.WaitAsync(); if (EnvironmentHelper.IsDebug) { return; } if (LastUpdateFailure.AddDays(1) > DateTimeOffset.Now) { Logger.Write("Skipping update check due to previous failure. Updating will be tried again after 24 hours have passed."); return; } var connectionInfo = ConfigService.GetConnectionInfo(); var serverUrl = ConfigService.GetConnectionInfo().Host; var platform = Environment.Is64BitOperatingSystem ? "x64" : "x86"; var fileUrl = serverUrl + $"/Content/Remotely-Win10-{platform}.zip"; var lastEtag = string.Empty; if (File.Exists("etag.txt")) { lastEtag = await File.ReadAllTextAsync("etag.txt"); } try { var wr = WebRequest.CreateHttp(fileUrl); wr.Method = "Head"; wr.Headers.Add("If-None-Match", lastEtag); using var response = (HttpWebResponse) await wr.GetResponseAsync(); if (response.StatusCode == HttpStatusCode.NotModified) { Logger.Write("Service Updater: Version is current."); return; } } catch (WebException ex) when((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.NotModified) { Logger.Write("Service Updater: Version is current."); return; } Logger.Write("Service Updater: Update found."); await InstallLatestVersion(); } catch (Exception ex) { Logger.Write(ex); } finally { CheckForUpdatesLock.Release(); } }
/// <summary> /// Posts the feedback message asynchronous. /// </summary> /// <param name="message">The message.</param> /// <param name="email">The email.</param> /// <param name="subject">The subject.</param> /// <param name="name">The name.</param> /// <param name="attachments">The attachments.</param> /// <returns></returns> /// <exception cref="System.Exception">Server error. Server returned status + fbResp.Status</exception> public async Task <IFeedbackMessage> PostFeedbackMessageAsync(string message, string email = null, string subject = null, string name = null, IEnumerable <IFeedbackAttachment> attachments = null) { IHockeyClientInternal client = HockeyClient.Current.AsInternal(); var msg = new FeedbackMessage(); msg.Name = client.UserID; msg.Text = message; msg.Email = email; msg.Name = name; msg.Subject = subject; HttpWebRequest request = null; if (this.IsNewThread) { msg.Token = this.Token; request = WebRequest.CreateHttp(new Uri(client.ApiBaseVersion2 + "apps/" + client.AppIdentifier + "/feedback", UriKind.Absolute)); request.Method = "Post"; } else { request = WebRequest.CreateHttp(new Uri(client.ApiBaseVersion2 + "apps/" + client.AppIdentifier + "/feedback/" + this.Token + "/", UriKind.Absolute)); request.Method = "Put"; } request.SetHeader(HttpRequestHeader.UserAgent.ToString(), client.UserAgentString); byte[] dataStream; if (attachments == null || !attachments.Any()) { string data = msg.SerializeToWwwForm(); dataStream = Encoding.UTF8.GetBytes(data); request.ContentType = "application/x-www-form-urlencoded"; request.SetHeader(HttpRequestHeader.ContentEncoding.ToString(), Encoding.UTF8.WebName.ToString()); using (Stream stream = await request.GetRequestStreamAsync()) { stream.Write(dataStream, 0, dataStream.Length); stream.Flush(); } } else { string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); request.ContentType = "multipart/form-data; boundary=" + boundary; using (Stream stream = await request.GetRequestStreamAsync()) { string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; //write form fields foreach (var keyValue in msg.MessagePartsDict) { stream.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string.Format(formdataTemplate, keyValue.Key, keyValue.Value); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); stream.Write(formitembytes, 0, formitembytes.Length); } //write images for (int index = 0; index < attachments.Count(); index++) { var attachment = attachments.ElementAt(index); stream.Write(boundarybytes, 0, boundarybytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; string header = string.Format(headerTemplate, "attachment" + index, attachment.FileName, String.IsNullOrEmpty(attachment.ContentType) ? "application/octet-stream" : attachment.ContentType); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); stream.Write(headerbytes, 0, headerbytes.Length); stream.Write(attachment.DataBytes, 0, attachment.DataBytes.Length); } byte[] trailer = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); stream.Write(trailer, 0, trailer.Length); stream.Flush(); } } var response = await request.GetResponseAsync(); var fbResp = await TaskEx.Run <FeedbackResponseSingle>(() => FeedbackResponseSingle.FromJson(response.GetResponseStream())); if (!fbResp.Status.Equals("success")) { throw new Exception("Server error. Server returned status " + fbResp.Status); } IFeedbackMessage fbNewMessage = fbResp.Feedback.Messages.Last(); if (fbNewMessage != null) { this.messages.Add(fbNewMessage as FeedbackMessage); } if (this.IsNewThread) { this.IsNewThread = false; } return(fbNewMessage); }
public async Task InstallLatestVersion() { try { await InstallLatestVersionLock.WaitAsync(); var connectionInfo = ConfigService.GetConnectionInfo(); var serverUrl = connectionInfo.Host; Logger.Write("Service Updater: Downloading install package."); using var wc = new WebClientEx((int)UpdateTimer.Interval); var downloadId = Guid.NewGuid().ToString(); var zipPath = Path.Combine(Path.GetTempPath(), "RemotelyUpdate.zip"); if (EnvironmentHelper.IsWindows) { var installerPath = Path.Combine(Path.GetTempPath(), "Remotely_Installer.exe"); var platform = Environment.Is64BitOperatingSystem ? "x64" : "x86"; await wc.DownloadFileTaskAsync( serverUrl + $"/Downloads/Remotely_Installer.exe", installerPath); await wc.DownloadFileTaskAsync( serverUrl + $"/api/AgentUpdate/DownloadPackage/win-{platform}/{downloadId}", zipPath); (await WebRequest.CreateHttp(serverUrl + $"/api/AgentUpdate/ClearDownload/{downloadId}").GetResponseAsync()).Dispose(); foreach (var proc in Process.GetProcessesByName("Remotely_Installer")) { proc.Kill(); } Logger.Write("Launching installer to perform update."); Process.Start(installerPath, $"-install -quiet -path {zipPath} -serverurl {serverUrl} -organizationid {connectionInfo.OrganizationID}"); } else if (EnvironmentHelper.IsLinux) { var installerPath = Path.Combine(Path.GetTempPath(), "RemotelyUpdate.sh"); string platform; if (RuntimeInformation.OSDescription.Contains("Ubuntu", StringComparison.OrdinalIgnoreCase)) { platform = "Ubuntu-x64"; } else if (RuntimeInformation.OSDescription.Contains("Manjaro", StringComparison.OrdinalIgnoreCase)) { platform = "Manjaro-x64"; } else { throw new PlatformNotSupportedException(); } await wc.DownloadFileTaskAsync( serverUrl + $"/API/ClientDownloads/{connectionInfo.OrganizationID}/{platform}", installerPath); await wc.DownloadFileTaskAsync( serverUrl + $"/API/AgentUpdate/DownloadPackage/linux/{downloadId}", zipPath); (await WebRequest.CreateHttp(serverUrl + $"/api/AgentUpdate/ClearDownload/{downloadId}").GetResponseAsync()).Dispose(); Logger.Write("Launching installer to perform update."); Process.Start("sudo", $"chmod +x {installerPath}").WaitForExit(); Process.Start("sudo", $"{installerPath} --path {zipPath} & disown"); } } catch (WebException ex) when(ex.Status == WebExceptionStatus.Timeout) { Logger.Write("Timed out while waiting to download update.", Shared.Enums.EventType.Warning); PreviousUpdateFailed = true; } catch (Exception ex) { Logger.Write(ex); PreviousUpdateFailed = true; } finally { InstallLatestVersionLock.Release(); } }
public async Task CheckForUpdates() { try { await CheckForUpdatesLock.WaitAsync(); if (EnvironmentHelper.IsDebug) { return; } if (PreviousUpdateFailed) { Logger.Write("Skipping update check due to previous failure. Restart the service to try again, or manually install the update."); return; } var connectionInfo = ConfigService.GetConnectionInfo(); var serverUrl = ConfigService.GetConnectionInfo().Host; string fileUrl; if (EnvironmentHelper.IsWindows) { var platform = Environment.Is64BitOperatingSystem ? "x64" : "x86"; fileUrl = serverUrl + $"/Downloads/Remotely-Win10-{platform}.zip"; } else if (EnvironmentHelper.IsLinux) { fileUrl = serverUrl + $"/Downloads/Remotely-Linux.zip"; } else { throw new PlatformNotSupportedException(); } var lastEtag = string.Empty; if (File.Exists("etag.txt")) { lastEtag = await File.ReadAllTextAsync("etag.txt"); } try { var wr = WebRequest.CreateHttp(fileUrl); wr.Method = "Head"; wr.Headers.Add("If-None-Match", lastEtag); using var response = (HttpWebResponse) await wr.GetResponseAsync(); if (response.StatusCode == HttpStatusCode.NotModified) { Logger.Write("Service Updater: Version is current."); return; } } catch (WebException ex) when((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.NotModified) { Logger.Write("Service Updater: Version is current."); return; } Logger.Write("Service Updater: Update found."); await InstallLatestVersion(); } catch (Exception ex) { Logger.Write(ex); } finally { CheckForUpdatesLock.Release(); } }
internal ApiRequest( string path, RequestData requestData, Session session, UrlParameters urlParameters, string httpMethod ) { if ( session == null && ( path != noSessionPath || httpMethod != noSessionMethod ) ) { Console.WriteLine(path); Console.WriteLine(httpMethod); throw new ApiRequestException(requiredSessionMessage); } string fullUrl; if (urlParameters != null) { fullUrl = apiEndpoint + path + urlParameters.ToString(); } else { fullUrl = apiEndpoint + path; } HttpWebRequest request = WebRequest.CreateHttp(fullUrl); request.UserAgent = userAgent; request.Method = httpMethod; if (session != null) { Signature signature; string apiKey = session.apiKey; if (requestData != null) { signature = new Signature(apiKey, path, requestData); } else { signature = new Signature(apiKey, path); } request.Headers.Add(sessionIdHeaderName, session.IdString()); request.Headers.Add(signatureHeaderName, signature.ToString()); } if (requestData != null) { string jsonData = requestData.JsonData(); UTF8Encoding utf8 = new UTF8Encoding(); byte[] data = utf8.GetBytes(jsonData); request.ContentLength = data.Length; request.ContentType = "application/json"; using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } } WebResponse response = request.GetResponse(); Stream receiveStream = response.GetResponseStream(); StreamReader readStream = new StreamReader( receiveStream, Encoding.UTF8 ); string responseJson = readStream.ReadToEnd(); response.Close(); readStream.Close(); try { responseData = JsonConvert.DeserializeObject <List <Dictionary <string, object> > >( responseJson ); } catch (JsonSerializationException) { responseData = JsonConvert.DeserializeObject <Dictionary <string, object> >( responseJson ); } return; }
private UpnpNatDeviceInfo BuildUpnpNatDeviceInfo(IPAddress localAddress, Uri location) { NatDiscoverer.TraceSource.LogInfo("Found device at: {0}", location.ToString()); var hostEndPoint = new IPEndPoint(IPAddress.Parse(location.Host), location.Port); WebResponse response = null; try { #if !(NET_4_6 || NET_STANDARD_2_0) var request = WebRequest.Create(location); #else var request = WebRequest.CreateHttp(location); #endif request.Headers.Add("ACCEPT-LANGUAGE", "en"); request.Method = "GET"; response = request.GetResponse(); var httpresponse = response as HttpWebResponse; if (httpresponse != null && httpresponse.StatusCode != HttpStatusCode.OK) { var message = string.Format("Couldn't get services list: {0} {1}", httpresponse.StatusCode, httpresponse.StatusDescription); throw new Exception(message); } var xmldoc = ReadXmlResponse(response); NatDiscoverer.TraceSource.LogInfo("{0}: Parsed services list", hostEndPoint); var ns = new XmlNamespaceManager(xmldoc.NameTable); ns.AddNamespace("ns", "urn:schemas-upnp-org:device-1-0"); var services = xmldoc.SelectNodes("//ns:service", ns); foreach (XmlNode service in services) { var serviceType = service.GetXmlElementText("serviceType"); if (!IsValidControllerService(serviceType)) { continue; } NatDiscoverer.TraceSource.LogInfo("{0}: Found service: {1}", hostEndPoint, serviceType); var serviceControlUrl = service.GetXmlElementText("controlURL"); NatDiscoverer.TraceSource.LogInfo("{0}: Found upnp service at: {1}", hostEndPoint, serviceControlUrl); NatDiscoverer.TraceSource.LogInfo("{0}: Handshake Complete", hostEndPoint); return(new UpnpNatDeviceInfo(localAddress, location, serviceControlUrl, serviceType)); } throw new Exception("No valid control service was found in the service descriptor document"); } catch (WebException ex) { // Just drop the connection, FIXME: Should i retry? NatDiscoverer.TraceSource.LogError("{0}: Device denied the connection attempt: {1}", hostEndPoint, ex); var inner = ex.InnerException as SocketException; if (inner != null) { NatDiscoverer.TraceSource.LogError("{0}: ErrorCode:{1}", hostEndPoint, inner.ErrorCode); NatDiscoverer.TraceSource.LogError("Go to http://msdn.microsoft.com/en-us/library/system.net.sockets.socketerror.aspx"); NatDiscoverer.TraceSource.LogError("Usually this happens. Try resetting the device and try again. If you are in a VPN, disconnect and try again."); } throw; } finally { if (response != null) { response.Close(); } } }
/// <summary> /// A helper function that checks the validity of a single remote link. /// Side effects: Prints to the console. /// </summary> /// <param name="markdownFilePath">The fully qualified path of the Markdown file to check</param> /// <param name="remoteLink">The object representing the remote link to check.</param> /// <param name="dotenv">A dictionary representing the dotenv contents.</param> /// <returns>A bool indicating success/failure</returns> internal static bool CheckRemoteLink(string markdownFilePath, RemoteLink remoteLink, Dictionary <string, string> dotenv) { // First check if its linking to something in our repository. // Note that github URLs are case-insensitive string githubUrl; if (!dotenv.TryGetValue("GITHUB_URL", out githubUrl)) { Console.WriteLine("No dotenv file found. Aborting linting."); Environment.Exit(1); } var githubRepoBlobPath = (githubUrl + "/blob/").ToLower(); var githubRepoTreePath = (githubUrl + "/tree/").ToLower(); var lowerUrl = remoteLink.Url.ToLower(); if (lowerUrl.Contains(githubRepoBlobPath) || lowerUrl.Contains(githubRepoTreePath)) { LogInvalidLink(markdownFilePath, remoteLink, "Remote link to repository detected. Use a relative path instead. For example, https://www.github.com/spatialos/UnityGDK/blob/master/README.md#docs referenced from docs/my-docs.md should be ../README.md#docs"); return(false); } // Necessary to be in scope in finally block. HttpWebResponse response = null; try { var strippedUrl = remoteLink.Url; // anchors break the link check, need to remove them from the link before creating the web request. if (strippedUrl.Contains("#")) { strippedUrl = remoteLink.Url.Substring(0, strippedUrl.IndexOf("#", StringComparison.Ordinal)); } var request = WebRequest.CreateHttp(strippedUrl); request.Method = WebRequestMethods.Http.Get; request.AllowAutoRedirect = true; response = request.GetResponse() as HttpWebResponse; // Check for non-200 error codes. if (response.StatusCode != HttpStatusCode.OK) { LogLinkWarning(markdownFilePath, remoteLink, $"returned a status code of: {(int) response.StatusCode}"); } return(true); } catch (WebException ex) { // There was an error code. Check if it was a 404. // Any other 4xx errors are considered "okay" for now. if (ex.Status == WebExceptionStatus.ProtocolError) { var statusCode = ((HttpWebResponse)ex.Response).StatusCode; if (statusCode == HttpStatusCode.NotFound) { LogInvalidLink(markdownFilePath, remoteLink); return(false); } LogLinkWarning(markdownFilePath, remoteLink, $"returned a status code of: {(int) statusCode}"); return(true); } LogInvalidLink(markdownFilePath, remoteLink, "An exception occured when trying to access this remote link."); LogException(ex); return(false); } catch (Exception ex) { LogInvalidLink(markdownFilePath, remoteLink, "An exception occured when trying to access this remote link."); LogException(ex); return(false); } finally { response?.Close(); } }
// GET: Crawler public ActionResult NYTimesCookingCrawler(string listRequestUrl) { var request = WebRequest.CreateHttp(listRequestUrl); request.Method = "GET"; request.Accept = "*/*"; request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36"; request.Host = "cooking.nytimes.com"; //request.Proxy = new WebProxy(new Uri("http://127.0.0.1:8787")); var response = request.GetResponse(); var html = string.Empty; using (var sr = new StreamReader(response.GetResponseStream())) { html = sr.ReadToEnd(); } foreach (Match match in Regex.Matches(html, "data-url=\"/recipes/(\\S+)\"")) { var pageid = match.Groups[1].ToString(); request = WebRequest.CreateHttp("http://cooking.nytimes.com/recipes/" + pageid); request.Method = "GET"; request.Accept = "*/*"; request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36"; request.Host = "cooking.nytimes.com"; //request.Proxy = new WebProxy(new Uri("http://127.0.0.1:8787")); response = request.GetResponse(); html = string.Empty; using (var sr = new StreamReader(response.GetResponseStream())) { html = sr.ReadToEnd(); var name = Regex.Match(html, "<h1 class=\"recipe-title title name\" data-name=\"(\\S.+)\"").Groups[1].ToString(); var description = Regex.Match(html, "<meta name=\"description\" content=\"(\\S.+)\"/>").Groups[1].ToString(); var directions = Regex.Match(html.Replace("\n", "").Replace("\r", ""), "<ol class=\"recipe-steps\" itemprop=\"recipeInstructions\">(.*?)</ol>").Groups[0].ToString(); var imageUrl = Regex.Match(html, "src=\"(.*?)-articleLarge.jpg").Groups[1].ToString(); var images = new List <ImageInfo>(); if (!string.IsNullOrEmpty(imageUrl)) { images.Add(new ImageInfo { Url = imageUrl + "-articleLarge.jpg" }); } var ingredients = new List <IngredientInfo>(); foreach (Match m in Regex.Matches(html.Replace("\n", "").Replace("\r", ""), "<span class=\"quantity\">(.*?)</span>(\\s+)<span class=\"ingredient-name\">(.*?)</li>")) { var match_name = Regex.Match(m.Groups[3].ToString().Trim(), "(.*?)<span>(.*?)</span>"); if (match_name.Groups.Count >= 3) { ingredients.Add(new IngredientInfo { Quantity = m.Groups[1].ToString().Trim(), Unit = match_name.Groups[1].ToString().Trim(), Name = match_name.Groups[2].ToString().Trim() }); } } var tags = new List <TagInfo>(); foreach (Match m in Regex.Matches(html, "<a id=\"(.*?)\" href=/tag/(.*?)>(.*?)</a>")) { tags.Add(new TagInfo { Name = m.Groups[3].ToString().Trim() }); } RecipeService.AddRecipe(new RecipeInfoViewModel { Name = name, Description = description, Directions = directions, Images = images, Ingredients = ingredients, Tags = tags }); } } return(Content(html)); }
private void ApplyConnectionHandlers() { var conductor = ServiceContainer.Instance.GetRequiredService <Conductor>(); Connection.Closed += (ex) => { Logger.Write($"Connection closed. Error: {ex?.Message}"); return(Task.CompletedTask); }; Connection.On("ReceiveIceCandidate", (string candidate, int sdpMlineIndex, string sdpMid, string viewerID) => { try { if (conductor.Viewers.TryGetValue(viewerID, out var viewer)) { viewer.RtcSession.AddIceCandidate(sdpMid, sdpMlineIndex, candidate); } } catch (Exception ex) { Logger.Write(ex); } }); Connection.On("ReceiveRtcAnswer", (string sdp, string viewerID) => { try { if (conductor.Viewers.TryGetValue(viewerID, out var viewer)) { viewer.RtcSession.SetRemoteDescription("answer", sdp); } } catch (Exception ex) { Logger.Write(ex); } }); Connection.On("ClipboardTransfer", (string transferText, bool typeText, string viewerID) => { try { if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl) { if (typeText) { KeyboardMouseInput.SendText(transferText, viewer); } else { ClipboardService.SetText(transferText); } } } catch (Exception ex) { Logger.Write(ex); } }); Connection.On("CtrlAltDel", async(string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl) { await SendCtrlAltDel(); } }); Connection.On("Disconnect", async(string reason) => { Logger.Write($"Disconnecting caster socket. Reason: {reason}"); foreach (var viewer in conductor.Viewers.Values.ToList()) { await Connection.SendAsync("ViewerDisconnected", viewer.ViewerConnectionID); viewer.DisconnectRequested = true; } }); Connection.On("GetScreenCast", (string viewerID, string requesterName) => { try { ScreenCaster.BeginScreenCasting(new ScreenCastRequest() { ViewerID = viewerID, RequesterName = requesterName }); } catch (Exception ex) { Logger.Write(ex); } }); Connection.On("GetWindowsSessions", async(string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer)) { await viewer.SendWindowsSessions(); } }); Connection.On("RequestScreenCast", (string viewerID, string requesterName) => { conductor.InvokeScreenCastRequested(new ScreenCastRequest() { ViewerID = viewerID, RequesterName = requesterName }); }); Connection.On("KeyDown", (string key, string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl) { KeyboardMouseInput.SendKeyDown(key, viewer); } }); Connection.On("KeyUp", (string key, string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl) { KeyboardMouseInput.SendKeyUp(key, viewer); } }); Connection.On("KeyPress", async(string key, string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl) { KeyboardMouseInput.SendKeyDown(key, viewer); await Task.Delay(1); KeyboardMouseInput.SendKeyUp(key, viewer); } }); Connection.On("MouseMove", (double percentX, double percentY, string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl) { KeyboardMouseInput.SendMouseMove(percentX, percentY, viewer); } }); Connection.On("MouseDown", (int button, double percentX, double percentY, string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl) { if (button == 0) { KeyboardMouseInput.SendLeftMouseDown(percentX, percentY, viewer); } else if (button == 2) { KeyboardMouseInput.SendRightMouseDown(percentX, percentY, viewer); } } }); Connection.On("MouseUp", (int button, double percentX, double percentY, string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl) { if (button == 0) { KeyboardMouseInput.SendLeftMouseUp(percentX, percentY, viewer); } else if (button == 2) { KeyboardMouseInput.SendRightMouseUp(percentX, percentY, viewer); } } }); Connection.On("MouseWheel", (double deltaX, double deltaY, string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl) { KeyboardMouseInput.SendMouseWheel(-(int)deltaY, viewer); } }); Connection.On("ViewerDisconnected", async(string viewerID) => { await Connection.SendAsync("ViewerDisconnected", viewerID); if (conductor.Viewers.TryGetValue(viewerID, out var viewer)) { viewer.DisconnectRequested = true; } conductor.InvokeViewerRemoved(viewerID); }); Connection.On("FrameReceived", (int bytesReceived, string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer)) { viewer.WebSocketBuffer = Math.Max(0, viewer.WebSocketBuffer - bytesReceived); } }); Connection.On("SelectScreen", (string displayName, string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer)) { viewer.Capturer.SetSelectedScreen(displayName); } }); Connection.On("QualityChange", (int qualityLevel, string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer)) { viewer.ImageQuality = qualityLevel; } }); Connection.On("AutoQualityAdjust", (bool isOn, string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer)) { viewer.AutoAdjustQuality = isOn; } }); Connection.On("ReceiveFile", async(byte[] buffer, string fileName, string messageId, bool endOfFile, bool startOfFile) => { await FileDownloadService.ReceiveFile(buffer, fileName, messageId, endOfFile, startOfFile); }); Connection.On("ToggleAudio", (bool toggleOn, string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl) { AudioCapturer.ToggleAudio(toggleOn); } }); Connection.On("ToggleBlockInput", (bool toggleOn, string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl) { KeyboardMouseInput.ToggleBlockInput(toggleOn); } }); Connection.On("TouchDown", (string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl) { //User32.GetCursorPos(out var point); //Win32Interop.SendLeftMouseDown(point.X, point.Y); } }); Connection.On("LongPress", (string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl) { //User32.GetCursorPos(out var point); //Win32Interop.SendRightMouseDown(point.X, point.Y); //Win32Interop.SendRightMouseUp(point.X, point.Y); } }); Connection.On("TouchMove", (double moveX, double moveY, string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl) { //User32.GetCursorPos(out var point); //Win32Interop.SendMouseMove(point.X + moveX, point.Y + moveY); } }); Connection.On("TouchUp", (string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl) { //User32.GetCursorPos(out var point); //Win32Interop.SendLeftMouseUp(point.X, point.Y); } }); Connection.On("Tap", (double percentX, double percentY, string viewerID) => { if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl) { KeyboardMouseInput.SendLeftMouseDown(percentX, percentY, viewer); KeyboardMouseInput.SendLeftMouseUp(percentX, percentY, viewer); } }); Connection.On("SharedFileIDs", (List <string> fileIDs) => { fileIDs.ForEach(id => { var url = $"{conductor.Host}/API/FileSharing/{id}"; var webRequest = WebRequest.CreateHttp(url); var response = webRequest.GetResponse(); var contentDisp = response.Headers["Content-Disposition"]; var fileName = contentDisp .Split(";".ToCharArray()) .FirstOrDefault(x => x.Trim().StartsWith("filename")) .Split("=".ToCharArray())[1]; var legalChars = fileName.ToCharArray().Where(x => !Path.GetInvalidFileNameChars().Any(y => x == y)); fileName = new string(legalChars.ToArray()); var dirPath = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "RemotelySharedFiles")).FullName; var filePath = Path.Combine(dirPath, fileName); using (var fs = new FileStream(filePath, FileMode.Create)) { using (var rs = response.GetResponseStream()) { rs.CopyTo(fs); } } Process.Start("explorer.exe", dirPath); }); }); Connection.On("SessionID", (string sessionID) => { conductor.InvokeSessionIDChanged(sessionID); }); }
static Task <WebResponse> ExecHttpRequestInternalAsync(Context ctx, CURLResource ch, Uri uri) { var req = WebRequest.CreateHttp(uri); // setup request: Debug.Assert(ch.Method != null, "Method == null"); req.Method = ch.Method; req.AllowAutoRedirect = ch.FollowLocation; req.Timeout = ch.Timeout; req.ContinueTimeout = ch.ContinueTimeout; req.MaximumAutomaticRedirections = ch.MaxRedirects; if (ch.UserAgent != null) { req.UserAgent = ch.UserAgent; } if (ch.ProtocolVersion != null) { req.ProtocolVersion = ch.ProtocolVersion; } if (ch.Referer != null) { req.Referer = ch.Referer; } if (ch.Headers != null) { AddHeaders(req, ch.Headers); } if (ch.CookieHeader != null) { TryAddCookieHeader(req, ch.CookieHeader); } if (ch.CookieFileSet) { req.CookieContainer = new CookieContainer(); } if (ch.Username != null) { req.Credentials = new NetworkCredential(ch.Username, ch.Password ?? string.Empty); } // TODO: certificate // TODO: proxy // make request: // GET, HEAD if (string.Equals(ch.Method, WebRequestMethods.Http.Get, StringComparison.OrdinalIgnoreCase) || string.Equals(ch.Method, WebRequestMethods.Http.Head, StringComparison.OrdinalIgnoreCase)) { // nothing to do } // POST else if (string.Equals(ch.Method, WebRequestMethods.Http.Post, StringComparison.OrdinalIgnoreCase)) { ProcessPost(ctx, req, ch); } // PUT else if (string.Equals(ch.Method, WebRequestMethods.Http.Put, StringComparison.OrdinalIgnoreCase)) { ProcessPut(req, ch); } // DELETE, or custom method else { // custom method, nothing to do } return(req.GetResponseAsync()); }
// copied from Outlook Power Hour code. public static Attachment GetAttachment(string attachmentId, string authToken, string ewsUrl) { string getAttachmentRequest = @"<?xml version=""1.0"" encoding=""utf-8""?> <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:t=""http://schemas.microsoft.com/exchange/services/2006/types""> <soap:Header> <t:RequestServerVersion Version=""Exchange2013"" /> </soap:Header> <soap:Body> <GetAttachment xmlns=""http://schemas.microsoft.com/exchange/services/2006/messages"" xmlns:t=""http://schemas.microsoft.com/exchange/services/2006/types""> <AttachmentShape/> <AttachmentIds> <t:AttachmentId Id=""{0}""/> </AttachmentIds> </GetAttachment> </soap:Body> </soap:Envelope>"; getAttachmentRequest = String.Format(getAttachmentRequest, attachmentId); // Prepare a web request object. HttpWebRequest webRequest = WebRequest.CreateHttp(ewsUrl); webRequest.Headers.Add("Authorization", string.Format("Bearer {0}", authToken)); webRequest.PreAuthenticate = true; webRequest.AllowAutoRedirect = false; webRequest.Method = "POST"; webRequest.ContentType = "text/xml; charset=utf-8"; // Construct the SOAP message for the GetAttchment operation. byte[] bodyBytes = System.Text.Encoding.UTF8.GetBytes(getAttachmentRequest); webRequest.ContentLength = bodyBytes.Length; Stream requestStream = webRequest.GetRequestStream(); requestStream.Write(bodyBytes, 0, bodyBytes.Length); requestStream.Close(); // Make the request to the Exchange server and get the response. HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); // If the response is okay, create an XML document from the // response and process the request. if (webResponse.StatusCode == HttpStatusCode.OK) { Stream responseStream = webResponse.GetResponseStream(); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(responseStream); string fileName = xmlDocument.GetElementsByTagName("t:Name")[0].InnerText; byte[] bytes = Convert.FromBase64String(xmlDocument.GetElementsByTagName("t:Content")[0].InnerText); // Close the response stream. responseStream.Close(); webResponse.Close(); return(new Attachment() { AttachmentBytes = bytes, AttachmentName = fileName }); } return(null); }
public async Task <string> AsyncTest() { var mapper = SeparatedValueTypeMapper.Define <SampleData>(); mapper.Property(x => x.YearStart).ColumnName("YearStart"); mapper.Property(x => x.YearEnd).ColumnName("YearEnd"); mapper.Property(x => x.LocationAbbreviation).ColumnName("LocationAbbr"); mapper.Property(x => x.LocationDescription).ColumnName("LocationDesc"); mapper.Property(x => x.DataSource).ColumnName("DataSource"); mapper.Property(x => x.Topic).ColumnName("Topic"); mapper.Property(x => x.Question).ColumnName("Question"); mapper.Property(x => x.Response).ColumnName("Response"); mapper.Property(x => x.DataValueUnit).ColumnName("DataValueUnit"); mapper.Property(x => x.DataValueType).ColumnName("DataValueType"); mapper.Property(x => x.DataValue).ColumnName("DataValue"); mapper.Property(x => x.AlternativeDataValue).ColumnName("DataValueAlt"); mapper.Property(x => x.DataValueFootnoteSymbol).ColumnName("DataValueFootnoteSymbol"); mapper.Property(x => x.DataValueFootnote).ColumnName("DatavalueFootnote"); mapper.Property(x => x.LowConfidenceLimit).ColumnName("LowConfidenceLimit"); mapper.Property(x => x.HighConfidenceLimit).ColumnName("HighConfidenceLimit"); mapper.Property(x => x.StratificationCategory1).ColumnName("StratificationCategory1"); mapper.Property(x => x.Stratification1).ColumnName("Stratification1"); mapper.Property(x => x.StratificationCategory2).ColumnName("StratificationCategory2"); mapper.Property(x => x.Stratification2).ColumnName("Stratification2"); mapper.Property(x => x.StratificationCategory3).ColumnName("StratificationCategory3"); mapper.Property(x => x.Stratification3).ColumnName("Stratification3"); mapper.CustomProperty(x => x.GeoLocation, new GeoLocationColumn("GeoLocation")); mapper.Property(x => x.ResponseId).ColumnName("ResponseID"); mapper.Property(x => x.LocationId).ColumnName("LocationID"); mapper.Property(x => x.TopicId).ColumnName("TopicID"); mapper.Property(x => x.QuestionId).ColumnName("QuestionID"); mapper.Property(x => x.DataValueTypeId).ColumnName("DataValueTypeID"); mapper.Property(x => x.StratificationCategoryId1).ColumnName("StratificationCategoryID1"); mapper.Property(x => x.StratificationId1).ColumnName("StratificationID1"); mapper.Property(x => x.StratificationCategoryId2).ColumnName("StratificationCategoryID2"); mapper.Property(x => x.StratificationId2).ColumnName("StratificationID2"); mapper.Property(x => x.StratificationCategoryId3).ColumnName("StratificationCategoryID3"); mapper.Property(x => x.StratificationId3).ColumnName("StratificationID3"); StringWriter textWriter = new StringWriter(); var http = WebRequest.CreateHttp("https://raw.githubusercontent.com/jehugaleahsa/FlatFiles/master/FlatFiles.Benchmark/TestFiles/SampleData.csv"); using (var response = await http.GetResponseAsync()) using (var textReader = new StreamReader(response.GetResponseStream())) { var reader = mapper.GetReader(textReader, new SeparatedValueOptions() { IsFirstRecordSchema = true }); var writer = mapper.GetWriter(textWriter, new SeparatedValueOptions() { IsFirstRecordSchema = true }); while (await reader.ReadAsync()) { await writer.WriteAsync(reader.Current); } } return(textWriter.ToString()); //StringWriter textWriter = new StringWriter(); //string directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); //string path = Path.Combine(directory, "TestFiles", "SampleData.csv"); //using (var stream = File.OpenRead(path)) //using (var textReader = new StreamReader(stream)) //{ // var options = new SeparatedValueOptions() { IsFirstRecordSchema = true }; // var reader = mapper.GetReader(textReader, options); // var writer = mapper.GetWriter(textWriter, options); // while (await reader.ReadAsync()) // { // await writer.WriteAsync(reader.Current); // } //} //return textWriter.ToString(); }
public N Connect <N>(string url, Func <HttpWebResponse, N> f) => Using(WebRequest.CreateHttp(url).GetResponse(), conn => f((HttpWebResponse)conn));
private async Task <Reply> HandleRequest(string method, string requestUri, params string[] requestBody) { Reply result = new Reply(); result.bIsSuccessful = false; currentState = EState.AuthInProgress; GoogleOAuth2.Token activeToken = await GoogleOAuth2.GetAuthorizationToken(clientId, authToken); if (activeToken != null && activeToken.IsValidForAuth()) { authToken = activeToken; currentState = EState.NoErrors; HttpWebRequest request = WebRequest.CreateHttp(requestUri); request.Method = method; request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + authToken.accessToken); SetRequestContent(request, requestBody); WebResponse rawResponse = null; try { rawResponse = await request.GetResponseAsync(); } catch (WebException ex) { lastApiResponse = ex.Message; } catch (Exception ex) { lastApiResponse = "Exception: " + ex; } HttpWebResponse response = (HttpWebResponse)rawResponse; result.response = response; if (response != null) { lastApiResponse = response.StatusDescription; if (response.StatusCode == HttpStatusCode.OK) { string responseBody = null; if (response.ContentLength > 0) { byte[] contentBytes = new byte[response.ContentLength]; Stream contentStream = response.GetResponseStream(); contentStream.Read(contentBytes, 0, contentBytes.Length); contentStream.Close(); responseBody = Encoding.UTF8.GetString(contentBytes); } result.bIsSuccessful = true; result.contentBody = responseBody; } } } else { currentState = EState.NotAuthorized; } return(result); }
//http://ergast.com/api/f1/drivers?offset=30&limit=30 public async Task ImportDrivers() { await Task.FromResult(true); int offset = 0; int limit = 30; bool keepGoing = true; while (keepGoing) { var driverGetsUrl = $"http://ergast.com/api/f1/drivers?offset={offset}&limit={limit}"; var request = WebRequest.CreateHttp(driverGetsUrl); var response = request.GetResponse(); XmlSerializer sr = new XmlSerializer(typeof(MRDataType)); var data = (MRDataType)sr.Deserialize(response.GetResponseStream()); Console.WriteLine($"Offset {offset}"); if (data.DriverTable.Driver.Length == 0) { break; } foreach (var driver in data.DriverTable.Driver) { if (!string.IsNullOrEmpty(driver.PermanentNumber)) { continue; } Console.WriteLine($"Adding {driver.GivenName} {driver.FamilyName}"); var res = await Program.HTTPCLIENT.PostAsJsonAsync <Driver>("Driver/adddriver", new Driver { Country = driver.Nationality, DriverNumber = string.IsNullOrEmpty(driver.PermanentNumber) ? -1 : Convert.ToInt32(driver.PermanentNumber), FirstName = driver.GivenName, LastName = driver.FamilyName }); var respo = await res.Content.ReadFromJsonAsync <AddItemResponse>(); if (respo.IsError) { Console.WriteLine(respo.Message); } else { Console.WriteLine(respo.NewItemId); } } offset += limit; if (offset > Convert.ToInt32(data.total)) { break; } } return; }
private async void GetImageAutomatic_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrWhiteSpace(Protocol.Text)) { EmptyTip.Target = Protocol; EmptyTip.IsOpen = true; return; } switch (Type) { case QuickStartType.Application: case QuickStartType.UpdateApp: { if (Uri.TryCreate(Protocol.Text, UriKind.Absolute, out Uri Result)) { if (Result.IsFile) { if (WIN_Native_API.CheckExist(Protocol.Text)) { try { StorageFile ExcuteFile = await StorageFile.GetFileFromPathAsync(Protocol.Text); DisplayName.Text = Convert.ToString((await ExcuteFile.Properties.RetrievePropertiesAsync(new string[] { "System.FileDescription" }))["System.FileDescription"]); if (await ExcuteFile.GetThumbnailBitmapAsync().ConfigureAwait(true) is BitmapImage Image) { Icon.Source = Image; } else { Icon.Source = new BitmapImage(new Uri("ms-appx:///Assets/Page_Solid_White.png")); } RenderTargetBitmap RTB = new RenderTargetBitmap(); await RTB.RenderAsync(Icon); StorageFile FileThumbnail = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("FileThumbnail.png", CreationCollisionOption.ReplaceExisting); using (IRandomAccessStream Stream = await FileThumbnail.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder Encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, Stream); byte[] PixelData = (await RTB.GetPixelsAsync()).ToArray(); Encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)RTB.PixelWidth, (uint)RTB.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, PixelData); await Encoder.FlushAsync(); } ImageFile = FileThumbnail; } catch { FailureTips.IsOpen = true; } } else { FailureTips.IsOpen = true; } } else { if ((await Launcher.FindUriSchemeHandlersAsync(Result.Scheme)).ToList().FirstOrDefault() is AppInfo App) { DisplayName.Text = App.DisplayInfo.DisplayName; using (IRandomAccessStreamWithContentType LogoStream = await App.DisplayInfo.GetLogo(new Windows.Foundation.Size(120, 120)).OpenReadAsync()) { BitmapDecoder Decoder = await BitmapDecoder.CreateAsync(LogoStream); using (SoftwareBitmap SBitmap = await Decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied)) using (SoftwareBitmap ResizeBitmap = ComputerVisionProvider.ResizeToActual(SBitmap)) { StorageFile FileThumbnail = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("FileThumbnail.png", CreationCollisionOption.ReplaceExisting); using (IRandomAccessStream Stream = await FileThumbnail.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder Encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, Stream); Encoder.SetSoftwareBitmap(ResizeBitmap); await Encoder.FlushAsync(); } ImageFile = FileThumbnail; using (IRandomAccessStream Stream = await FileThumbnail.OpenAsync(FileAccessMode.Read)) { BitmapImage Source = new BitmapImage(); await Source.SetSourceAsync(Stream); Icon.Source = Source; } } } } else { FormatErrorTip.IsOpen = true; } } } else { FormatErrorTip.IsOpen = true; } break; } case QuickStartType.WebSite: case QuickStartType.UpdateWeb: { try { if (Uri.TryCreate(Protocol.Text, UriKind.Absolute, out Uri Result)) { Uri ImageUri = new Uri(Result, "favicon.ico"); HttpWebRequest Request = WebRequest.CreateHttp(ImageUri); using (WebResponse Response = await Request.GetResponseAsync().ConfigureAwait(true)) using (Stream ImageStream = Response.GetResponseStream()) { StorageFile DownloadImage = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("DownloadFile.ico", CreationCollisionOption.ReplaceExisting); using (Stream FileStream = await DownloadImage.OpenStreamForWriteAsync().ConfigureAwait(true)) { await ImageStream.CopyToAsync(FileStream).ConfigureAwait(true); } ImageFile = DownloadImage; } Icon.Source = new BitmapImage(ImageUri); } else { FailureTips.IsOpen = true; } } catch { try { Uri QueryUrl = Globalization.CurrentLanguage == LanguageEnum.Chinese_Simplified ? new Uri($"http://statics.dnspod.cn/proxy_favicon/_/favicon?domain={new Uri(Protocol.Text).Host}") : new Uri($"http://www.google.com/s2/favicons?domain={new Uri(Protocol.Text).Host}"); HttpWebRequest Request = WebRequest.CreateHttp(QueryUrl); using (WebResponse Response = await Request.GetResponseAsync().ConfigureAwait(true)) using (Stream ImageStream = Response.GetResponseStream()) { StorageFile DownloadImage = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("DownloadFile.ico", CreationCollisionOption.ReplaceExisting); using (Stream FileStream = await DownloadImage.OpenStreamForWriteAsync().ConfigureAwait(true)) { await ImageStream.CopyToAsync(FileStream).ConfigureAwait(true); } ImageFile = DownloadImage; } Icon.Source = new BitmapImage(QueryUrl); } catch { FailureTips.IsOpen = true; } } break; } } }
private string getLatTrans(string voc, bool inf) { HttpWebRequest request = WebRequest.CreateHttp("https://www.latein.me/latein/" + voc); request.KeepAlive = false; request.ContentType = "text/html"; request.Date = DateTime.UtcNow; WebResponse rawresponse; try { rawresponse = request.GetResponse(); } catch (WebException ex) { return(ex.Message); } //if(rawresponse StreamReader response = new StreamReader(rawresponse.GetResponseStream()); string VocLine = ""; bool hasntVocLine = true; while (hasntVocLine) { string tmp = response.ReadLine(); if (tmp.Contains("<div class=\"contentBox\">")) { hasntVocLine = false; VocLine = tmp; } } response.Close(); //VocLinePrep //VocLine = VocLine.Replace("",""); if (inf) { string[] infinitives = VocLine.Split(new string[] { "<dt class=\"translationEntryBox\">" }, StringSplitOptions.RemoveEmptyEntries); infinitives[0] = ""; for (int i = 0; i < infinitives.Length; i++) { string[] tmp = infinitives[i].Split(new char[] { '<', '>' }, StringSplitOptions.RemoveEmptyEntries); if (tmp.Length > 1) { infinitives[i] = tmp[1]; } } //TODO!! StringBuilder output = new StringBuilder(); foreach (string s in infinitives) { if (s != "") { output.Append(s); output.Append(" oder "); } } if (output.Length > 6) { output.Remove(output.Length - 6, 6); } return(output.ToString()); } else { //VocLineParser string[] translation = VocLine.Split(new string[] { "<dd class=\"translationEntry\">" }, StringSplitOptions.RemoveEmptyEntries); string[] formAnalysis = VocLine.Split(new string[] { "<dd class=\"formAnalysisEntry\">" }, StringSplitOptions.RemoveEmptyEntries); Console.Write("H"); translation[0] = ""; formAnalysis[0] = ""; for (int i = 0; i < translation.Length; i++) { string[] tmp = translation[i].Split(new char[] { '<', '>' }, StringSplitOptions.RemoveEmptyEntries); if (tmp.Length > 1) { translation[i] = tmp[1]; } } for (int i = 0; i < formAnalysis.Length; i++) { string[] tmp = formAnalysis[i].Split(new char[] { '<', '>' }, StringSplitOptions.RemoveEmptyEntries); if (tmp.Length > 0) { formAnalysis[i] = tmp[0]; } } StringBuilder output = new StringBuilder(); foreach (string s in translation) { if (s != "" & output.Length < 100) { output.Append(s); output.Append(" oder "); } } output.Remove(output.Length - 6, 6); //output.Append("; Formbestimmung: "); //foreach (string s in formAnalysis) //{ // if (s != "") // { // output.Append(s); // output.Append(" oder "); // } //} //output.Remove(output.Length - 6, 6); return(output.ToString()); } }
//流模式post public string Post(string url, string data, Encoding encoding, int type = 3) { HttpWebRequest req = null; HttpWebResponse rsp = null; Stream reqStream = null; //Stream resStream = null; try { req = WebRequest.CreateHttp(new Uri(url)); if (type == 1) { req.ContentType = "application/json;charset=utf-8"; } else if (type == 2) { req.ContentType = "application/xml;charset=utf-8"; } else { req.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; } req.Method = "POST"; //req.Accept = "text/xml,text/javascript"; req.ContinueTimeout = 60000; byte[] postData = encoding.GetBytes(data); reqStream = req.GetRequestStreamAsync().Result; reqStream.Write(postData, 0, postData.Length); //reqStream.Dispose(); rsp = (HttpWebResponse)req.GetResponseAsync().Result; string result = GetResponseAsString(rsp, encoding); return(result); } catch (Exception ex) { throw ex; } finally { // 释放资源 if (reqStream != null) { reqStream.Close(); reqStream = null; } if (rsp != null) { rsp.Close(); rsp = null; } if (req != null) { req.Abort(); req = null; } } }
protected virtual string SendReceivetHttp() { string str1 = this.EncryptPassword(this.InboundXML); if (this.Settings.LogXml) this.LogDocument("XmlRequest", str1); byte[] bytes = Encoding.Unicode.GetBytes(str1); bool flag = ApplicationProtocol.Https == this.Settings.Protocol; UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Host = this.Settings.Host; uriBuilder.Path = this.Settings.AppServerUriStem; if (!string.IsNullOrWhiteSpace(uriBuilder.Path)) { if (!uriBuilder.Path.EndsWith("/")) uriBuilder.Path += "/"; } else uriBuilder.Path = "/"; uriBuilder.Scheme = flag ? "https" : "http"; if (flag && 443 != this.Settings.Port || !flag && 80 != this.Settings.Port) uriBuilder.Port = this.Settings.Port; if (-1 != this.InboundXML.IndexOf("<__service")) { uriBuilder.Path += "service/"; int startIndex = this.InboundXML.IndexOf("__serviceType=\"") + "__serviceType =\"".Length - 1; string str2 = this.InboundXML.Substring(startIndex, this.InboundXML.IndexOf("\">", startIndex) - startIndex); uriBuilder.Path += str2; } else if (-1 != this.InboundXML.IndexOf("<__query")) uriBuilder.Path += "query/"; else if (-1 != this.InboundXML.IndexOf("<__requestData")) { if (-1 != this.InboundXML.IndexOf("<__metadata")) { if (-1 != this.InboundXML.IndexOf("<__label")) uriBuilder.Path += "label/"; else uriBuilder.Path += "metadata/"; } else uriBuilder.Path += "requestdata/"; } HttpWebRequest http = WebRequest.CreateHttp(uriBuilder.Uri); http.Method = "POST"; http.ContentType = "application/xml; charset=utf-16le"; http.AllowWriteStreamBuffering = true; http.AllowAutoRedirect = false; http.PreAuthenticate = false; http.CookieContainer = new CookieContainer(); http.KeepAlive = true; http.SendChunked = false; http.Accept = "application/xml; charset=utf-16le"; http.Headers.Add(HttpRequestHeader.AcceptCharset, "utf-16le"); http.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; if (flag) http.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(this.RemoteCertificateValidationCallback); http.GetRequestStream().Write(bytes, 0, bytes.Length); HttpWebResponse response = (HttpWebResponse) http.GetResponse(); string document = string.Empty; if (response.ContentLength != 0L) { Encoding encoding = Encoding.Unicode; try { encoding = Encoding.GetEncoding(response.CharacterSet); } catch { } document = new StreamReader(response.GetResponseStream(), encoding).ReadToEnd(); } if (this.Settings.LogXml) this.LogDocument("XmlResponse", document); return document; }
public static async Task <string> Download(string content) { var errorCount = 0; Retry: try { var fileName = Path.Combine(Vars.CacheDir, Conf.GetRandomFileName() + "USER.mp3"); Bridge.ALog($"(E5) 正在下载 TTS, 文件名: {fileName}, 方法: {Vars.CurrentConf.ReqType}"); if (Vars.CurrentConf.ReqType == RequestType.ApplicationXWwwFormUrlencoded || Vars.CurrentConf.ReqType == RequestType.TextPlain) { Bridge.ALog("POST 模式: text/plain / application/x-www-form-urlencoded"); // 配置 Headers var uploader = WebRequest.CreateHttp(Vars.CurrentConf.CustomEngineURL); uploader.Method = "POST"; if (Vars.CurrentConf.HttpAuth) { uploader.Credentials = new NetworkCredential(Vars.CurrentConf.HttpAuthUsername, Vars.CurrentConf.HttpAuthPassword); uploader.PreAuthenticate = true; } foreach (var header in Vars.CurrentConf.Headers) { Bridge.ALog($"添加 Header: {header.Name}, 值 {header.Value}"); uploader.Headers.Add(header.Name, header.Value); } uploader.ContentType = Vars.CurrentConf.ReqType == RequestType.ApplicationXWwwFormUrlencoded ? "application/x-www-form-urlencoded" : "text/plain"; // 准备数据 var data = Encoding.UTF8.GetBytes(Vars.CurrentConf.PostData); var dataStream = uploader.GetRequestStream(); dataStream.Write(data, 0, data.Length); dataStream.Close(); uploader.ContentLength = data.Length; // 等响应 using (var res = uploader.GetResponse()) { // 写数据 using (var writer = new StreamWriter(File.OpenWrite(fileName)) { AutoFlush = true }) { byte[] responseData = new byte[res.ContentLength]; res.GetResponseStream().Read(responseData, 0, responseData.Length); writer.Write(responseData); } } } else if (Vars.CurrentConf.ReqType == RequestType.MultipartFormData) { using (var httpClient = new HttpClient()) { var form = new MultipartFormDataContent(); // 配置 Headers if (Vars.CurrentConf.HttpAuth) { var authArray = Encoding.UTF8.GetBytes($"{Vars.CurrentConf.HttpAuthUsername}:{Vars.CurrentConf.HttpAuthPassword}"); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authArray)); } foreach (var header in Vars.CurrentConf.Headers) { Bridge.ALog($"添加 Header: {header.Name}, 值 {header.Value}"); httpClient.DefaultRequestHeaders.Add(header.Name, header.Value); } // 转换数据 var postItems = JsonConvert.DeserializeObject <List <Header> >(Vars.CurrentConf.PostData); foreach (var item in postItems) { var data = Convert.FromBase64String(item.Value); form.Add(new ByteArrayContent(data, 0, data.Length), item.Name); } // 抓结果 using (var res = await httpClient.PostAsync(Vars.CurrentConf.CustomEngineURL, form)) { res.EnsureSuccessStatusCode(); // 写数据 using (var writer = new StreamWriter(File.OpenWrite(fileName)) { AutoFlush = true }) { var responseData = await res.Content.ReadAsByteArrayAsync(); writer.Write(responseData); } } } } else { Bridge.ALog("GET 模式"); using (var downloader = new WebClient()) { downloader.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"); foreach (var header in Vars.CurrentConf.Headers) { Bridge.ALog($"添加 Header: {header.Name}, 值 {header.Value}"); downloader.Headers.Add(header.Name, header.Value); } if (Vars.CurrentConf.HttpAuth) { downloader.Credentials = new NetworkCredential(Vars.CurrentConf.HttpAuthUsername, Vars.CurrentConf.HttpAuthPassword); } await downloader.DownloadFileTaskAsync(Vars.CurrentConf.CustomEngineURL.Replace("$TTSTEXT", content), fileName); } } // validate if file is playable using (var reader = new AudioFileReader(fileName)) { } return(fileName); } catch (Exception ex) { Bridge.ALog($"(E5) TTS 下载失败: {ex.Message}"); errorCount += 1; Vars.TotalFails++; if (errorCount <= Vars.CurrentConf.DownloadFailRetryCount) { goto Retry; } return(null); } }
async void downloadfile(JSONFile jfile) { if (jfile.Size.ToLower().Contains("mb") || jfile.Size.ToLower().Contains("gb")) { if (EnsureUnsnapped()) { FileSavePicker savePicker = new FileSavePicker(); savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as savePicker.FileTypeChoices.Add(string.IsNullOrEmpty(jfile.Type) ? jfile.Extension : jfile.Type, new List <string>() { jfile.Extension }); // Default file name if the user does not type one in or select a file to replace savePicker.SuggestedFileName = jfile.Name; StorageFile file = await savePicker.PickSaveFileAsync(); Uri uri = new Uri(HAPSettings.CurrentSite.Address, jfile.Path.Substring(1)); BackgroundDownloader downloader = new BackgroundDownloader(); downloader.Method = "GET"; downloader.SetRequestHeader("Cookie", string.Format("{0}={1}; token={2}", HAPSettings.CurrentToken[2], HAPSettings.CurrentToken[1], HAPSettings.CurrentToken[0])); DownloadOperation download = downloader.CreateDownload(uri, file); // Attach progress and completion handlers. HandleDownloadAsync(download, true); MessageDialog mes = new MessageDialog("The download of " + jfile.Name + " has started, you will get notified when it's done", "Downloading"); mes.Commands.Add(new UICommand("OK")); mes.DefaultCommandIndex = 0; mes.ShowAsync(); var ignored3 = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { pro.Visibility = Windows.UI.Xaml.Visibility.Collapsed; loading.IsIndeterminate = false; }); } } else { HttpWebRequest req = WebRequest.CreateHttp(new Uri(HAPSettings.CurrentSite.Address, jfile.Path.Substring(1))); req.Method = "GET"; req.Headers = new WebHeaderCollection(); req.CookieContainer = new CookieContainer(); req.CookieContainer.Add(HAPSettings.CurrentSite.Address, new Cookie("token", HAPSettings.CurrentToken[0])); req.CookieContainer.Add(HAPSettings.CurrentSite.Address, new Cookie(HAPSettings.CurrentToken[2], HAPSettings.CurrentToken[1])); req.AllowReadStreamBuffering = false; req.BeginGetResponse(a => { using (WebResponse response = req.EndGetResponse(a)) { int expected = (int)response.ContentLength; using (System.IO.BinaryReader reader = new BinaryReader(response.GetResponseStream())) { MemoryStream ms = new MemoryStream(expected); bool canwrite = true; long count = 0; int x = 0; while (canwrite) { try { ms.WriteByte(reader.ReadByte()); } catch { canwrite = false; } count++; x++; if (x == 100) { x = 0; try { var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { try { pro.Value = count * 100.0 / expected; } catch { } }); } catch { } } } var ignored1 = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { makefile(ms, (JSONFile)a.AsyncState); }); } } } , jfile); } }
public void HttpWebRequest_TimeOutDefaultGet_Ok() { HttpWebRequest request = WebRequest.CreateHttp(Configuration.Http.RemoteEchoServer); Assert.Equal(100000, request.Timeout); }
protected override PropertyBagDataItem[] GetOutputData(DataItemBase[] inputDataItems) { var result = new List <PropertyBagDataItem>(); var bagItem = new Dictionary <string, object>(); try { var requestUri = new UriBuilder(_testUri) { Path = _path }; string hostHeader = null; if (_customDnsServers.Count > 0) { // is custom DNS used, then URI is like https://192.168.1.1/path, but Host header is set to the actual host name hostHeader = requestUri.Host; requestUri.Host = TcpHelper.ResolveHostName(hostHeader, _customDnsServers.ToArray())[0].ToString(); // IP address } // prepare request var request = WebRequest.CreateHttp(requestUri.Uri); request.Method = _method; if (hostHeader != null) { request.Host = hostHeader; } TcpHelper.SetHeaders(request, _headers); if (!string.IsNullOrEmpty(_userAgent)) { request.UserAgent = _userAgent; } if (!string.IsNullOrWhiteSpace(_authenticationScheme)) { var cachedCreds = new CredentialCache(); if (string.IsNullOrWhiteSpace(_authenticationDomain)) { cachedCreds.Add(_testUri, _authenticationScheme, new NetworkCredential(_authenticationUserName, _authenticationPassword)); } else { cachedCreds.Add(_testUri, _authenticationScheme, new NetworkCredential(_authenticationUserName, _authenticationPassword, _authenticationDomain)); } request.Credentials = cachedCreds; } request.AllowAutoRedirect = _allowRedirection; // Execute the request using (var response = request.GetResponse()) { var responseStream = response.GetResponseStream(); using (var reader = new StreamReader(responseStream, Encoding.UTF8)) { string fullResponse = reader.ReadToEnd(); if (!string.IsNullOrWhiteSpace(_pageExpression) && !Regex.IsMatch(fullResponse, _pageExpression)) { bagItem.Add("State", "WARNING"); bagItem.Add("Error", "Page regular expression does not match."); bagItem.Add("Response", fullResponse.Substring(0, fullResponse.Length >= 255 ? 255 : fullResponse.Length)); bagItem.Add("ResponseLength", fullResponse.Length); } else { bagItem.Add("State", "OK"); bagItem.Add("Error", ""); bagItem.Add("Response", fullResponse.Substring(0, fullResponse.Length >= 255 ? 255 : fullResponse.Length)); bagItem.Add("ResponseLength", fullResponse.Length); } } } } catch (Exception e) { bagItem.Add("State", "ERROR"); bagItem.Add("Error", e.Message); bagItem.Add("Response", string.Empty); bagItem.Add("ResponseLength", 0); } finally { result.Add(new PropertyBagDataItem(null, new Dictionary <string, Dictionary <string, object> > { { string.Empty, bagItem } })); } return(result.ToArray()); }