public void TestMethod1() { var web = new WebClient(); var stream = web.OpenRead("http://" + Environment.GetEnvironmentVariable("APPNAME")); var result = new StreamReader(stream).ReadToEnd(); Assert.IsTrue(result.Contains("ASP.NET MVC Website") && result.Contains("Home")); }
static void TestLoggingAndDelete(string path) { ILogger log = null; try { log = new LoggerConfiguration() .WriteTo.File(path) .CreateLogger(); var message = Some.MessageTemplate(); log.Write(new LogEvent( DateTimeOffset.Now, LogEventLevel.Information, null, message, Enumerable.Empty<LogEventProperty>())); var refile = System.IO.File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); var content = new StreamReader(refile).ReadToEnd(); refile.Dispose(); Assert.That(content.Contains(message.Text)); } finally { var disposable = (IDisposable) log; if (disposable != null) disposable.Dispose(); System.IO.File.Delete(path); } }
public bool login(string username, string password) { var initialRequest = CyberghostRequest("https://account.cyberghostvpn.com/en_us/login"); var initialResponse = (HttpWebResponse)initialRequest.GetResponse(); var csrfToken = new StreamReader(initialResponse.GetResponseStream()).ReadToEnd(); csrfToken = csrfToken.Substring(csrfToken.IndexOf("var CSRF", StringComparison.Ordinal) + 12, 64); var loginRequest = CyberghostRequest("https://account.cyberghostvpn.com/en_us/proxy/users/me?flags=17&csrf=" + csrfToken); var postData = "username="******"&authentication=" + password + "&captcha="; var data = Encoding.ASCII.GetBytes(postData); loginRequest.Method = "POST"; loginRequest.ContentType = "application/x-www-form-urlencoded"; loginRequest.ContentLength = data.Length; using (var stream = loginRequest.GetRequestStream()) { stream.Write(data, 0, data.Length); } try { var loginResponse = (HttpWebResponse)loginRequest.GetResponse(); var responded = new StreamReader(loginResponse.GetResponseStream()).ReadToEnd(); return responded.Contains("user_name"); } catch (Exception) { return false; } }
/// <summary> /// 指定されたメールアドレスとパスワードでニコニコ動画にログインする.<para/> /// アプリケーションの起動時に1回だけ呼ぶ. /// </summary> /// <param name="mail">メールアドレス</param> /// <param name="passwd">パスワード</param> public static void LoginToNicovideo(string mail, string passwd) { var req = (HttpWebRequest)HttpWebRequest.Create("https://secure.nicovideo.jp/secure/login?site=niconico"); req.Method = "POST"; var args = new Dictionary<string, string> { {"mail", mail}, {"password", passwd} }; var s = args.Select(x => x.Key + "=" + x.Value).Aggregate((x, y) => x + "&" + y); var bs = Encoding.UTF8.GetBytes(s); req.ContentLength = bs.Length; req.ContentType = "application/x-www-form-urlencoded"; req.CookieContainer = LoginCookie; req.GetRequestStream().Write(bs, 0, bs.Length); string result; try { var resp = (HttpWebResponse) req.GetResponse(); result = new StreamReader(resp.GetResponseStream()).ReadToEnd(); } catch (Exception ex) { throw new Exception("Error during login proccess.", ex); } if (result.Contains("wrongPass")) { throw new Exception("Wrong ID or Password. Login Failed."); } }
static void TestLoggingAndDelete(string path) { ExecuteAndCleanUpFile( path, p => new LoggerConfiguration() .WriteTo.File(p) .CreateLogger(), log => { var message = Some.MessageTemplate(); log.Write(new LogEvent( DateTimeOffset.Now, LogEventLevel.Information, null, message, Enumerable.Empty<LogEventProperty>())); var refile = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); var content = new StreamReader(refile).ReadToEnd(); refile.Dispose(); Assert.That(content.Contains(message.Text)); }); }
public bool TryExtract(string fullPath, Stream stream, string fileName, out ExtractionResult result) { result = null; if (IsExtractable(fileName)) { var encoding = GetFileEncoding(stream); stream.Position = 0; //TODO: buscar una forma mas elegante de hacer esto var text = new StreamReader(stream, encoding).ReadToEnd(); //TODO: mejorar este parche feo y caro para soportar a la vez ansi y utf sin bom if (text.Contains("Ã")) { var bytes = encoding.GetBytes(text); text = Encoding.UTF8.GetString(bytes); } result = new ExtractionResult() { ContentType = "text/plain", PlainContent = text }; return true; } else { return false; } }
public void WriterShouldNotIncludeTypeNameForCollectionOfDerivedType() { // JSON Light: writer doesn't include type name for collection of derived type // If I have a collection property declared in metadata as Collection(Edm.Geography), // and at serialization type, it's clearly a Collection(Edm.GeographyPoint), // we won't write the type name for that property by default (i.e., minimal metadata mode). var model = new EdmModel(); var entityType = new EdmEntityType("Var1", "Type"); entityType.AddKeys(entityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32)); entityType.AddProperty(new EdmStructuralProperty(entityType, "Geographies", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.Geography, false))))); model.AddElement(entityType); var writerSettings = new ODataMessageWriterSettings(); writerSettings.SetContentType(ODataFormat.Json); writerSettings.DisableMessageStreamDisposal = true; var message = new InMemoryMessage { Stream = new MemoryStream() }; using (ODataMessageWriter odataMessageWriter = new ODataMessageWriter((IODataRequestMessage)message, writerSettings, model)) { ODataWriter odataWriter = odataMessageWriter.CreateODataEntryWriter(); odataWriter.WriteStart( new ODataEntry { TypeName = "Var1.Type", Properties = new[] { new ODataProperty() { Name = "Id", Value = 1 }, new ODataProperty() { Name = "Geographies", Value = new ODataCollectionValue { Items = new[] { GeographyPoint.Create(0,0), GeographyPoint.Create(1,1), GeographyPoint.Create(2,2) } } }, } }); odataWriter.WriteEnd(); odataWriter.Flush(); } message.Stream.Position = 0; var output = new StreamReader(message.Stream).ReadToEnd(); Assert.IsFalse(output.Contains("Collection(Edm.GeographyPoint)"), @"output.Contains(""Collection(Edm.GeographyPoint)"" == false"); }
public void TestRequest() { var request = new RestRequest(BaseUrl + "TestPage.aspx"); var response = request.Request("POST", "test=" + HttpUtility.UrlEncode("Bring the awesome."), "application/x-www-form-urlencoded"); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, response.StatusDescription); var responseBody = new StreamReader(response.GetResponseStream()).ReadToEnd(); Assert.IsTrue(responseBody.Contains("Bring the awesome."), responseBody); }
public static void Init() { try { GetResponse(WebRequest.Create(UpdateMsgPath), response => { UpdateMsg = new StreamReader(response.GetResponseStream()).ReadToEnd().ToString(); }); Core.DelayAction( () => { GetResponse( WebRequest.Create(WebVersionPath), response => { var data = new StreamReader(response.GetResponseStream()).ReadToEnd().ToString(); if (data.Contains(CurrentVersionPath.ToString())) { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(DateTime.Now.ToString("[H:mm:ss - ") + "Info]" + " KappaAIO: Your version is Updated !"); Console.ResetColor(); } else { Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine(DateTime.Now.ToString("[H:mm:ss - ") + "Warn] KappaAIO: There is a new Update Available for KappaAIO !"); Console.ResetColor(); Console.ForegroundColor = ConsoleColor.Cyan; Chat.Print("<b>KappaAIO: There is a new Update Available for KappaAIO !</b>"); if (UpdateMsg != string.Empty) { Console.WriteLine(DateTime.Now.ToString("[H:mm:ss - ") + "Info] KappaAIO: " + UpdateMsg); Console.ResetColor(); Chat.Print("<b>KappaAIO: " + UpdateMsg + "</b>"); Common.ShowNotification("There is a new Update Available for KappaAIO !", 10000, UpdateMsg); } else { Console.WriteLine(DateTime.Now.ToString("[H:mm:ss - ") + "Info] KappaAIO: Failed to retrive update msg"); Console.ResetColor(); Chat.Print("<b>KappaAIO: Failed to Retrieve Update msg</b>"); Common.ShowNotification("There is a new Update Available for KappaAIO !", 10000, "Failed to retrive update msg"); } } }); }, 500); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine(DateTime.Now.ToString("[H:mm:ss - ") + "Warn] KappaAIO: Failed To Check for Updates !"); Console.WriteLine(DateTime.Now.ToString("[H:mm:ss - ") + ex); Console.ResetColor(); } }
/// <summary> /// Allows OAuth applications to directly exchange Twitter usernames and passwords for OAuth access tokens and secrets. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <returns>A <see cref="OAuthTokenResponse"/> instance.</returns> public static OAuthTokenResponse GetAccessTokens(string consumerKey, string consumerSecret, string username, string password) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(username)) { throw new ArgumentNullException("username"); } if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException("password"); } OAuthTokenResponse response = new OAuthTokenResponse(); try { WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/oauth/access_token"), HTTPVerb.POST, new OAuthTokens() { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }, ""); builder.Parameters.Add("x_auth_username", username); builder.Parameters.Add("x_auth_password", password); builder.Parameters.Add("x_auth_mode", "client_auth"); string responseBody = new StreamReader(builder.ExecuteRequest().GetResponseStream()).ReadToEnd(); response.Token = Regex.Match(responseBody, @"oauth_token=([^&]+)").Groups[1].Value; response.TokenSecret = Regex.Match(responseBody, @"oauth_token_secret=([^&]+)").Groups[1].Value; if (responseBody.Contains("user_id=")) response.UserId = long.Parse(Regex.Match(responseBody, @"user_id=([^&]+)").Groups[1].Value, CultureInfo.CurrentCulture); response.ScreenName = Regex.Match(responseBody, @"screen_name=([^&]+)").Groups[1].Value; } catch (WebException wex) { throw new Exception(wex.Message, wex); } return response; }
public void Serialize_message_without_typeinfo() { using (var stream = new MemoryStream()) { Serializer.SkipArrayWrappingForSingleMessages = true; Serializer.Serialize(new object[] { new SimpleMessage() }, stream); stream.Position = 0; var result = new StreamReader(stream).ReadToEnd(); Assert.That(!result.Contains("$type"), result); } }
public void Should_be_able_to_serialize_and_deserialize_a_transport_message() { var original = new TransportMessage(); var sut = SUT(); var stream = sut.Serialize(original); var xml = new StreamReader(stream).ReadToEnd(); Assert.IsTrue(xml.Contains(original.MessageId.ToString())); stream.Position = 0; Assert.AreEqual(original.MessageId, ((TransportMessage)sut.Deserialize(typeof(TransportMessage), stream)).MessageId); }
public static Tuple<bool, string> Login(string user, string hash) { if (user == null || hash == null) { return new Tuple<bool, string>(false, "Password or username is empty"); } try { var uri = "username="******"&password="******"http://" + AuthServer + "/forum/api.php?request=login"); wr.Timeout = 2000; wr.ContentLength = dataBytes.Length; wr.Method = "POST"; wr.ContentType = "application/x-www-form-urlencoded"; var dataStream = wr.GetRequestStream(); dataStream.Write(dataBytes, 0, dataBytes.Length); dataStream.Close(); var response = wr.GetResponse(); using (var stream = response.GetResponseStream()) { if (stream != null) { var responseString = new StreamReader(stream, Encoding.UTF8).ReadToEnd(); if (responseString.Contains("success")) { return new Tuple<bool, string>(true, "Success!"); } } } return new Tuple<bool, string>(false, "Wrong password or username, register at http://" + AuthServer); } catch (Exception e) { return new Tuple<bool, string>(true, "Fallback T_T"); } }
public void ThenAllDataWillBeSent() { GivenKinesisClient(); WhenLoggerCreated(); var messages = Fixture.CreateMany<string>(100).ToList(); foreach (var message in messages) { Logger.Information(message); Thread.Sleep(TimeSpan.FromMilliseconds(ThrottleTime.TotalMilliseconds / 30)); } Thread.Sleep(ThrottleTime.Add(ThrottleTime)); DataSent.Position = 0; var data = new StreamReader(DataSent).ReadToEnd(); messages.ShouldAllBe(msg => data.Contains(msg)); }
public void Serialize_message_without_concrete_implementation() { var messageMapper = new MessageMapper(); messageMapper.Initialize(new[] { typeof(ISuperMessageWithoutConcreteImpl) }); var serializer = new JsonMessageSerializer(messageMapper); using (var stream = new MemoryStream()) { serializer.Serialize(messageMapper.CreateInstance<ISuperMessageWithoutConcreteImpl>(), stream); stream.Position = 0; var result = new StreamReader(stream).ReadToEnd(); Assert.That(!result.Contains("$type"), result); Assert.That(result.Contains("SomeProperty"), result); } }
public void Serialize_message_without_typeInfo() { var messageMapper = new MessageMapper(); var serializer = new JsonMessageSerializer(messageMapper); using (var stream = new MemoryStream()) { serializer.Serialize(new SimpleMessage(), stream); stream.Position = 0; var result = new StreamReader(stream).ReadToEnd(); Assert.That(!result.Contains("$type"), result); } }
public static void TestSimpleDecryptFileOnThreadWorker() { FileOperationsController controller = new FileOperationsController(_fileSystemState); controller.QueryDecryptionPassphrase += (object sender, FileOperationEventArgs e) => { e.Passphrase = "a"; }; bool knownKeyWasAdded = false; controller.KnownKeyAdded += (object sender, FileOperationEventArgs e) => { knownKeyWasAdded = e.Key == new Passphrase("a").DerivedPassphrase; }; string destinationPath = String.Empty; FileOperationStatus status = FileOperationStatus.Unknown; controller.Completed += (object sender, FileOperationEventArgs e) => { destinationPath = e.SaveFileFullName; status = e.Status; }; using (ThreadWorker worker = new ThreadWorker(new ProgressContext())) { controller.DecryptFile(_helloWorldAxxPath, worker); worker.Join(); } Assert.That(status, Is.EqualTo(FileOperationStatus.Success), "The status should indicate success."); Assert.That(knownKeyWasAdded, "A new known key was used, so the KnownKeyAdded event should have been raised."); IRuntimeFileInfo destinationInfo = OS.Current.FileInfo(destinationPath); Assert.That(destinationInfo.Exists, "After decryption the destination file should be created."); string fileContent; using (Stream stream = destinationInfo.OpenRead()) { fileContent = new StreamReader(stream).ReadToEnd(); } Assert.That(fileContent.Contains("Hello"), "A file named Hello World should contain that text when decrypted."); }
public static void TestSimpleDecryptAndLaunchOnThreadWorker() { FakeLauncher launcher = null; FakeRuntimeEnvironment environment = (FakeRuntimeEnvironment)OS.Current; environment.Launcher = ((string path) => { launcher = new FakeLauncher(path); return launcher; }); FileOperationsController controller = new FileOperationsController(_fileSystemState); controller.QueryDecryptionPassphrase += (object sender, FileOperationEventArgs e) => { e.Passphrase = "a"; }; FileOperationStatus status = FileOperationStatus.Unknown; controller.Completed += (object sender, FileOperationEventArgs e) => { status = e.Status; }; using (ThreadWorker worker = new ThreadWorker(new ProgressContext())) { controller.DecryptAndLaunch(_helloWorldAxxPath, worker); worker.Join(); } Assert.That(status, Is.EqualTo(FileOperationStatus.Success), "The status should indicate success."); Assert.That(launcher, Is.Not.Null, "There should be a call to launch."); Assert.That(Path.GetFileName(launcher.Path), Is.EqualTo("HelloWorld-Key-a.txt"), "The file should be decrypted and the name should be the original from the encrypted headers."); IRuntimeFileInfo destinationInfo = OS.Current.FileInfo(launcher.Path); Assert.That(destinationInfo.Exists, "After decryption the destination file should be created."); string fileContent; using (Stream stream = destinationInfo.OpenRead()) { fileContent = new StreamReader(stream).ReadToEnd(); } Assert.That(fileContent.Contains("Hello"), "A file named Hello World should contain that text when decrypted."); }
/// <summary> /// Обрабатывает очередь сообщений /// </summary> private void FlushQueue() { var notifications = Convert.ToBoolean(ConfigurationManager.AppSettings["Notifications"]); if (!notifications) { return; } using (var httpRequestScope = Locator.BeginNestedHttpRequestScope()) { // Репозиторий var dc = Locator.GetService<LCDataContext>(); var messages = dc.SMSNotificationMessages.Where(m => m.Sended == false).ToList(); // Выходим если в очереди пусто if (messages.Count == 0) { return; } // Обрабатываем очередь Logger.Info(string.Format("Обрабатываем очередь сообщений, в очереди {0} писем", messages.Count)); // Корневой объект отправки var rootObject = new JObject(new JProperty("apikey", new JValue(System.Configuration.ConfigurationManager.AppSettings["SMSAPIKey"]))); // Массив, содержащий отправляемые сообщения var sendArray = new JArray(); // Формируем запрос на отправку foreach (var msg in messages) { var number = StringUtils.NormalizePhoneNumber(msg.Recipient); var sendObject = new JObject( new JProperty("id", new JValue(msg.Id)), new JProperty("from", new JValue("Fulgur.ru")), new JProperty("to",new JValue(number)), new JProperty("text",new JValue(msg.Message))); sendArray.Add(sendObject); } rootObject.Add(new JProperty("send",sendArray)); // Отправляем HttpWebResponse response = null; try { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(String.Format("http://smspilot.ru/api2.php?json={0}", HttpUtility.UrlEncode(rootObject.ToString()))); response = (HttpWebResponse) webRequest.GetResponse(); } catch (Exception e) { Logger.Error(string.Format("Ошибка в ходе обработки очереди СМС: {0}",e.Message)); throw; } // Обрабатываем результат bool sendSuccess = false; var responseStream = response.GetResponseStream(); if (responseStream != null) { // Анализируем ответ var json = new StreamReader(responseStream).ReadToEnd(); if (json.Contains("\"send\"")) { sendSuccess = true; } } // Помечаем письма как отправленные if (sendSuccess) { foreach (var msg in messages) { msg.Sended = true; msg.DateSended = DateTime.Now; } dc.SubmitChanges(); } Logger.Info(string.Format("Обработка очереди смс сообщений завершена.")); } }
// upload a file using the web form instead of the API (for old versions of WikiMedia which don't have the upload API) private void UploadFileThroughForm(LoginInfo loginInfo, string localFilePath, string remoteFilename) { UploadFile[] files = new UploadFile[] { new UploadFile(localFilePath, "wpUploadFile", "application/octet-stream") }; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GetUrl("Special:Upload")); request.CookieContainer = loginInfo.Cookies; var parameters = new System.Collections.Specialized.NameValueCollection(); parameters["wpSourceType"] = "file"; parameters["wpDestFile"] = remoteFilename; parameters["wpUpload"] = "Upload file"; var response = HttpUploadHelper.Upload(request, files, parameters); string strResponse = new StreamReader(response.GetResponseStream()).ReadToEnd(); if (strResponse.Contains("A file with this name exists already")) throw new MediaWikiException("Image already exists on the wiki"); }
// implemented for a wiki that logs users through another form after a redirection private LoginInfo LoginRedirected(Uri uri) { // These parameter names may be specific. If the need arises, they could be made configurable. string postData = string.Format("submit=Login&username={0}&password={1}", Options.Account.Username, Options.Account.Password); ASCIIEncoding encoding = new ASCIIEncoding(); byte[] postBytes = encoding.GetBytes(postData); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Method = WebRequestMethods.Http.Post; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postBytes.Length; var cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; Stream postStream = request.GetRequestStream(); postStream.Write(postBytes, 0, postBytes.Length); postStream.Close(); var response = request.GetResponse(); string strResponse = new StreamReader(response.GetResponseStream()).ReadToEnd(); if (strResponse.Contains("Authentication Failed")) throw new MediaWikiException("Authentication failed"); //var cookies = cookieContainer.GetCookies(uri); return new LoginInfo() { NeedToken = false, Cookies = cookieContainer }; }
static void tt() { var lines = plist.Split(new[] { Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries); for (int i = 25; i < lines.Length; i++) { var line = lines[i]; Console.WriteLine(line); var ss = line.Split(':'); var ip = ss[0]; var port = int.Parse(ss[1]); Exception ex = null; var t = new Thread(() => { try { var p1 = new Socks5(IPAddress.Parse(ip), port); //var p1 = new HttpProxy(IPAddress.Parse("175.182.229.2"), 80); var tcp = p1.CreateConnection(IPAddress.Parse("1111"), 80); var bytes = Encoding.ASCII.GetBytes("GET / HTTP/1.0" + Environment.NewLine + "Host: qwe" + Environment.NewLine + Environment.NewLine); tcp.GetStream().Write(bytes, 0, bytes.Length); var response = new StreamReader(tcp.GetStream()).ReadToEnd(); if (response.Contains("508 Loop Detected")) Console.WriteLine("Blacklisted"); else Console.WriteLine(response); tcp.Close(); } catch (Exception e) { ex = e; } }); t.Start(); if (t.Join(10000)) { if (ex != null) Console.WriteLine("error"); } else { t.Abort(); Console.WriteLine("timeout"); } Console.WriteLine(); } /*var p1 = new Socks5(IPAddress.Parse("98.191.62.242"), 16902); //var p1 = new HttpProxy(IPAddress.Parse("175.182.229.2"), 80); var tcp = p1.CreateConnection(IPAddress.Parse("1111"), 80); var bytes = Encoding.ASCII.GetBytes("GET / HTTP/1.0" + Environment.NewLine + "Host: qwe" + Environment.NewLine + Environment.NewLine); tcp.GetStream().Write(bytes, 0, bytes.Length); Console.WriteLine(new StreamReader(tcp.GetStream()).ReadToEnd()); tcp.Close();*/ }
protected virtual string GetUrlRaw(string rota, object post = null) { var request = (HttpWebRequest)CreateRequest(rota); try { if (post != null) { if (post is string && ((string)post).Contains("xmlns")) { var bytes = System.Text.Encoding.UTF8.GetBytes((string)post); request.Method = "POST"; request.ContentType = "text/xml"; request.ContentLength = bytes.Length; using (var postStream = request.GetRequestStream()) { postStream.Write(bytes, 0, bytes.Length); postStream.Flush(); } } else { var postValuesDict = post is IDictionary <string, object>? new RouteValueDictionary((IDictionary <string, object>)post) : new RouteValueDictionary((object)post); var postValues = string.Join("&", (from key in postValuesDict.Keys select key + "=" + System.Web.HttpUtility.UrlEncode(Convert.ToString(postValuesDict[key])))); var bytes = System.Text.Encoding.UTF8.GetBytes(postValues); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = bytes.Length; using (var postStream = request.GetRequestStream()) { postStream.Write(bytes, 0, bytes.Length); postStream.Flush(); } } } using (var response = (HttpWebResponse)request.GetResponse()) { FixCookies(request, response); // Save cookies to the next request if (response.Cookies != null && response.Cookies.Count > 0) { if (this.lastCookies != null) { foreach (Cookie c in response.Cookies) { var existente = lastCookies.OfType <Cookie>().Where(x => x.Name == c.Name).FirstOrDefault(); if (existente == null) { lastCookies.Add(c); } else { existente.Value = c.Value; } } } else { this.lastCookies = response.Cookies; } } var reader = new System.IO.StreamReader(response.GetResponseStream()); var raw = reader.ReadToEnd(); if (!raw.Contains("{") && !raw.Contains("[") && !raw.Contains("<")) { throw new WebException(raw, null, WebExceptionStatus.UnknownError, response); } LogRaw(rota, raw); return(raw); } } catch (WebException ex) { var proxy = request.Proxy as WebProxy; if (proxy != null) { ex.Data.Add("ext-api_proxy", proxy.Address); } ex.Data.Add("ext-api_rota", rota); ex.Data.Add("ext-api_url", request.RequestUri.ToString()); try { var stream = ex.Response.GetResponseStream(); stream.Seek(0, System.IO.SeekOrigin.Begin); var message = new System.IO.StreamReader(stream).ReadToEnd(); if (message.Contains("<body")) { message = new Regex("<[^>]*>").Replace(message, ""); } ex.Data.Add("ext-api_error", message); } catch { } try { if (request.Credentials as NetworkCredential != null) { ex.Data.Add("userName", (request.Credentials as NetworkCredential).UserName); } if (request.Credentials as CredentialCache != null) { foreach (var c in (request.Credentials as CredentialCache)) { if (c as NetworkCredential != null) { ex.Data.Add("userName", (c as NetworkCredential).UserName); } } } if (request.Headers.AllKeys.Contains("token")) { ex.Data.Add("token", request.Headers["token"]); } } catch { } throw; } }
void PlaceBetThread() { try { Parent.updateStatus(string.Format("Betting: {0:0.00000000} at {1:0.00000000} {2}", amount, this.chance, High ? "High" : "Low")); HttpWebRequest loginrequest = HttpWebRequest.Create("https://www.999dice.com/api/web.aspx") as HttpWebRequest; if (Prox != null) loginrequest.Proxy = Prox; string post = string.Format("a=GetServerSeedHash&s={0}", sessionCookie); string sEmitResponse = ""; double chance = (999999.0) * (this.chance / 100.0); HttpWebResponse EmitResponse; if (next == "" && next!=null) { loginrequest = HttpWebRequest.Create("https://www.999dice.com/api/web.aspx") as HttpWebRequest; if (Prox != null) loginrequest.Proxy = Prox; post = string.Format("a=GetServerSeedHash&s={0}", sessionCookie); loginrequest.Method = "POST"; loginrequest.ContentLength = post.Length; loginrequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; using (var writer = new StreamWriter(loginrequest.GetRequestStream())) { writer.Write(post); } EmitResponse = (HttpWebResponse)loginrequest.GetResponse(); sEmitResponse = new StreamReader(EmitResponse.GetResponseStream()).ReadToEnd(); if (sEmitResponse.Contains("error")) { if (BetRetries++ < 3) { Thread.Sleep(200); PlaceBetThread(); return; } else throw new Exception(); } string Hash = next = json.JsonDeserialize<d999Hash>(sEmitResponse).Hash; } loginrequest = HttpWebRequest.Create("https://www.999dice.com/api/web.aspx") as HttpWebRequest; if (Prox != null) loginrequest.Proxy = Prox; string ClientSeed = r.Next(0, int.MaxValue).ToString(); post = string.Format("a=PlaceBet&s={0}&PayIn={1}&Low={2}&High={3}&ClientSeed={4}&Currency={5}&ProtocolVersion=2", sessionCookie, (long)Math.Ceiling(amount * 100000000.0), High ? 999999 - (int)chance : 0, High ? 999999 : (int)chance, ClientSeed, Currency); loginrequest.Method = "POST"; loginrequest.ContentLength = post.Length; loginrequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; using (var writer = new StreamWriter(loginrequest.GetRequestStream())) { writer.Write(post); } EmitResponse = (HttpWebResponse)loginrequest.GetResponse(); sEmitResponse = new StreamReader(EmitResponse.GetResponseStream()).ReadToEnd(); d999Bet tmpBet = json.JsonDeserialize<d999Bet>(sEmitResponse); if (amount>=21) { } if (tmpBet.ChanceTooHigh==1 || tmpBet.ChanceTooLow==1| tmpBet.InsufficientFunds == 1|| tmpBet.MaxPayoutExceeded==1|| tmpBet.NoPossibleProfit==1) { throw new Exception(); } if (tmpBet.BetId==0) { } balance = (double)tmpBet.StartingBalance / 100000000.0 - (amount) + ((double)tmpBet.PayOut / 100000000.0); profit += -(amount ) + (double)(tmpBet.PayOut / 100000000m); Bet tmp = new Bet(); tmp.Amount = (decimal)amount; tmp.BetDate = DateTime.Now.ToString(); ; tmp.Chance = ((decimal)chance * 100m) / 999999m; tmp.clientseed = ClientSeed; tmp.Currency = Currency; tmp.high = High; tmp.Id = tmpBet.BetId; tmp.nonce = 0; tmp.Profit = ((decimal)tmpBet.PayOut / 100000000m) - ((decimal)amount); tmp.Roll = tmpBet.Secret / 10000m; tmp.serverhash = next; tmp.serverseed = tmpBet.ServerSeed; tmp.uid = (int)uid; tmp.UserName = ""; bool win = false; if ((tmp.Roll > 99.99m - tmp.Chance && High) || (tmp.Roll < tmp.Chance && !High)) { win = true; } if (win) wins++; else losses++; Wagered += tmp.Amount; bets++; BetRetries = 0; sqlite_helper.InsertSeed(tmp.serverhash, tmp.serverseed); next = tmpBet.Next; FinishedBet(tmp); } catch { System.Windows.Forms.MessageBox.Show("Something went wrong! betting stopped."); } }
public static void TestDecryptWithAlternativeDestinationName() { IRuntimeFileInfo expectedDestinationInfo = OS.Current.FileInfo(Path.Combine(Path.GetDirectoryName(_helloWorldAxxPath), "HelloWorld-Key-a.txt")); using (Stream stream = expectedDestinationInfo.OpenWrite()) { } FileOperationsController controller = new FileOperationsController(_fileSystemState); controller.QueryDecryptionPassphrase += (object sender, FileOperationEventArgs e) => { e.Passphrase = "a"; }; controller.QuerySaveFileAs += (object sender, FileOperationEventArgs e) => { e.SaveFileFullName = Path.Combine(Path.GetDirectoryName(e.SaveFileFullName), "Other Hello World.txt"); }; string destinationPath = String.Empty; controller.Completed += (object sender, FileOperationEventArgs e) => { destinationPath = e.SaveFileFullName; }; FileOperationStatus status = controller.DecryptFile(_helloWorldAxxPath); Assert.That(status, Is.EqualTo(FileOperationStatus.Success), "The status should indicate success."); IRuntimeFileInfo destinationInfo = OS.Current.FileInfo(destinationPath); string fileContent; using (Stream stream = destinationInfo.OpenRead()) { fileContent = new StreamReader(stream).ReadToEnd(); } Assert.That(fileContent.Contains("Hello"), "A file named 'Other Hello World.txt' should contain that text when decrypted."); }
private static void HandleWebException(WebException ex) { if (ex.Status == WebExceptionStatus.Timeout) throw new ClientTimeoutException(); if (ex.Status == WebExceptionStatus.KeepAliveFailure) throw new KeepAliveFailureException(); if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) { Stream responseStream = ex.Response.GetResponseStream(); if (responseStream != null) { string message = new StreamReader(responseStream).ReadToEnd(); if (message.Contains("quota exceeded")) throw new ClientQuotaExceededException(); string symbol; if (IsSymbolNotFound(ex, out symbol)) throw new SymbolNotFoundException(symbol); if (message.Contains("Message") && message.Contains("StatusCode")) throw new ClientBadRequestException(message); if (ex.Message.Contains("(401) Unauthorized")) throw new ClientAuthorizationException(); throw new ClientGenericProtocolException(message); } } throw ex; }
public static byte[] GetBytesFromResponse(string URL, string commands = null, string user = null, string password = null, int?timeOut = null, string contentType = null, Dictionary <string, string> headers = null, Dictionary <string, string> cookies = null, string userAgent = null, string method = "GET", string Body = "") { Stream stream = default(Stream); HttpWebResponse response = default(HttpWebResponse); HttpWebRequest request = default(HttpWebRequest); Uri uri = default(Uri); string strResponse = String.Empty; string fullURL = String.Empty; try { if (!String.IsNullOrEmpty(commands)) { if (!commands.StartsWith(@"/")) { @commands = @"/" + @commands; } if (!commands.EndsWith(@"/")) { @commands += @"/"; } } fullURL = @URL + @commands ?? ""; uri = new Uri(@fullURL); stream = default(Stream); response = default(HttpWebResponse); request = (WebRequest.Create(uri) as HttpWebRequest); if (!String.IsNullOrEmpty(URL)) { request.Timeout = (int)TimeSpan.FromSeconds(timeOut ?? 60).TotalMilliseconds; request.ReadWriteTimeout = (int)TimeSpan.FromSeconds(timeOut ?? 60).TotalMilliseconds; request.ContentType = contentType; request.Method = method; request.UserAgent = userAgent; request.AllowAutoRedirect = true; request.AllowWriteStreamBuffering = false; request.MaximumAutomaticRedirections = byte.MaxValue; request.MaximumResponseHeadersLength = byte.MaxValue; request.PreAuthenticate = false; request.UseDefaultCredentials = true; request.AutomaticDecompression = DecompressionMethods.GZip; request.KeepAlive = false; if (!String.IsNullOrEmpty(user) && !String.IsNullOrEmpty(password)) { request.PreAuthenticate = true; request.UseDefaultCredentials = false; request.Credentials = new NetworkCredential(user, password); } else { request.Credentials = CredentialCache.DefaultCredentials; } if (cookies != null) { request.CookieContainer = new CookieContainer(); foreach (var item in cookies) { request.CookieContainer.SetCookies(uri, item.Value); } } if (headers.Count > 0) { foreach (var item in headers) { if (item.Key.Equals("accept", StringComparison.OrdinalIgnoreCase)) { request.Accept = item.Value; } else { request.Headers.Add(item.Key, item.Value); } } } if (!string.IsNullOrEmpty(Body)) { request.ContentLength = 1; } if (request.ContentLength <= 0) { try { response = (request.GetResponse() as HttpWebResponse); if (response.StatusCode == HttpStatusCode.OK) { stream = response.GetResponseStream(); } } catch (WebException ex) { response = (ex.Response as HttpWebResponse); stream = (response != null) ? response.GetResponseStream() : null; string error = ""; try { if (ex is WebException && ((WebException)ex).Status == WebExceptionStatus.ProtocolError) { WebResponse errResp = ((WebException)ex).Response; using (Stream respStream = errResp.GetResponseStream()) { // read the error response error = new System.IO.StreamReader(ex.Response.GetResponseStream()).ReadToEnd(); } if (error.Contains("No hay registros asociados")) { byte[] bytes = UTF8Encoding.UTF8.GetBytes(error); return(bytes); } else { throw new Exception(String.Format(error, URL)); } } } catch (Exception) { } } if (stream != null) { byte[] buffer = Util.GetBytesFromStream(stream); if (buffer.Length > 0) { headers.Clear(); if (response.Headers.Count > 0) { if (headers == null) { headers = new Dictionary <string, string>(); } for (int i = 0; i < response.Headers.Count; i++) { headers.Add(response.Headers.GetKey(i), response.Headers.Get(i)); } } return(buffer); } else { throw new Exception(String.Format(Errors[0], strResponse)); } } else { throw new Exception(Errors[1]); } } else { byte[] Trama = UTF8Encoding.UTF8.GetBytes(Body); request.ContentLength = Trama.Length; stream = request.GetRequestStream(); stream.Write(Trama, 0, Trama.Length); response = request.GetResponse() as HttpWebResponse; StreamReader reader = new StreamReader(response.GetResponseStream()); string Respuesta = reader.ReadToEnd(); if ((!string.IsNullOrEmpty(Respuesta))) { byte[] bytes = UTF8Encoding.UTF8.GetBytes(Respuesta); return(bytes); } else { throw new Exception(Errors[1]); } } } else { throw new Exception(String.Format(Errors[2], URL)); } } catch (System.Net.WebException ex) { string error = ""; try { if (ex is WebException && ((WebException)ex).Status == WebExceptionStatus.ProtocolError) { WebResponse errResp = ((WebException)ex).Response; using (Stream respStream = errResp.GetResponseStream()) { // read the error response error = new System.IO.StreamReader(ex.Response.GetResponseStream()).ReadToEnd(); } if (error.Contains("No hay registros asociados")) { byte[] bytes = UTF8Encoding.UTF8.GetBytes(error); return(bytes); } else { throw new Exception(String.Format(error, URL)); } } } catch (Exception) { throw; } } catch (System.Exception ex) { throw new Exception(String.Format(Errors[3], ex.Message, fullURL)); } finally { if (request != null) { request.Abort(); } if (response != null) { response.Close(); } if (stream != null) { stream.Close(); } } byte[] res = null; return(res); }
private string GetOvalDefinitionsXml(string resourceFolder, string resouceName) { var resourcePath = String.Format("{0}.{1}", resourceFolder, resouceName); try { var ovalDefinitionsAsStream = new OvalDocumentLoader().GetStreamFrom(resourcePath); if (ovalDefinitionsAsStream == null) Assert.Fail("A resource with name '{0}' could not be found.", resourcePath); var ovalDefinitionsAsXml = new StreamReader(ovalDefinitionsAsStream).ReadToEnd(); Assert.IsNotNull(ovalDefinitionsAsXml, "Could not possible to get Oval Definitions Document from stream."); Assert.IsTrue(ovalDefinitionsAsXml.Contains("<oval_definitions "), "The document is not an Oval Definitions file. Missing <oval_definitions> begin tag."); Assert.IsTrue(ovalDefinitionsAsXml.Contains("</oval_definitions>"), "The document is not an Oval Definitions file. Missing </oval_definitions> closing tag."); return ovalDefinitionsAsXml; } catch (Exception ex) { Assert.Fail("An error occurred while trying to load resource '{0}': '{1}'.", resourcePath, ex.Message); return null; } }
/// <summary> /// Send the current trade offer. /// </summary> /// <param name="message">Message to send with trade offer.</param> /// <param name="token">Optional trade offer token.</param> /// <returns>-1 if response fails to deserialize (general error), 0 if no tradeofferid exists (Steam error), or the Trade Offer ID of the newly created trade offer.</returns> public ulong SendTrade(string message, string token = "") { var url = "https://steamcommunity.com/tradeoffer/new/send"; var referer = "http://steamcommunity.com/tradeoffer/new/?partner=" + partnerId.AccountID; var data = new NameValueCollection(); data.Add("sessionid", sessionId); data.Add("partner", partnerId.ConvertToUInt64().ToString()); data.Add("tradeoffermessage", message); data.Add("json_tradeoffer", JsonConvert.SerializeObject(this.tradeStatus)); data.Add("trade_offer_create_params", token == "" ? "{}" : "{\"trade_offer_access_token\":\"" + token + "\"}"); try { string result = ""; for (int i = 0; i < 10; i++) { try { var response = SteamWeb.Request(url, "POST", data, cookies, true, referer); using (System.IO.Stream responseStream = response.GetResponseStream()) { using (var reader = new System.IO.StreamReader(responseStream)) { result = reader.ReadToEnd(); if (string.IsNullOrEmpty(result)) { Console.WriteLine("Web request failed (status: {0}). Retrying...", response.StatusCode); System.Threading.Thread.Sleep(1000); } else { break; } } } } catch (WebException ex) { try { int statusCode = 0; if (ex.Status == WebExceptionStatus.ProtocolError) { statusCode = (int)((HttpWebResponse)ex.Response).StatusCode; Console.WriteLine("Status Code: {0}, {1}", statusCode, ((HttpWebResponse)ex.Response).StatusDescription); } string errorMessage = new System.IO.StreamReader(ex.Response.GetResponseStream()).ReadToEnd(); Console.WriteLine("Error: {0}", errorMessage); if (statusCode == 500 && errorMessage.Contains("There was an error sending your trade offer.")) { var errorJson = JsonConvert.DeserializeObject <dynamic>(errorMessage); if (errorJson.strError != null) { string errorString = errorJson.strError; int errorCode = Convert.ToInt32(errorString.Split(new char[] { '(', ')' })[1]); if (errorCode == 16 || errorCode == 11) { Console.WriteLine("Encountered Steam error code {0}, manually checking for completion...", errorCode); var tradeOfferList = tradeOffers.GetTradeOffers(); foreach (var tradeOffer in tradeOfferList) { if (tradeStatus.me.assets.Count == tradeOffer.ItemsToGive.Length && tradeStatus.them.assets.Count == tradeOffer.ItemsToReceive.Length) { foreach (var item in tradeOffer.ItemsToGive) { var asset = new TradeAsset(item.AppId, Convert.ToInt64(item.ContextId), item.AssetId.ToString(), item.Amount); if (!tradeStatus.me.assets.Contains(asset)) { Console.WriteLine("Could not validate that this trade offer was sent successfully. (1)"); return(0); } } foreach (var item in tradeOffer.ItemsToReceive) { var asset = new TradeAsset(item.AppId, Convert.ToInt64(item.ContextId), item.AssetId.ToString(), item.Amount); if (!tradeStatus.them.assets.Contains(asset)) { Console.WriteLine("Could not validate that this trade offer was sent successfully. (2)"); return(0); } } Console.WriteLine("Successfully validated!"); return(tradeOffer.Id); } } } else if (errorCode == 15) { throw new TradeOfferException(errorString, errorCode); } } } } catch { } } catch (Exception ex) { Console.WriteLine(ex); } } var jsonResponse = JsonConvert.DeserializeObject <dynamic>(result); try { return(Convert.ToUInt64(jsonResponse.tradeofferid)); } catch { return(0); } } catch { return(0); } }
public static void TestDecryptFileWithRepeatedPassphraseQueries() { FileOperationsController controller = new FileOperationsController(_fileSystemState); int passphraseTry = 0; controller.QueryDecryptionPassphrase += (object sender, FileOperationEventArgs e) => { switch (++passphraseTry) { case 1: e.Passphrase = "b"; break; case 2: e.Passphrase = "d"; break; case 3: e.Passphrase = "a"; break; case 4: e.Passphrase = "e"; break; }; }; string destinationPath = String.Empty; controller.Completed += (object sender, FileOperationEventArgs e) => { destinationPath = e.SaveFileFullName; }; bool knownKeyWasAdded = false; controller.KnownKeyAdded += (object sender, FileOperationEventArgs e) => { knownKeyWasAdded = e.Key == new Passphrase("a").DerivedPassphrase; }; FileOperationStatus status = controller.DecryptFile(_helloWorldAxxPath); Assert.That(status, Is.EqualTo(FileOperationStatus.Success), "The status should indicate success."); Assert.That(knownKeyWasAdded, "A new known key was used, so the KnownKeyAdded event should have been raised."); Assert.That(passphraseTry, Is.EqualTo(3), "The third key was the correct one."); IRuntimeFileInfo destinationInfo = OS.Current.FileInfo(destinationPath); Assert.That(destinationInfo.Exists, "After decryption the destination file should be created."); string fileContent; using (Stream stream = destinationInfo.OpenRead()) { fileContent = new StreamReader(stream).ReadToEnd(); } Assert.That(fileContent.Contains("Hello"), "A file named Hello World should contain that text when decrypted."); }
/// <summary> /// Begins the async query. /// </summary> /// <param name="index">The index.</param> /// <param name="query">The query.</param> /// <param name="includes">The include paths</param> public Task<QueryResult> QueryAsync(string index, IndexQuery query, string[] includes) { EnsureIsNotNullOrEmpty(index, "index"); var path = query.GetIndexQueryUrl(url, index, "indexes"); if (includes != null && includes.Length > 0) { path += "&" + string.Join("&", includes.Select(x => "include=" + x).ToArray()); } var request = jsonRequestFactory.CreateHttpJsonRequest(new CreateHttpJsonRequestParams(this, path, "GET", credentials, convention)); return request.ReadResponseJsonAsync() .ContinueWith(task => { RavenJObject json; try { json = (RavenJObject) task.Result; } catch (AggregateException e) { var we = e.ExtractSingleInnerException() as WebException; if(we != null) { var httpWebResponse = we.Response as HttpWebResponse; if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.NotFound) { var text = new StreamReader(httpWebResponse.GetResponseStreamWithHttpDecompression()).ReadToEnd(); if (text.Contains("maxQueryString")) throw new InvalidOperationException(text, e); throw new InvalidOperationException("There is no index named: " + index); } } throw; } return new QueryResult { IsStale = Convert.ToBoolean(json["IsStale"].ToString()), IndexTimestamp = json.Value<DateTime>("IndexTimestamp"), IndexEtag = new Guid(request.ResponseHeaders["ETag"]), Results = ((RavenJArray)json["Results"]).Cast<RavenJObject>().ToList(), TotalResults = Convert.ToInt32(json["TotalResults"].ToString()), IndexName = json.Value<string>("IndexName"), SkippedResults = Convert.ToInt32(json["SkippedResults"].ToString()) }; }); }
public static void TestDecryptWithKnownKey() { FileOperationsController controller = new FileOperationsController(_fileSystemState); _fileSystemState.KnownKeys.Add(new Passphrase("b").DerivedPassphrase); _fileSystemState.KnownKeys.Add(new Passphrase("c").DerivedPassphrase); _fileSystemState.KnownKeys.Add(new Passphrase("a").DerivedPassphrase); _fileSystemState.KnownKeys.Add(new Passphrase("e").DerivedPassphrase); bool passphraseWasQueried = false; controller.QueryDecryptionPassphrase += (object sender, FileOperationEventArgs e) => { passphraseWasQueried = true; }; string destinationPath = String.Empty; controller.Completed += (object sender, FileOperationEventArgs e) => { destinationPath = e.SaveFileFullName; }; bool knownKeyWasAdded = false; controller.KnownKeyAdded += (object sender, FileOperationEventArgs e) => { knownKeyWasAdded = true; }; FileOperationStatus status = controller.DecryptFile(_helloWorldAxxPath); Assert.That(status, Is.EqualTo(FileOperationStatus.Success), "The status should indicate success."); Assert.That(!knownKeyWasAdded, "An already known key was used, so the KnownKeyAdded event should not have been raised."); Assert.That(!passphraseWasQueried, "An already known key was used, so the there should be no need to query for a passphrase."); IRuntimeFileInfo destinationInfo = OS.Current.FileInfo(destinationPath); Assert.That(destinationInfo.Exists, "After decryption the destination file should be created."); string fileContent; using (Stream stream = destinationInfo.OpenRead()) { fileContent = new StreamReader(stream).ReadToEnd(); } Assert.That(fileContent.Contains("Hello"), "A file named Hello World should contain that text when decrypted."); }
/// <summary> /// Loads from the unofficial online tool /// </summary> public static void LoadBuildFromPoezone(SkillTree tree, string buildUrl) { if (!buildUrl.Contains('#')) throw new FormatException(); const string dataUrl = "http://poezone.ru/skilltree/data.js"; const string buildPostUrl = "http://poezone.ru/skilltree/"; string build = buildUrl.Substring(buildUrl.LastIndexOf('#') + 1); string dataFile, buildFile; { var req = (HttpWebRequest) WebRequest.Create(dataUrl); req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Iron/12.0.750.0 Chrome/12.0.750.0 Safari/534.30"; WebResponse resp = req.GetResponse(); dataFile = new StreamReader(resp.GetResponseStream()).ReadToEnd(); } { string postData = "build=" + build; byte[] postBytes = Encoding.ASCII.GetBytes(postData); var req = (HttpWebRequest) WebRequest.Create(buildPostUrl); req.Method = "POST"; req.ContentLength = postBytes.Length; req.ContentType = "application/x-www-form-urlencoded"; req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Iron/12.0.750.0 Chrome/12.0.750.0 Safari/534.30"; req.Accept = "application/json, text/javascript, */*; q=0.01"; req.Host = "poezone.ru"; req.Referer = "http://poezone.ru/skilltree/"; req.AutomaticDecompression = DecompressionMethods.GZip; //req.Headers.Add( "Accept", "application/json, text/javascript" ); req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3"); req.Headers.Add("Accept-Encoding", "gzip,deflate,sdch"); req.Headers.Add("Accept-Language", "en-US,en;q=0.8"); //req.Headers.Add( "Connection", "keep-alive" ); //req.Headers.Add( "Host", "poezone.ru" ); req.Headers.Add("Origin", "http://poezone.ru"); //req.Headers.Add( "Referer", "http://poezone.ru/skilltree/" ); //req.Headers.Add( "User-Agent", ); req.Headers.Add("X-Requested-With", "XMLHttpRequest"); req.Expect = ""; req.Credentials = CredentialCache.DefaultCredentials; Stream dataStream = req.GetRequestStream(); dataStream.Write(postBytes, 0, postBytes.Length); dataStream.Close(); WebResponse resp = req.GetResponse(); string status = (resp as HttpWebResponse).StatusDescription; buildFile = new StreamReader(resp.GetResponseStream()).ReadToEnd(); } if (!buildFile.Contains("[")) { Popup.Error(string.Format(L10n.Message("An error occured while attempting to load Skill tree from {0} location."), "poezone.ru")); return; } // position decompose var positions = new List<Vector2D?>(); string[] lines = dataFile.Split('\n'); foreach (string line in lines) if (line.StartsWith("skillpos=")) { string posString = line.Substring(line.IndexOf('[') + 1, line.LastIndexOf(']') - line.IndexOf('[') - 1); var sb = new StringBuilder(); bool inBracket = false; foreach (char c in posString) { if (!inBracket && c == ',') { positions.Add(sb.Length == 0 ? null : new Vector2D?(new Vector2D( int.Parse(sb.ToString().Split(',')[0]), int.Parse(sb.ToString().Split(',')[1]) ))); sb.Clear(); } else { if (c == '[') inBracket = true; else if (c == ']') inBracket = false; else sb.Append(c); } } positions.Add(sb.Length == 0 ? null : new Vector2D?(new Vector2D( int.Parse(sb.ToString().Split(',')[0]), int.Parse(sb.ToString().Split(',')[1]) ))); } // min max double minx = float.MaxValue, miny = float.MaxValue, maxx = float.MinValue, maxy = float.MinValue; foreach (var posn in positions) { if (!posn.HasValue) continue; Vector2D pos = posn.Value; minx = Math.Min(pos.X, minx); miny = Math.Min(pos.Y, miny); maxx = Math.Max(pos.X, maxx); maxy = Math.Max(pos.Y, maxy); } double nminx = float.MaxValue, nminy = float.MaxValue, nmaxx = float.MinValue, nmaxy = float.MinValue; foreach (SkillNode node in SkillTree.Skillnodes.Values) { Vector2D pos = node.Position; nminx = Math.Min(pos.X, nminx); nminy = Math.Min(pos.Y, nminy); nmaxx = Math.Max(pos.X, nmaxx); nmaxy = Math.Max(pos.Y, nmaxy); } //respose string[] buildResp = buildFile.Replace("[", "").Replace("]", "").Split(','); int character = int.Parse(buildResp[0]); var skilled = new List<int>(); tree.Chartype = character; tree.SkilledNodes.Clear(); SkillNode startnode = SkillTree.Skillnodes.First(nd => nd.Value.Name == SkillTree.CharName[tree.Chartype].ToUpper()).Value; tree.SkilledNodes.Add(startnode.Id); for (int i = 1; i < buildResp.Length; ++i) { if (!positions[int.Parse(buildResp[i])].HasValue) Debugger.Break(); Vector2D poezonePos = (positions[int.Parse(buildResp[i])].Value - new Vector2D(minx, miny))* new Vector2D(1/(maxx - minx), 1/(maxy - miny)); double minDis = 2; var minNode = new KeyValuePair<ushort, SkillNode>(); foreach (var node in SkillTree.Skillnodes) { Vector2D nodePos = (node.Value.Position - new Vector2D(nminx, nminy))* new Vector2D(1/(nmaxx - nminx), 1/(nmaxy - nminy)); double dis = (nodePos - poezonePos).Length; if (dis < minDis) { minDis = dis; minNode = node; } } tree.SkilledNodes.Add(minNode.Key); } tree.UpdateAvailNodes(); //string dataFile = }