public AnimeTorrents(IIndexerManagerService i, HttpWebClient c, Logger l, IProtectionService ps) : base(name: "AnimeTorrents", description: "Definitive source for anime and manga", link: "http://animetorrents.me/", caps: new TorznabCapabilities(), manager: i, client: c, // Forced HTTP client for custom headers logger: l, p: ps, configData: new ConfigurationDataBasicLogin()) { Encoding = Encoding.GetEncoding("UTF-8"); Language = "en-us"; Type = "private"; AddCategoryMapping(1, TorznabCatType.MoviesSD); // Anime Movie AddCategoryMapping(6, TorznabCatType.MoviesHD); // Anime Movie HD AddCategoryMapping(2, TorznabCatType.TVAnime); // Anime Series AddCategoryMapping(7, TorznabCatType.TVAnime); // Anime Series HD AddCategoryMapping(5, TorznabCatType.XXXDVD); // Hentai (censored) AddCategoryMapping(9, TorznabCatType.XXXDVD); // Hentai (censored) HD AddCategoryMapping(4, TorznabCatType.XXXDVD); // Hentai (un-censored) AddCategoryMapping(8, TorznabCatType.XXXDVD); // Hentai (un-censored) HD AddCategoryMapping(13, TorznabCatType.BooksForeign); // Light Novel AddCategoryMapping(3, TorznabCatType.BooksComics); // Manga AddCategoryMapping(10, TorznabCatType.BooksComics); // Manga 18+ AddCategoryMapping(11, TorznabCatType.TVAnime); // OVA AddCategoryMapping(12, TorznabCatType.TVAnime); // OVA HD AddCategoryMapping(14, TorznabCatType.BooksComics); // Doujin Anime AddCategoryMapping(15, TorznabCatType.XXXDVD); // Doujin Anime 18+ AddCategoryMapping(16, TorznabCatType.AudioForeign); // Doujin Music AddCategoryMapping(17, TorznabCatType.BooksComics); // Doujinshi AddCategoryMapping(18, TorznabCatType.BooksComics); // Doujinshi 18+ AddCategoryMapping(19, TorznabCatType.Audio); // OST }
/// <summary> /// 订单号生成 /// </summary> /// <returns></returns> public Order CreateOrderNo() { string url = "http://o2oapi.aladingyidong.com/OnlineShopping/data/Data.aspx?action=setOrderInfo&ReqContent={\"common\":{\"openId\":\"oxbbcjrc2RgSbCyYt_5fYMvmqqtE\",\"customerId\":\"e703dbedadd943abacf864531decdac1\",\"userId\":\"8a52e19010474d5283b224a38b4f0aa5\",\"locale\":null},\"special\":{\"qty\":1,\"totalAmount\":33,\"action\":\"setOrderInfo\",\"orderDetailList\":[{\"skuId\":\"\",\"salesPrice\":33,\"qty\":1}]}}"; //Request Create Service return(HttpWebClient.DoHttpRequest(url, string.Empty).DeserializeJSONTo <Order>()); }
/// <summary> /// Get attendee by session id and email /// </summary> /// <param name="sessionId"></param> /// <param name="email"></param> /// <returns></returns> public AttendeeView GetByEmail(string sessionId, string email, out ApiErrorResponse error) { if (String.IsNullOrEmpty(sessionId)) { throw new ArgumentNullException(nameof(sessionId)); } if (String.IsNullOrEmpty(email)) { throw new ArgumentNullException(nameof(email)); } var request = HttpWebClient.CreateWebRequest("GET", BuildRoute($"session/{sessionId}/attendee/{email}")); var response = HttpWebClient.SendWebRequest(request); AttendeeView attendeeView = null; error = null; if (response != null) { string result = HttpWebClient.GetResponseBody(response); if (response.StatusCode == HttpStatusCode.OK) { attendeeView = result.ToObject <AttendeeView>(); } else { error = response.ToErrorResponse(); } } return(attendeeView); }
public async Task <CADComic> GetComicAsync() { if (rateLimiter.IsRatelimited()) { return(null); } (var doc, var redirect) = await HttpWebClient.ScrapeUrlAsync(new Uri("https://cad-comic.com/random")).ConfigureAwait(false); var html = doc.DocumentNode.ChildNodes.FirstOrDefault(x => x.Name == "html"); var body = html.ChildNodes.FirstOrDefault(x => x.Name == "body"); var container = body.ChildNodes.Where(x => x.Attributes.Contains("class") && x.Attributes["class"].Value.Contains("container")).FirstOrDefault(z => z.ChildNodes.Any(x => x.Attributes.Contains("class") && x.Attributes["class"].Value.Contains("col-md-8 main-content"))); var container2 = container.ChildNodes.FirstOrDefault(x => x.Attributes.Contains("class") && x.Attributes["class"].Value.Contains("col-md-8 main-content")); var content = container2.ChildNodes.FirstOrDefault(x => x.Name == "article"); var comicview = content.ChildNodes.FirstOrDefault(x => x.HasClass("comicpage")); var comicholder = comicview.ChildNodes.LastOrDefault(x => x.Name == "a"); var comicmeta = content.ChildNodes.FirstOrDefault(x => x.Attributes.Contains("id") && x.Attributes["id"].Value == "comicblog").ChildNodes.FirstOrDefault(x => x.HasClass("blog-wrap")); var comicinfo = comicmeta.ChildNodes.FirstOrDefault(x => x.Attributes.Contains("class") && x.Attributes["class"].Value == "blog-meta-wrap"); var comicurl = comicinfo.ChildNodes.FirstOrDefault(x => x.Name == "a"); var comicdate = comicinfo.ChildNodes.FirstOrDefault(x => x.Name == "p").InnerText.Replace(" by Tim", ""); return(new CADComic { ImageURL = comicholder.FirstChild.Attributes["src"].Value, Title = comicurl.InnerText, Uploaded = DateTime.Parse(comicdate).ToString("dd'/'MM'/'yyyy"), URL = comicurl.Attributes["href"].Value }); }
/// <summary> /// Changes user's password. /// </summary> /// <param name="userId"></param> /// <param name="password"></param> /// <returns></returns> public bool ChangeUserPassword(string userId, string password, out ApiErrorResponse error) { if (String.IsNullOrEmpty(userId)) { throw new ArgumentNullException(nameof(userId)); } if (String.IsNullOrEmpty(password)) { throw new ArgumentNullException(nameof(password)); } var request = HttpWebClient.CreateWebRequest("PUT", BuildRoute($"user/{userId}/password?password={password}")); var response = HttpWebClient.SendWebRequest(request, password); error = null; bool success = false; if (response != null) { success = response.StatusCode == HttpStatusCode.NoContent; if (!success) { error = response.ToErrorResponse(); } } return(success); }
/// <summary> /// Updates a user /// </summary> /// <param name="user"></param> /// <returns></returns> public UserView UpdateUser(string user_id, PostUserView user, out ApiErrorResponse error) { if (user is null) { throw new ArgumentNullException(nameof(user)); } var request = HttpWebClient.CreateWebRequest("PUT", BuildRoute($"user/{user_id}")); var response = HttpWebClient.SendWebRequest(request, user); UserView userView = null; error = null; if (response != null) { string result = HttpWebClient.GetResponseBody(response); if (response.StatusCode == HttpStatusCode.OK) { userView = result.ToObject <UserView>(); } else { error = response.ToErrorResponse(); } } return(userView); }
public void Get() { HttpWebServer aHttpListener = new HttpWebServer("http://127.0.0.1:8094/"); try { aHttpListener.StartListening(x => { if (x.Request.HttpMethod == "GET") { x.SendResponseMessage("blabla"); } else { x.Response.StatusCode = 404; } }); HttpWebResponse aWebResponse = HttpWebClient.Get(new Uri("http://127.0.0.1:8094/hello/")); Assert.AreEqual(HttpStatusCode.OK, aWebResponse.StatusCode); string aResponseMessage = aWebResponse.GetResponseMessageStr(); Assert.AreEqual("blabla", aResponseMessage); } finally { aHttpListener.StopListening(); } }
protected string getHttpProxy(string url, Dictionary <string, string> header = null) { try { WebHeaderCollection webHeaderCollection = new WebHeaderCollection(); CookieCollection cookies = new CookieCollection(); string accept = ""; if (header != null) { foreach (KeyValuePair <string, string> kv in header) { if (kv.Key == "Accept") { accept = kv.Value; } else { webHeaderCollection.Add(kv.Key, kv.Value); } } } if (int.Parse(getOptions()["EnableProxy"]) > 0) { return(Encoding.UTF8.GetString(HttpWebClient.Get(url, "", "", accept, 0, ref cookies, ref webHeaderCollection, new WebProxy(getProxyAddress(), getProxyPort()), Encoding.UTF8))); } else { return(Encoding.UTF8.GetString(HttpWebClient.Get(url, "", "", accept, 0, ref cookies, ref webHeaderCollection, null, Encoding.UTF8))); } } catch (WebException) { return(""); } }
private void Client_UploadProgressChanged(object sender, System.Net.UploadProgressChangedEventArgs e) { try { //Thread.Sleep(20); HttpWebClient <AddAttachmentDto> hbc = sender as HttpWebClient <AddAttachmentDto>; AddAttachmentDto dtos = hbc.obj as AddAttachmentDto; AddAttachmentDto changed = _attachment.SingleOrDefault(m => m.fileGuid == (hbc.obj as AddAttachmentDto).fileGuid); if (e.ProgressPercentage != 100) { changed.btnStatus = e.ProgressPercentage + "%"; if (changed.btnforeground != "2") { changed.btnforeground = "2"; } } else { changed.btnforeground = "0"; changed.btnStatus = "上传成功"; } //Console.WriteLine(e.ProgressPercentage.ToString()); } catch (Exception ex) { LogHelper.WriteError("[NoticeAddWindowViewModel_UploadProgressChanged]:" + ex.Message + ex.StackTrace + ex.Source); } }
public void Delete() { HttpWebServer aHttpListener = new HttpWebServer("http://127.0.0.1:8094/"); try { aHttpListener.StartListening(x => { if (x.Request.HttpMethod == "DELETE") { // OK //x.Response.StatusCode = 200; } else { x.Response.StatusCode = 404; } }); HttpWebResponse aWebResponse = HttpWebClient.Delete(new Uri("http://127.0.0.1:8094/hello/")); Assert.AreEqual(HttpStatusCode.OK, aWebResponse.StatusCode); } finally { aHttpListener.StopListening(); } }
private async void GetListOfPersons() { MainViewModel.ProgressBarInProgress = Visibility.Visible; await Task.Run(() => { MainViewModel.StatusMessage = "Getting Persons..."; string responseStream; try { responseStream = HttpWebClient.SendRequest($"{GetPersonsUri}{NumberOfPersonsToFetch}", "GET", null, null); var ser = new DataContractJsonSerializer(typeof(ServiceResult <Person>)); MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(responseStream)); var result = ser.ReadObject(ms) as ServiceResult <Person>; Persons = result.Result.ToList(); MainViewModel.StatusMessage = "Finished getting list of persons."; } catch (Exception ex) { responseStream = ""; Persons = new List <Person> { }; MainViewModel.StatusMessage = ex.Message; } MainViewModel.ProgressBarInProgress = Visibility.Hidden; }); }
public LocalUserLogonerForAccessThroughGroup(string username, string password, string groupname, IWebServer webServer) { UserName = username; Password = password; GroupName = groupname; WebServer = webServer; HttpWebClient httpWebClient = new HttpWebClient(); WebServerTestBase.LoginAsRoot(httpWebClient, webServer); HttpResponseHandler webResponse; webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/UserDB?Method=CreateUser", new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("displayName", username), new KeyValuePair<string, string>("password", password), new KeyValuePair<string, string>("assignSession", false.ToString())); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/UserDB?Method=CreateGroup", new KeyValuePair<string, string>("groupname", groupname), new KeyValuePair<string, string>("username", "root")); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(groupname + " created", webResponse.AsString(), "Unexpected response"); webResponse = httpWebClient.Get("http://localhost:" + WebServer.Port + "/Users/UserDB", new KeyValuePair<string, string>("Method", "AddUserToGroup"), new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("groupname", groupname)); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(username + " added to " + groupname, webResponse.AsString(), "Unexpected response"); }
public static IMusic[] SearchMusic(MusicSource type, string content) { try { if (type == MusicSource.Netease) { string url = "http://blog.ylz1.cn/page/music/api.php"; byte[] commit = Encoding.UTF8.GetBytes($"types=search&count=10&source=netease&pages=1&name={content}"); byte[] data = HttpWebClient.Post(url, commit); NeteaseMusic[] infos = JsonConvert.DeserializeObject <NeteaseMusic[]>(Encoding.UTF8.GetString(data)); return(infos); } else if (type == MusicSource.Kugou) { string url = "http://blog.ylz1.cn/page/music/api.php"; byte[] commit = Encoding.UTF8.GetBytes($"types=search&count=10&source=kugou&pages=1&name={content}"); byte[] data = HttpWebClient.Post(url, commit); KugouMusic[] infos = JsonConvert.DeserializeObject <KugouMusic[]>(Encoding.UTF8.GetString(data)); return(infos); } else { string url = $"https://api.qq.jsososo.com/search?key={content}&pageNo=1&pageSize=10"; byte[] data = HttpWebClient.Get(url); TencentMusic[] infos = JsonConvert.DeserializeObject <TencentMusic[]>(JObject.Parse(Encoding.UTF8.GetString(data))?["data"]?["list"].ToString()); return(infos); } } catch (Exception) { return(new IMusic[0]); } }
public static List <int> TagSearch(string tagName) { string url = "https://yande.re/post?tags=" + tagName.Replace(" ", "_"); using (HttpWebClient http = new HttpWebClient() { TimeOut = 10000, Encoding = Encoding.UTF8, Proxy = MainSave.Proxy, AllowAutoRedirect = true, }) { //http.Proxy = new System.Net.WebProxy { Address = new Uri("http://127.0.0.1:1080") }; string rawHtml = http.DownloadString(url); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(rawHtml); var picNode = doc.DocumentNode.SelectSingleNode(Xpath_List); List <int> picID = new List <int>(); if (picNode != null && picNode.ChildNodes[1].Name == "ul") { foreach (var item in picNode.ChildNodes[1].ChildNodes) { if (item.Name == "li") { picID.Add(Convert.ToInt32(item.Attributes["id"].Value.Replace("p", ""))); } } } else { picID.Add(0); } return(picID); } }
public void ReturnsWithoutResources() { HttpWebClient client = Host.CreateWebClient(); string result = client.GetPage("WithoutResources.aspx"); Assert.AreEqual("OK", result); }
/// <summary> /// Constructor to initialize the proxy /// </summary> internal SessionEventArgs(int bufferSize, ProxyEndPoint endPoint, Func <SessionEventArgs, Task> httpResponseHandler) { this.bufferSize = bufferSize; this.httpResponseHandler = httpResponseHandler; ProxyClient = new ProxyClient(); WebSession = new HttpWebClient(bufferSize); LocalEndPoint = endPoint; WebSession.ProcessId = new Lazy <int>(() => { if (RunTime.IsWindows) { var remoteEndPoint = (IPEndPoint)ProxyClient.TcpClient.Client.RemoteEndPoint; //If client is localhost get the process id if (NetworkHelper.IsLocalIpAddress(remoteEndPoint.Address)) { return(NetworkHelper.GetProcessIdFromPort(remoteEndPoint.Port, endPoint.IpV6Enabled)); } //can't access process Id of remote request from remote machine return(-1); } throw new PlatformNotSupportedException(); }); }
public FriendList Get_Friend_List() { try { using (HttpWebClient httpWebClient = new HttpWebClient()) { string address = "https://qun.qq.com/cgi-bin/qun_mgr/get_friend_list"; string s = $"bkn={Bkn}"; httpWebClient.Headers["Accept"] = "application/json, text/javascript, */*; q=0.01"; httpWebClient.Headers["Referer"] = "http://qun.qq.com/member.html"; httpWebClient.Headers["X-Requested-With"] = "XMLHttpRequest"; httpWebClient.Headers["User-Agent"] = UA; httpWebClient.Headers.Add("Cache-Control: no-cache"); httpWebClient.Cookies = QunCookies; string text = Encoding.UTF8.GetString(httpWebClient.UploadData(address, "POST", Encoding.UTF8.GetBytes(s))); Regex r = new Regex("\"[0-9]+\":"); if (r.IsMatch(text)) { foreach (var match in r.Matches(text)) { var str = ((Capture)match).Value; text = text.Replace(str, ""); } text = text.Replace("\"result\":{{", "\"result\":[{").Replace("\"}}}", "\"}]}"); } MessageLog("获取好友列表成功:" + text); return(JsonConvert.DeserializeObject <FriendList>(text)); } } catch (Exception ex) { MessageLog("获取好友列表失败:" + ex.Message); } return(null); }
/// <summary> /// Deletes and attendee by session id and email /// </summary> /// <param name="sessionId"></param> /// <param name="email"></param> /// <returns></returns> public bool DeleteByEmail(string sessionId, string email, out ApiErrorResponse error) { if (String.IsNullOrEmpty(sessionId)) { throw new ArgumentNullException(nameof(sessionId)); } if (String.IsNullOrEmpty(email)) { throw new ArgumentNullException(nameof(email)); } var request = HttpWebClient.CreateWebRequest("DELETE", BuildRoute($"session/{sessionId}/attendee/{email}")); var response = HttpWebClient.SendWebRequest(request); error = null; bool success = false; if (response != null) { success = response.StatusCode == HttpStatusCode.NoContent; if (!success) { error = response.ToErrorResponse(); } } return(success); }
public bool GetQunCookies() { try { using (HttpWebClient httpWebClient = new HttpWebClient()) { string address = string.Format("https://ssl.ptlogin2.qq.com/jump?pt_clientver=5509&pt_src=1&keyindex=9&clientuin={0}&clientkey={1}&u1=http%3A%2F%2Fqun.qq.com%2Fmember.html%23gid%3D168209441", QQ, Util.ToHex(TXProtocol.BufServiceTicketHttp /*QunKey*/, "", "{0}"), Util.GetTimeMillis(DateTime.Now)); httpWebClient.Headers["User-Agent"] = UA; var result = Encoding.UTF8.GetString(httpWebClient.DownloadData(address)); QunCookies = httpWebClient.Cookies; CookieCollection cookies = QunCookies.GetCookies(new Uri("http://qun.qq.com")); if (cookies["skey"] != null && !string.IsNullOrWhiteSpace(cookies["skey"].Value)) { QQSkey = cookies["skey"].Value; Bkn = Util.GetBkn(cookies["skey"].Value); } string value2 = cookies["p_skey"].Value; if (!string.IsNullOrWhiteSpace(value2)) { QunPSkey = cookies["p_skey"].Value; QunGtk = Util.GET_GTK(value2); } return(true); } } catch (Exception ex) { MessageLog("获取skey失败:" + ex.Message); } return(false); }
/// <summary> /// Gets a user by username /// </summary> /// <param name="username"></param> /// <returns></returns> public UserView GetUserByUsername(string username, out ApiErrorResponse error) { if (String.IsNullOrEmpty(username)) { throw new ArgumentNullException(nameof(username)); } var request = HttpWebClient.CreateWebRequest("GET", BuildRoute($"user/{username}")); var response = HttpWebClient.SendWebRequest(request); UserView userView = null; error = null; if (response != null) { string result = HttpWebClient.GetResponseBody(response); if (response.StatusCode == HttpStatusCode.OK) { userView = result.ToObject <UserView>(); } else { error = response.ToErrorResponse(); } } return(userView); }
public bool GetCookies() { try { using (HttpWebClient httpWebClient = new HttpWebClient()) { //string address = string.Format("http://ptlogin2.qq.com/jump?ptlang=2052&clientuin={0}&clientkey={1}&u1=http%3A%2F%2Fqzone.qq.com&ADUIN={0}&ADSESSION={2}&ADTAG=CLIENT.QQ.5365_.0&ADPUBNO=26405", // QQ, Util.ToHex(TXProtocol.ClientKey, "", "{0}"), Util.GetTimeMillis(DateTime.Now)); string address = $"https://ssl.ptlogin2.qq.com/jump?pt_clientver=5593&pt_src=1&keyindex=9&ptlang=2052&clientuin={QQ}&clientkey={Util.ToHex(TXProtocol.BufServiceTicketHttp, "", "{0}")}&u1=https:%2F%2Fuser.qzone.qq.com%2F417085811%3FADUIN=417085811%26ADSESSION={Util.GetTimeMillis(DateTime.Now)}%26ADTAG=CLIENT.QQ.5593_MyTip.0%26ADPUBNO=26841&source=namecardhoverstar"; httpWebClient.Headers["User-Agent"] = UA; string text = Encoding.UTF8.GetString(httpWebClient.DownloadData(address)); QQCookies = httpWebClient.Cookies; CookieCollection cookies = QQCookies.GetCookies(new Uri("http://qq.com")); if (cookies["skey"] != null) { string value = cookies["skey"].Value; if (!string.IsNullOrWhiteSpace(value)) { QQSkey = value; Bkn = Util.GetBkn(value); QQGtk = Util.GET_GTK(value); return(true); } } } } catch (Exception ex) { MessageLog("获取skey失败:" + ex.Message); } return(false); }
/// <summary> /// Deletes a user by user id /// </summary> /// <param name="userId"></param> /// <returns></returns> public bool DeleteByUserId(string userId, out ApiErrorResponse error) { if (String.IsNullOrEmpty(userId)) { throw new ArgumentNullException(nameof(userId)); } var request = HttpWebClient.CreateWebRequest("DELETE", BuildRoute($"user/{userId}")); var response = HttpWebClient.SendWebRequest(request); error = null; bool success = false; if (response != null) { success = response.StatusCode == HttpStatusCode.NoContent; if (!success) { error = response.ToErrorResponse(); } } return(success); }
/// <summary> /// Http请求头部处理 /// </summary> /// <param name="httpRequest"></param> protected override void RequestHeaderExecuting(HttpWebClient httpRequest) { if (!string.IsNullOrEmpty(this.Token.AccessToken)) { httpRequest.Headers["Authorization"] = string.Format("OAuth2 {0}", this.Token.AccessToken); } }
/// <summary> /// Search for attendees in a specefic session /// </summary> /// <param name="sessionId"></param> /// <param name="attendanceCode"></param> /// <returns></returns> public List <AttendeeView> SearchAttendees(string sessionId, AttendeeFilter filter, out ApiErrorResponse error) { if (String.IsNullOrEmpty(sessionId)) { throw new ArgumentNullException(nameof(sessionId)); } var filterQuery = filter.ToQueryString(); var request = HttpWebClient.CreateWebRequest("GET", BuildRoute($"session/{sessionId}/attendees?{filterQuery}")); var response = HttpWebClient.SendWebRequest(request); List <AttendeeView> attendeeViews = null; error = null; if (response != null) { string result = HttpWebClient.GetResponseBody(response); if (response.StatusCode == HttpStatusCode.OK) { attendeeViews = result.ToObject <List <AttendeeView> >(); } else { error = response.ToErrorResponse(); } } return(attendeeViews); }
protected SessionEventArgsBase(ProxyServer server, ProxyEndPoint endPoint, CancellationTokenSource cancellationTokenSource, Request request) : this(server, endPoint, cancellationTokenSource) { CancellationTokenSource = cancellationTokenSource; ProxyClient = new ProxyClient(); WebSession = new HttpWebClient(request); LocalEndPoint = endPoint; WebSession.ProcessId = new Lazy <int>(() => { if (RunTime.IsWindows) { var remoteEndPoint = ClientEndPoint; // If client is localhost get the process id if (NetworkHelper.IsLocalIpAddress(remoteEndPoint.Address)) { var ipVersion = endPoint.IpV6Enabled ? IpVersion.Ipv6 : IpVersion.Ipv4; return(TcpHelper.GetProcessIdByLocalPort(ipVersion, remoteEndPoint.Port)); } // can't access process Id of remote request from remote machine return(-1); } throw new PlatformNotSupportedException(); }); }
//"this code is executed entirely within the web application domain" private static void EndConversationTestInHostImpl() { IAspFixtureHost host = AspTestContext.Host; Assert.IsNotNull(host); HttpWebClient clnt = host.CreateClientWithDefaultPort(); //Start EndConversationTestBegin string content = clnt.GetPage("/EndConversationTestBegin.aspx").Trim(); Assert.AreEqual("OK", content, "Start EndConversationTestBegin : Request Error!! " + content); String uniqIdOrig = (String)AspTestContext.HttpContext.Session["ConversationEvidenceBsn_UniqId"]; content = clnt.GetPage("/EndConversationTestBegin.aspx").Trim(); Assert.AreEqual("OK", content, "Start EndConversationTestBegin : Request Error!! " + content); Assert.AreEqual( uniqIdOrig, AspTestContext.HttpContext.Session["ConversationEvidenceBsn_UniqId"] ); //End EndConversationTestEnd content = clnt.GetPage("/EndConversationTestEnd.aspx").Trim(); Assert.AreEqual("OK", content, "EndConversationTestEnd: Request Error!! " + content); //ReStart EndConversationTestBegin content = clnt.GetPage("/EndConversationTestBegin.aspx").Trim(); Assert.AreEqual("OK", content, "ReStart EndConversationTestBegin: Request Error!! " + content); Assert.AreNotEqual( uniqIdOrig, AspTestContext.HttpContext.Session["ConversationEvidenceBsn_UniqId"] ); }
public void UsesReadonlySession() { HttpWebClient client = Host.CreateWebClient(); string result = client.GetPage("ReadOnlySession.aspx"); Assert.AreEqual("OK", result); }
private static void PatialEndConvTestInHostImpl() { IAspFixtureHost host = AspTestContext.Host; Assert.IsNotNull(host); HttpWebClient clnt = host.CreateClientWithDefaultPort(); String convPatialEndConv_A_BSts = "{Id='convPatialEndConv_A_B'; " + "this.ParentConversation.Id=convPatialEndConv_A;" + " InnerConversations=[{Id='convPatialEndConv_A_B_A';" + " this.ParentConversation.Id=convPatialEndConv_A_B;" + " InnerConversations=[]}{Id='convPatialEndConv_A_B_B';" + " this.ParentConversation.Id=convPatialEndConv_A_B;" + " InnerConversations=[]}]}"; //Start PatialEndConv_A_Begin string content = clnt.GetPage("/PatialEndConv_A_Begin.aspx").Trim(); Assert.AreEqual("OK", content, "PatialEndConv_A_Begin.aspx : Request Error!! " + content); String conversationStr = (String)AspTestContext.HttpContext.Session["ConversationStr"]; Assert.IsTrue(conversationStr.Contains(convPatialEndConv_A_BSts), String.Format("convPatialEndConv_A_BSts was NOT found in '{0}'", conversationStr)); //remove PatialEndConv_A_B_End content = clnt.GetPage("/PatialEndConv_A_B_End.aspx").Trim(); Assert.AreEqual("OK", content, "PatialEndConv_A_B_End.aspx : Request Error!! " + content); //Start PatialEndConv_A_Begin with 'convPatialEndConv_A_B' ended. content = clnt.GetPage("/PatialEndConv_A_Begin.aspx").Trim(); Assert.AreEqual("OK", content, "PatialEndConv_A_Begin.aspx : Request Error!! " + content); conversationStr = (String)AspTestContext.HttpContext.Session["ConversationStr"]; Assert.IsFalse(conversationStr.Contains(convPatialEndConv_A_BSts), String.Format("convPatialEndConv_A_BSts was FOUND in '{0}'", conversationStr)); }
private static void SerializeConversationTestInHostImpl() { // use static method to avoid passing a reference to ourselves to the host domain IAspFixtureHost host = AspTestContext.Host; Assert.IsNotNull(host); HttpWebClient clnt = host.CreateClientWithDefaultPort(); //first time (before serialization) string content = clnt.GetPage("/SerializeConversationTest.aspx").Trim(); Assert.IsNotNull(AspTestContext.HttpContext, content); Assert.IsNotNull(AspTestContext.HttpContext.Session, content); Assert.AreEqual("OK", content, content); DateTime beginDt = DateTime.Now; //second time (after derialization) content = clnt.GetPage("/SerializeConversationTest.aspx").Trim(); Assert.IsNotNull(AspTestContext.HttpContext, content); Assert.IsNotNull(AspTestContext.HttpContext.Session, content); Assert.AreEqual("OK", content, content); log.Error(DateTime.Now.Subtract(beginDt)); }
public async Task <SubReddit> GetSubRedditAsync(string subRedditName, int amountOfPosts) { try { if (rateLimiter.IsRatelimited()) { return(null); } var uri = new Uri("https://www.reddit.com/" + subRedditName + "/.json?limit=" + amountOfPosts); var response = await HttpWebClient.ReturnStringAsync(uri); if (!string.IsNullOrEmpty(response) || !string.IsNullOrWhiteSpace(response)) { return(JsonConvert.DeserializeObject <SubReddit>(response)); } else { throw new Exception("Empty response from " + uri); } } catch { return(null); } }
public static IntPtr CQ_getImage(int authCode, IntPtr file) { string filename = file.ToString(GB18030); string path = $"data\\image\\{filename}.cqimg"; if (File.Exists(path)) { IniConfig ini = new IniConfig(path); ini.Load(); if (ini.Object.ContainsKey("image") is false) { return(Marshal.StringToHGlobalAnsi(string.Empty)); } string picurl = ini.Object["image"]["url"]; HttpWebClient http = new HttpWebClient { TimeOut = 10000 }; http.DownloadFile(picurl, $"data\\image\\{filename}.jpg"); FileInfo fileInfo = new FileInfo($"data\\image\\{filename}.jpg"); return(Marshal.StringToHGlobalAnsi(fileInfo.FullName)); } else { return(Marshal.StringToHGlobalAnsi(string.Empty)); } }
public void TestEnforcementOfActionPermissions() { HttpWebClient httpWebClient = new HttpWebClient(); HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/Users/root"); Assert.AreEqual(HttpStatusCode.Unauthorized, webResponse.StatusCode, "Bad status code"); }
public void TestCanGetOpenIdLandingPage() { HttpWebClient httpWebClient = new HttpWebClient(); HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/Shell/OpenID/OpenIDLandingPage.wchtml?openid.mode=checkid_setup&openid.trust_root=&openid.identity=http%3a%2f%2flocalhost%3a1080%2fUsers%2froot.user&openid.return_to=http%3a%2f%2flocalhost%3a1080%2fUsers%2fUserDB%3fMethod%3dCompleteOpenIdLogin%26esoid.claimed_id%3dhttp%253a%252f%252flocalhost%253a1080%252fUsers%252froot.user"); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); }
public void TestBypassOfActionPermissions() { HttpWebClient httpWebClient = new HttpWebClient(); HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/Users/root?BypassActionPermission=true"); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); }
public void TestIgnoreUnknownActionPermissions() { HttpWebClient httpWebClient = new HttpWebClient(); HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/Users/root?Action=Abc"); Assert.AreEqual(HttpStatusCode.InternalServerError, webResponse.StatusCode, "Bad status code"); Assert.AreEqual("ObjectCloud does not support the action \"Abc\" for files of type \"directory\"", webResponse.AsString(), "Unexpected response"); }
public void TestGarbageCollection() { try { IWebConnection webConnection = null; WebServer.Stop(); WebServer.StartServer(); EventHandler<IWebServer, EventArgs<IWebConnection>> webConnectionStarted = delegate(IWebServer webServer, EventArgs<IWebConnection> e) { webConnection = e.Value; }; try { WebServer.WebConnectionStarting += webConnectionStarted; HttpWebClient httpWebClient = new HttpWebClient(); HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/"); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.IsNotNull(webResponse.AsString(), "Nothing returned"); Assert.IsNotNull(webConnection, "IWebConnection not set by delegate"); } finally { WebServer.WebConnectionStarting -= webConnectionStarted; } WebServer.Stop(); // Wait for the conneciton to close while (webConnection.Connected) Thread.Sleep(25); WeakReference weakReference = new WeakReference(webConnection); webConnection = null; DateTime stopTime = DateTime.Now.AddSeconds(5); while (weakReference.IsAlive) { Thread.Sleep(25); GC.Collect(); Assert.IsTrue(DateTime.Now < stopTime, "Took too long to garbage collect the IWebConnection"); } } finally { WebServer.StartServer(); } }
public static void LoginAsRoot(HttpWebClient httpWebClient, IWebServer webServer) { // Log in as root HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + webServer.Port + "/Users/UserDB?Method=Login", new KeyValuePair<string, string>("username", "root"), new KeyValuePair<string, string>("password", "root")); Assert.AreEqual(HttpStatusCode.Accepted, webResponse.StatusCode, "Bad status code"); Assert.AreEqual("root logged in", webResponse.AsString(), "Unexpected response"); }
public void SetFilePermission(HttpWebClient httpWebClient, string directory, string filename, string username, FilePermissionEnum filePermission) { HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + directory + "?Method=SetFilePermission", new KeyValuePair<string, string>("FileName", filename), new KeyValuePair<string, string>("UserOrGroup", username), new KeyValuePair<string, string>("FilePermission", filePermission.ToString())); Assert.AreEqual(HttpStatusCode.Accepted, webResponse.StatusCode, "Bad status code"); Assert.AreEqual("Permission set to " + filePermission.ToString(), webResponse.AsString(), "Unexpected response"); }
static bool SendAlarmMessage(HttpWebClient cli, Arguments a) { "Perform Alarm(Code={0}, Title={1}, Text={2})".LogVerbose (a.Code, a.Title, a.Text); var authToken = ConfigurationContainer.Instance.GetAuthToken (); //ServicePointManager.UseNagleAlgorithm = false; //Http.Get (a.Code, a.Title, a.Text); var result = cli.PerformAlarm (authToken, a.Code, a.Title, a.Text); return result.Successful; }
public void TestCreateEmbeddedDatabase() { string newfileName = "TestCreateEmbeddedDatabase" + SRandom.Next().ToString() + ".db"; HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "database"); HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=PostQuery", new KeyValuePair<string, string>("query", "create table testtable (testcol int)")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); int[] resultInts = webResponse.AsJsonReader().Deserialize<int[]>(); Assert.IsNotNull(resultInts, "Result deserialized as null"); Assert.AreEqual(0, resultInts[0], "Incorrect result"); webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=PostQuery", new KeyValuePair<string, string>("query", "insert into testtable (testcol) values (123);insert into testtable (testcol) values (456)")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); resultInts = webResponse.AsJsonReader().Deserialize<int[]>(); Assert.AreEqual(2, resultInts[0], "Incorrect result"); webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=PostQuery", new KeyValuePair<string, string>("query", "select * from testtable; select * from testtable")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Dictionary<string, object>[][] resultObjss = webResponse.AsJsonReader().Deserialize<Dictionary<string, object>[][]>(); Assert.AreEqual(2, resultObjss.Length, "Wrong number of queries returned"); foreach (Dictionary<string, object>[] resultObjs in resultObjss) { List<int> expected = new List<int>(new int[] {123,456}); foreach(Dictionary<string, object> resultObj in resultObjs) { int value = Convert.ToInt32(resultObj["testcol"]); Assert.IsTrue(expected.Contains(value), "Unexpected value: " + value); expected.Remove(value); } Assert.IsTrue(0 == expected.Count, "Expected values not returned: " + StringGenerator.GenerateCommaSeperatedList(expected)); } }
public void TestErrorInShellSetting() { string newfileName = "TestUseText" + SRandom.Next().ToString() + ".badDNE"; HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "text"); HttpResponseHandler webResponse = httpWebClient.Get("http://localhost:" + WebServer.Port + "/" + newfileName); Assert.AreEqual(HttpStatusCode.InternalServerError, webResponse.StatusCode, "Bad status code"); Assert.AreEqual("ObjectCloud is not configured to handle files of type badDNE", webResponse.AsString(), "Unexpected value"); }
public void TestCanCreateGroup() { HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); HttpResponseHandler webResponse; string groupname = "testgroup" + SRandom.Next(100000).ToString(); webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/UserDB?Method=CreateGroup", new KeyValuePair<string, string>("groupname", groupname)); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(groupname + " created", webResponse.AsString(), "Unexpected response"); }
public MainForm() { this.Font = SystemFonts.MessageBoxFont; this.Width = 550; this.Height = 500; this.Text = "AlarmPushTool Log-Ausgaben"; main.Dock = DockStyle.Fill; this.Controls.Add (main); logEntries.Dock = DockStyle.Fill; logEntries.Multiline = true; logEntries.ScrollBars = ScrollBars.Vertical; this.cli = new HttpWebClient (ConfigurationContainer.Instance.Url); }
public void TestAddUserToGroup() { HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); HttpResponseHandler webResponse; string groupname = "testgroup" + SRandom.Next(100000).ToString(); webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/UserDB?Method=CreateGroup", new KeyValuePair<string, string>("groupname", groupname), new KeyValuePair<string, string>("username", "root")); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(groupname + " created", webResponse.AsString(), "Unexpected response"); string username = "******" + SRandom.Next(100000).ToString(); webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/UserDB?Method=CreateUser", new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("displayName", username), new KeyValuePair<string, string>("password", "password"), new KeyValuePair<string, string>("assignSession", false.ToString())); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(username + " created", webResponse.AsString(), "Unexpected response"); webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/UserDB?Method=AddUserToGroup", new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("groupname", groupname)); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(username + " added to " + groupname, webResponse.AsString(), "Unexpected response"); webResponse = httpWebClient.Get("http://localhost:" + WebServer.Port + "/Users/UserDB", new KeyValuePair<string, string>("Method", "GetUsersGroups"), new KeyValuePair<string, string>("username", username)); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); JsonReader jsonReader = webResponse.AsJsonReader(); object[] result = jsonReader.Deserialize<object[]>(); Assert.AreEqual(1, result.Length, "Wrong number of groups"); Assert.IsInstanceOf<Dictionary<string, object>>(result[0], "Wrong type decoded"); Dictionary<string, object> group = (Dictionary<string, object>)result[0]; Assert.AreEqual(groupname, group["Name"], "Wrong name returned"); }
public void TestLargeBinaryFile() { string newfileName = "TestLargeBinaryFile" + SRandom.Next().ToString(); HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "binary"); byte[] toWrite = SRandom.NextBytes(1024 * 1024 * 3); for (int requestCtr = 0; requestCtr < 3; requestCtr++) { HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=WriteAll"); webRequest.KeepAlive = true; webRequest.UnsafeAuthenticatedConnectionSharing = true; webRequest.Method = "POST"; webRequest.ContentType = "application/binary"; webRequest.CookieContainer = httpWebClient.CookieContainer; webRequest.ContentLength = toWrite.Length; // Write the request webRequest.GetRequestStream().Write(toWrite, 0, toWrite.Length); using (HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse()) { Assert.AreEqual(HttpStatusCode.Accepted, httpWebResponse.StatusCode, "Bad status code"); } byte[] written = FileHandlerFactoryLocator.FileSystemResolver.ResolveFile("/" + newfileName).CastFileHandler<IBinaryHandler>().ReadAll(); Assert.IsTrue(Enumerable.Equals(toWrite, written), "Data written incorrectly"); HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/" + newfileName, new KeyValuePair<string, string>("Method", "ReadAll")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.IsTrue(Enumerable.Equals(toWrite, webResponse.AsBytes()), "Unexpected value"); } }
public OpenIDLogonerThroughObjectCloud(string name, string password, IWebServer secondWebServer) { Name = name; Password = password; SecondWebServer = secondWebServer; HttpWebClient httpWebClient = new HttpWebClient(); WebServerTestBase.LoginAsRoot(httpWebClient, SecondWebServer); HttpResponseHandler webResponse; webResponse = httpWebClient.Post("http://localhost:" + SecondWebServer.Port + "/Users/UserDB?Method=CreateUser", new KeyValuePair<string, string>("username", name), new KeyValuePair<string, string>("displayName", name), new KeyValuePair<string, string>("password", password)); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); webResponse = httpWebClient.Get("http://localhost:" + SecondWebServer.Port + "/Users/" + name + ".user"); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Thread.Sleep(2000); }
static void Main(string[] args) { HttpWebResponseResult httpWebResponseResult = null; HttpWebClient httpWebClient = new HttpWebClient(); httpWebClient.Headers.Add("Referer", "http://localhost"); httpWebClient.IsTraceEnabled = true; //Example No.1 multipart/form-data POST reqeust String url = "http://localhost:53090/upload/uploadfile"; byte[] byteFiles = null; using (FileStream fs = new FileStream(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "01.jpg"), FileMode.Open, FileAccess.Read)) { byteFiles = new byte[fs.Length]; fs.Read(byteFiles, 0, byteFiles.Length); } httpWebClient.SetField("StorageFile.Title", "title01", true); httpWebClient.SetField("StorageFile.Summary", "summary01", true); httpWebClient.SetField("filedata", byteFiles, "001.jpg", String.Empty); httpWebResponseResult = httpWebClient.Post(url); TraceInfo(httpWebResponseResult); //Example No.2 application/x-www-form-urlencoded POST reqeust url = "http://localhost:53090/passport/logon"; httpWebClient.SetField("LogonInfo.ValidateCode", "gvzwb"); httpWebClient.SetField("LogonInfo.User.Username", "sanxia123"); httpWebClient.SetField("LogonInfo.User.Password", "Yc123703"); httpWebClient.SetField("LogonInfo.IsPersistentCookie", "false"); httpWebResponseResult = httpWebClient.Post(url); TraceInfo(httpWebResponseResult); //Example No.3 GET reqeust url = "http://localhost:53090/content/oauth.html"; httpWebClient.SetField("a", "1"); httpWebResponseResult = httpWebClient.Get(url); TraceInfo(httpWebResponseResult); System.Console.ReadKey(true); }
private static void DoCallHome(object state) { HttpWebClient client = new HttpWebClient(); log.Info("Calling home to " + FileHandlerFactoryLocator.CallHomeEndpoint); client.BeginPost( FileHandlerFactoryLocator.CallHomeEndpoint, delegate(HttpResponseHandler response) { log.Info("Successfully called home to " + FileHandlerFactoryLocator.CallHomeEndpoint); }, delegate(Exception e) { log.Error("Exception when calling home to " + FileHandlerFactoryLocator.CallHomeEndpoint, e); // no-op for strict compiler if (null == Timer) {} }, new KeyValuePair<string, string>("host", FileHandlerFactoryLocator.Hostname)); }
public OpenIDLogonerThroughObjectCloud(string name, string password, IWebServer webServer, IWebServer secondWebServer) : this(name, password, secondWebServer) { HttpWebClient httpWebClient = new HttpWebClient(); WebServerTestBase.LoginAsRoot(httpWebClient, webServer); HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + webServer.Port + "/?Method=CreateFile", new KeyValuePair<string, string>("FileName", name), new KeyValuePair<string, string>("FileType", "directory")); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); webResponse = httpWebClient.Post( "http://localhost:" + webServer.Port + "/?Method=SetFilePermission", new KeyValuePair<string, string>("FileName", name), new KeyValuePair<string, string>("UserOrGroup", Name), new KeyValuePair<string, string>("FilePermission", FilePermissionEnum.Administer.ToString())); Assert.AreEqual(HttpStatusCode.Accepted, webResponse.StatusCode, "Bad status code"); _WritableDirectory = "/" + _Name + "/"; }
public void TestNoIndexFile() { string newfileName = "TestNoIndexFile" + SRandom.Next().ToString(); HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "directory"); HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=SetIndexFile"); Assert.AreEqual(HttpStatusCode.Accepted, webResponse.StatusCode, "Bad status code"); Assert.AreEqual("Index file disabled", webResponse.AsString(), "Unexpected response"); webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/" + newfileName, new KeyValuePair<string, string>("Method", "GetIndexFile")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual("No index file", webResponse.AsString(), "Unexpected response"); }
public void TestMimeType(string mimeType, string extension) { string newfileName = "TestMimeType" + SRandom.Next().ToString() + "." + extension; HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "text"); HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=WriteAll"); webRequest.CookieContainer = httpWebClient.CookieContainer; webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; string text = "nurw348nuo48h78t40oghw9phq 98fh587ghr7soiyo578whvntronvaeihrfbow45gn98owvs78zrgh78whgnv8ono8q7iehgrb8h78qofhfb78wehgnow8"; byte[] toWrite = Encoding.UTF8.GetBytes(text); webRequest.ContentLength = toWrite.Length; // Write the request webRequest.GetRequestStream().Write(toWrite, 0, toWrite.Length); using (HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse()) { Assert.AreEqual(HttpStatusCode.Accepted, httpWebResponse.StatusCode, "Bad status code"); } HttpResponseHandler webResponse = httpWebClient.Get("http://localhost:" + WebServer.Port + "/" + newfileName); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(text, webResponse.AsString(), "Unexpected value"); Assert.AreEqual(mimeType, webResponse.ContentType, "Unexpected content type"); }
public void TestCreateFileConcurrent() { string newfileName = "CreateFile_TestCreateFileConcurrent" + SRandom.Next().ToString(); Shared<uint> numSuccess = new Shared<uint>(0); Shared<uint> numConflict = new Shared<uint>(0); List<Thread> threads = new List<Thread>(); Exception threadException = null; DateTime startTime = DateTime.Now.AddMilliseconds(100); for (int ctr = 0; ctr < 10; ctr++) threads.Add(new Thread(delegate() { while (DateTime.Now < startTime) { } // spin until it's time to start try { HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + "/?Method=CreateFile", new KeyValuePair<string, string>("FileName", newfileName), new KeyValuePair<string, string>("FileType", "text")); switch (webResponse.StatusCode) { case HttpStatusCode.Created: lock (numSuccess) numSuccess.Value++; break; case HttpStatusCode.Conflict: lock (numConflict) numConflict.Value++; break; default: Assert.Fail("Unexpected status when creating duplicate files"); break; } } catch (Exception e) { threadException = e; } })); foreach (Thread thread in threads) thread.Start(); foreach (Thread thread in threads) thread.Join(); if (null != threadException) throw threadException; Assert.AreEqual(1, numSuccess.Value, "Wrong number of successfully created files"); Assert.AreEqual(threads.Count - 1, numConflict.Value, "Wrong number of conflicts"); }
public void CreateFile(IWebServer webServer, HttpWebClient httpWebClient, string directory, string filename, string typeid, HttpStatusCode expectedStatusCode) { HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + webServer.Port + directory + "?Method=CreateFile", new KeyValuePair<string, string>("FileName", filename), new KeyValuePair<string, string>("FileType", typeid)); Assert.AreEqual(expectedStatusCode, webResponse.StatusCode, "Bad status code"); // Read the response so the server isn't left trying to transmit webResponse.AsBytes(); }
public void Send() { HttpWebClient loHttp = new HttpWebClient(); string result; loHttp.HandleCookies = true; StringBuilder sb = new StringBuilder(); sb.Append("{actionForm.statusCadastro}=S&"); sb.Append("{actionForm.foneArea}=21&"); sb.Append("{actionForm.foneNumero}=98564467&"); sb.Append("{actionForm.senha}=3734&"); // // PASSO 1 // string loginPage = "https://servicos.vivo.com.br/VOLWeb/LoginAction.do"; result = loHttp.GetUrl(loginPage +"?"+ sb.ToString()); // // PASSO 2 // string cookiePage = "https://servicos.vivo.com.br/VOLWeb/servicos/torpedoEmpresas.do?idMenu=494&idSubMenu=1967"; result = loHttp.GetUrl(cookiePage); // // PASSO 3 // int beginScriptTag = result.IndexOf("https://"); int endScriptTag = result.IndexOf("');"); string nextPage = result.Substring(beginScriptTag, endScriptTag - beginScriptTag); result = loHttp.GetUrl(nextPage); // // PASSO 4 // string crossPage = "https://online.vivo-rjes.com.br/torpedoempresa/RecuperaDadosEnvio?action=RecuperaDadosEnvio"; result = loHttp.GetUrl(crossPage); // // PASSO 5 // loHttp.PostMode = PostMode.MultiPart; loHttp.AddPostKey("Titulo","Empresa"); loHttp.AddPostKey("TipoEnvio","0"); loHttp.AddPostKey("Periodicidade","4"); loHttp.AddPostKey("ListaEnvio","0"); loHttp.AddPostKey("Operadora","11"); loHttp.AddPostKey("MinutoAtual", DateTime.Now.Minute.ToString() ); loHttp.AddPostKey("HoraAtual", DateTime.Now.Hour.ToString()); loHttp.AddPostKey("AnoAtual", DateTime.Now.Year.ToString()); loHttp.AddPostKey("MesAtual", DateTime.Now.Month.ToString()); loHttp.AddPostKey("DiaAtual", DateTime.Now.Day.ToString()); loHttp.AddPostKey("NumDiasValidadeAgendamento","30"); loHttp.AddPostKey("NumDestinatario","0"); loHttp.AddPostKey("TelefoneCompleto","2181243318"); loHttp.AddPostKey("action","EnviaShortMessageAnexadaUmaMensagem"); loHttp.AddPostKey("DestinatariosMensagem","com.tcbnet.webapp.torpedotelefonicanet.envio.LeafScheduleRecipient,2181243318;"); loHttp.AddPostKey("Mensagem","Teste de Envio " + DateTime.Now.ToString() ); string sendSmsPage = "https://online.vivo-rjes.com.br/torpedoempresa/EnvioAnexado"; result = loHttp.PostUrl(sendSmsPage); }
public void TestNewUser() { HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); HttpResponseHandler webResponse; string username = "******" + SRandom.Next(100000).ToString(); webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/UserDB?Method=CreateUser", new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("displayName", username), new KeyValuePair<string, string>("password", "password"), new KeyValuePair<string, string>("assignSession", true.ToString())); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(username + " created", webResponse.AsString(), "Unexpected response"); // Verify that the current user is the newly-created user webResponse = httpWebClient.Get("http://localhost:" + WebServer.Port + "/Users/[name].user", new KeyValuePair<string, string>("Method", "GetName")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(username, webResponse.AsString(), "Unexpected response"); }
/// <summary> /// Helper for Ioe.*Tests /// </summary> /// <param name="host"></param> /// <param name="clnt"></param> /// <param name="test"></param> private static void IoeTestsHelper(IAspFixtureHost host, HttpWebClient clnt, String test) { //Test for Raise Invalid OperationException with ""Conversation already has another manager". string content = clnt.GetPage("/IoeTests.aspx?test=" + test).Trim(); Assert.AreEqual("OK", content, "/IoeTests.aspx?test=" + test + ": Request Error!! " + content); Assert.AreEqual("OK", (String)AspTestContext.HttpContext.Session["testResult"], (String)AspTestContext.HttpContext.Session["testResult"]); }
public void TestViewTextFile() { string newfileName = "TestUseText" + SRandom.Next().ToString() + ".txt"; HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "text"); HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=WriteAll"); webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.CookieContainer = httpWebClient.CookieContainer; string text = "huriownuifeowb,tw89hu8ofryuovrbywoivujrz,fgersykghvyauofho9fnauwielo"; byte[] toWrite = Encoding.UTF8.GetBytes(text); webRequest.ContentLength = toWrite.Length; // Write the request webRequest.GetRequestStream().Write(toWrite, 0, toWrite.Length); using (HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse()) { Assert.AreEqual(HttpStatusCode.Accepted, httpWebResponse.StatusCode, "Bad status code"); } HttpResponseHandler webResponse = httpWebClient.Get("http://localhost:" + WebServer.Port + "/" + newfileName); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(text, webResponse.AsString(), "Unexpected value"); Assert.AreEqual("text/plain", webResponse.ContentType, "Unexpected content type"); }
public void TestUseBinary() { string newfileName = "TestUseBinary" + SRandom.Next().ToString(); HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "binary"); HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=WriteAll"); webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.CookieContainer = httpWebClient.CookieContainer; byte[] binary = SRandom.NextBytes(2048); webRequest.ContentLength = binary.Length; // Write the request webRequest.GetRequestStream().Write(binary, 0, binary.Length); using (HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse()) { Assert.AreEqual(HttpStatusCode.Accepted, httpWebResponse.StatusCode, "Bad status code"); } HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/" + newfileName, new KeyValuePair<string, string>("Method", "ReadAll")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.IsTrue(Enumerable.Equals(binary, webResponse.AsBytes()), "Unexpected value"); }
public void TestSetPassword() { HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); HttpResponseHandler webResponse; string username = "******" + SRandom.Next(100000).ToString(); webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/UserDB?Method=CreateUser", new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("displayName", username), new KeyValuePair<string, string>("password", "password"), new KeyValuePair<string, string>("assignSession", true.ToString())); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(username + " created", webResponse.AsString(), "Unexpected response"); // Verify that the current user is the newly-created user webResponse = httpWebClient.Get("http://localhost:" + WebServer.Port + "/Users/[name].user", new KeyValuePair<string, string>("Method", "GetName")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(username, webResponse.AsString(), "Unexpected response"); webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/" + username + ".user?Method=SetPassword", new KeyValuePair<string, string>("OldPassword", "password"), new KeyValuePair<string, string>("NewPassword", "22password")); Assert.AreEqual(HttpStatusCode.Accepted, webResponse.StatusCode, "Wrong status code when calling SetPassword"); Assert.AreEqual("Password changed", webResponse.AsString(), "Wrong response text when changing the password"); Logout(httpWebClient); // Log in as root webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + "/Users/UserDB?Method=Login", new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("password", "22password")); Assert.AreEqual(HttpStatusCode.Accepted, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(username + " logged in", webResponse.AsString(), "Unexpected response"); }
public void TestCreateMultipleFilesConcurrent() { List<Thread> threads = new List<Thread>(); Exception threadException = null; DateTime startTime = DateTime.Now.AddMilliseconds(100); for (int ctr = 0; ctr < 10; ctr++) threads.Add(new Thread(delegate() { while (DateTime.Now < startTime) { } // spin until it's time to start try { string newfileName = "CreateFile_TestCreateMultipleFilesConcurrent" + SRandom.Next().ToString(); HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "text"); } catch (Exception e) { threadException = e; } })); foreach (Thread thread in threads) thread.Start(); foreach (Thread thread in threads) thread.Join(); if (null != threadException) throw threadException; }