public static CookieJar StudyQuestionnairePostToDeployments(CookieJar cookieJar, PanelPreferences preferences)
        {
            var studyQuestionnaireViewUrl = new Uri(preferences.PanelAdminUrl + "StudyQuestionnaireView.aspx");

            string questionnaireViewToDeployFormParams = GetQuestionnaireViewToDeployFormParams(studyQuestionnaireViewUrl, cookieJar.SourceCode);
            var bytes = Encoding.ASCII.GetBytes(questionnaireViewToDeployFormParams);

            var questionnaireViewToDeployRequest = AutomationHelper.CreatePost(studyQuestionnaireViewUrl, cookieJar);
            questionnaireViewToDeployRequest.Referer = preferences.PanelAdminUrl + "HomeView.aspx";
            questionnaireViewToDeployRequest.ContentLength = bytes.Length;

            using (Stream os = questionnaireViewToDeployRequest.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
            }

            var response = (HttpWebResponse)questionnaireViewToDeployRequest.GetResponse();
            string cookies = response.Headers["Set-Cookie"];
            string pageSource = String.Empty;
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                pageSource = reader.ReadToEnd();
            }

            cookieJar.VcAuthentication = AutomationHelper.GetVcAuthentication(cookies);
            cookieJar.UniqueRequestId = AutomationHelper.GetReqId(cookies);

            response.Close();
            return cookieJar;
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Open()
        {
            var cookieJar = new CookieJar();
            await _authorizationService.AuthorizeAsync(User, cookieJar, CookieJarAuthOperations.Open);

            return(View());
        }
Exemplo n.º 3
0
        public static CookieJar AuthenticationPost(string viewState, CookieJar cookieJar, PanelPreferences preferences)
        {
            var authenticationViewUrl = new Uri(preferences.PanelAdminUrl + "AuthenticationView.aspx");
            string authenticationFormParams = GetAuthFormParams(viewState, preferences);
            byte[] bytes = Encoding.ASCII.GetBytes(authenticationFormParams);

            var authenticationRequest = AutomationHelper.CreatePost(authenticationViewUrl, cookieJar);
            authenticationRequest.Headers.Remove("Cookie");
            authenticationRequest.Referer = preferences.PanelAdminUrl + "AuthenticationView.aspx";
            authenticationRequest.ContentLength = bytes.Length;
            authenticationRequest.AllowAutoRedirect = false;

            using (Stream os = authenticationRequest.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
            }

            var response = (HttpWebResponse)authenticationRequest.GetResponse();

            string cookies = response.Headers["Set-Cookie"];

            cookieJar.AspNetSessionId = AutomationHelper.GetSessionId(cookies);
            cookieJar.VcAuthentication = AutomationHelper.GetVcAuthentication(cookies);

            response.Close();

            return cookieJar;
        }
        /// <summary> set all current cookies for each new request </summary>
        public static bool ApplyAllCookiesToRequest(this UnityWebRequest self)
        {
            Uri uri = new Uri(self.url);

            try {
                // If available use the CookieContainer to apply set cookies to the request:
                var container = IoC.inject.Get <System.Net.CookieContainer>(uri);
                if (container != null)
                {
                    self.SetRequestHeader("Cookie", container.GetCookieHeader(uri));
                    return(true);
                }
                // Else use the CookieJar (if available):
                CookieJar jar = IoC.inject.Get <CookieJar>(uri);
                if (jar == null)
                {
                    return(true);
                }
                var allCookies = jar.GetCookies(new CookieAccessInfo(uri.Host, uri.AbsolutePath));
                if (allCookies.IsNullOrEmpty() && uri.Scheme.Equals("https"))
                {
                    allCookies = jar.GetCookies(new CookieAccessInfo(uri.Host, uri.AbsolutePath, true));
                }
                return(self.SetCookies(allCookies));
            }
            catch (Exception e) { Log.e(e); }
            return(false);
        }
Exemplo n.º 5
0
        /// <summary>Loads the domain data from the given JSON string.</summary>
        public void LoadFromJson(string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                return;
            }

            // Load the JSON:
            JSObject json = JSON.Parse(data);

            if (json == null)
            {
                return;
            }

            // Setup content and cookies:
            JSObject cookies = json["cookies"];

            if (cookies != null)
            {
                // Setup:
                Cookies = new CookieJar(this);
                Cookies.LoadFromJson(cookies);
            }

            // Content:
            JSObject content = json["files"];

            if (content != null)
            {
                // Setup:
                Content = new CachedContentSet(this);
                Content.LoadFromJson(content);
            }
        }
        public static CookieJar ValidateStudyPost(CookieJar cookieJar, PanelPreferences preferences)
        {
            var studyQuestionnaireViewUrl = new Uri(preferences.PanelAdminUrl + "StudyQuestionnaireView.aspx");
            string questionnaireViewFormParams = GetQuestionnaireViewFormParams(studyQuestionnaireViewUrl, cookieJar.SourceCode);
            var bytes = Encoding.ASCII.GetBytes(questionnaireViewFormParams);

            var questionnaireViewRequest = AutomationHelper.CreatePost(studyQuestionnaireViewUrl, cookieJar);
            questionnaireViewRequest.Referer = preferences.PanelAdminUrl + "HomeView.aspx";
            questionnaireViewRequest.ContentLength = bytes.Length;

            questionnaireViewRequest.Headers.Add("Cookie", "ASP.NET_SessionId=" + cookieJar.AspNetSessionId + "; .VCPanelAuth=" + cookieJar.VcAuthentication + "; " + ".reqid=" + cookieJar.UniqueRequestId + "; " + " .vcmach=" + cookieJar.MachineId);

            using (Stream os = questionnaireViewRequest.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
            }

            var response = (HttpWebResponse)questionnaireViewRequest.GetResponse();
            string cookies = response.Headers["Set-Cookie"];
            string pageSource = String.Empty;
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                pageSource = reader.ReadToEnd();
            }

            cookieJar.SourceCode = pageSource;
            cookieJar.VcAuthentication = AutomationHelper.GetVcAuthentication(cookies);
            cookieJar.UniqueRequestId = AutomationHelper.GetReqId(cookies);

            response.Close();
            return cookieJar;
        }
        public static CookieJar PanelSettingsPostToAssetManager(CookieJar cookieJar, PanelPreferences preferences)
        {
            var panelSettingsViewUrl = new Uri(preferences.PanelAdminUrl + "PanelSettingsManagementView.aspx");
            string panelSettingsViewFormParams = GetPanelSettingsToAssetManagerFormParams();
            var bytes = Encoding.ASCII.GetBytes(panelSettingsViewFormParams);

            var homeViewRequest = AutomationHelper.CreatePost(panelSettingsViewUrl, cookieJar);
            homeViewRequest.Referer = preferences.PanelAdminUrl + "PanelSettingsManagementView.aspx";
            homeViewRequest.ContentLength = bytes.Length;

            using (Stream os = homeViewRequest.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
            }

            var response = (HttpWebResponse)homeViewRequest.GetResponse();
            string cookies = response.Headers["Set-Cookie"];
            string pageSource = String.Empty;
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                pageSource = reader.ReadToEnd();
            }

            cookieJar.UniqueRequestId = AutomationHelper.GetReqId(cookies);

            response.Close();
            return cookieJar;
        }
Exemplo n.º 8
0
        public static CookieJar HomeViewGet(CookieJar cookieJar, PanelPreferences preferences)
        {
            var client = new WebClient();

            client.Headers.Add("Pragma", "no-cache");
            client.Headers.Add("Accept", "text/html, application/xhtml+xml, */*");
            client.Headers.Add("Accept-Encoding", "gzip, deflate");
            client.Headers.Add("Accept-Language", "en-US");
            client.Headers.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
            client.Headers.Add("Referer", preferences.PanelAdminUrl + "HomeView.aspx");

            client.Headers.Add("Cookie", "ASP.NET_SessionId=" + cookieJar.AspNetSessionId + "; .VCPanelAuth=" + cookieJar.VcAuthentication + ";");

            var source = client.DownloadString(preferences.PanelAdminUrl + "ChangePasswordView.aspx");

            string cookies = client.ResponseHeaders["Set-Cookie"];

            cookieJar.MachineId = AutomationHelper.GetVcMach(cookies);
            cookieJar.VcAuthentication = AutomationHelper.GetVcAuthentication(cookies);
            cookieJar.UniqueRequestId = AutomationHelper.GetReqId(cookies);

            client.Dispose();

            return cookieJar;
        }
Exemplo n.º 9
0
        public static CookieJar HomeViewPostToPanelSettingsManager(CookieJar cookieJar, PanelPreferences preferences)
        {
            //Added for Panel settings will be fecthed from UI not from WebConfig
            var homeViewUrl = new Uri(preferences.PanelAdminUrl + "HomeView.aspx");
            string homeViewFormParams = GetHomeViewFormParams();
            var bytes = Encoding.ASCII.GetBytes(homeViewFormParams);

            var homeViewRequest = AutomationHelper.CreatePost(homeViewUrl, cookieJar);
            homeViewRequest.Referer = preferences.PanelAdminUrl + "HomeView.aspx";
            homeViewRequest.ContentLength = bytes.Length;

            using (Stream os = homeViewRequest.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
            }

            var response = (HttpWebResponse)homeViewRequest.GetResponse();
            string cookies = response.Headers["Set-Cookie"];
            string pageSource = String.Empty;
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                pageSource = reader.ReadToEnd();
            }

            cookieJar.SourceCode = pageSource;
            cookieJar.VcAuthentication = AutomationHelper.GetVcAuthentication(cookies);
            cookieJar.UniqueRequestId = AutomationHelper.GetReqId(cookies);

            response.Close();
            return cookieJar;
        }
Exemplo n.º 10
0
        public void AddCookieWithSubSubDomainIsSuccessful()
        {
            var cookieJar = new CookieJar();

            cookieJar.Add(new Uri("http://baz.foo.bar.ext"), new Cookie {
                Domain = "bar.ext"
            });
        }
Exemplo n.º 11
0
 public void LoginUser(IEnumerable <FlurlCookie> cookies)
 {
     Cookies = new CookieJar();
     foreach (var cookie in cookies)
     {
         Cookies.AddOrReplace(cookie);
     }
 }
Exemplo n.º 12
0
        public void AddCookieThatDoesNotMatchSubDomainWillThrowException()
        {
            var cookieJar = new CookieJar();

            Assert.Throws <CookieException>(() => cookieJar.Add(new Uri("http://bar.ext"), new Cookie {
                Domain = "foo.bar.ext"
            }));
        }
Exemplo n.º 13
0
        public void ClearAndIsEmpty()
        {
            CookieJar jar = new CookieJar();

            jar.Store["a"] = "b";
            Assert.IsFalse(jar.IsEmpty);
            jar.Clear();
            Assert.IsTrue(jar.IsEmpty);
        }
Exemplo n.º 14
0
        public void BuildWithToString()
        {
            CookieJar jar = new CookieJar();

            jar.Store["A1"]   = "B1";
            jar.Store[" C1"]  = "D1";
            jar.Store[" C4 "] = " D4 ";

            Assert.AreEqual("A1=B1; C1=D1; C4 = D4 ", jar.ToString());
        }
Exemplo n.º 15
0
        public static async Task <bool> PingAsync(string room)
        {
            int       index;
            string    me;
            CookieJar cookies   = new CookieJar();
            string    StintoUrl = "https://stin.to/api/chat/" + room + "/";

            while (true)
            {
                me = RandomString(6);
                IFlurlResponse response;
                try {
                    Trace.WriteLine("Logujem se u sobu za ping " + room);
                    response = await StintoUrl.AppendPathSegment("login").WithTimeout(999).PostUrlEncodedAsync(new { nick = me, termsOfUse = "true" });

                    if (response.ResponseMessage.IsSuccessStatusCode)
                    {
                        cookies.AddOrReplace(response.Cookies[1]);
                        break;
                    }
                }
                catch (FlurlHttpException ex) when(ex.StatusCode == 429)
                {
                    Trace.WriteLine("Previše se logujem se u sobu za ping " + room);
                    await Task.Delay(500);

                    continue;
                }
            }
            Trace.WriteLine("Gledam ko sam ja u pingu u sobi " + room);
            string result = await StintoUrl.AppendPathSegment("poll").SetQueryParam("seq", -2).WithCookies(cookies).GetStringAsync();

            string[] lines = result.Substring(0, result.IndexOf("\n0")).Split('\n');
            lines = lines.Take(lines.Length - 1).Where(line => line.Split('\t')[6] == me && line.Split('\t')[8] == "false").ToArray();
            me    = lines[0].Split('\t')[4];

            Trace.WriteLine("Čitam index poslednje poruke za ping u sobi " + room);
            result = DecodeUri((await StintoUrl.AppendPathSegment("poll").SetQueryParam("seq", 0).WithCookies(cookies).GetStringAsync()).Trim());
            index  = Convert.ToInt32(result.Split('\n').Last().Split('\t')[0], 16);

            Trace.WriteLine("Zovem domaćina za ping u sobi " + room);
            await StintoUrl.AppendPathSegment("post").WithCookies(cookies).PostUrlEncodedAsync(new { type = "TXT", text = "private" + delimeter + areyoufree + delimeter + me });

            var cancellationToken = new CancellationTokenSource();
            var task = WaitPingAsync(cookies, StintoUrl, me, index, cancellationToken.Token);

            Trace.WriteLine("Čekam domaćinov odgovr za ping u sobi " + room);
            if (await Task.WhenAny(task, Task.Delay(waitTime, cancellationToken.Token)) == task)
            {
                return(true);
            }
            Trace.WriteLine("Domaćin nije odgovrio u sobi " + room);
            cancellationToken.Cancel();
            return(false);
        }
Exemplo n.º 16
0
 private void Setup()
 {
     HTTPCacheService.SetupCacheFolder();
     CookieJar.SetupFolder();
     CookieJar.Load();
     if (IsThreaded)
     {
         new Thread(ThreadFunc).Start();
     }
     IsSetupCalled = true;
 }
 private void Start()
 {
     if (PlayerPrefs.HasKey("userName"))
     {
         CookieJar.Set(this.URI, new Cookie("user", PlayerPrefs.GetString("userName")));
     }
     this.signalRConnection                  = new Connection(this.URI);
     this.signalRConnection.JsonEncoder      = new LitJsonEncoder();
     this.signalRConnection.OnStateChanged  += new OnStateChanged(this.signalRConnection_OnStateChanged);
     this.signalRConnection.OnNonHubMessage += new OnNonHubMessageDelegate(this.signalRConnection_OnGeneralMessage);
     this.signalRConnection.Open();
 }
 // Use this for initialization
 void Start()
 {
     jar = FindObjectOfType <CookieJar>();
     if (isLocalPlayer)
     {
         CookieClick[] clickers = FindObjectsOfType <CookieClick>();
         foreach (CookieClick clicker in clickers)
         {
             clicker.gateway = this;
         }
     }
 }
Exemplo n.º 19
0
        public bool SendSms(string recipient, string message)
        {
            if (IsLoggedIn == false)
            {
                throw new Exception("Not logged in");
            }

            string cookieVal = CookieJar.GetCookies(new Uri(base_url))["JSESSIONID"].Value;

            cookieVal = cookieVal.Substring(cookieVal.IndexOf('~') + 1);

            CQ sendSmsPage           = Client.DownloadString(base_url + "SendSMS?id=" + cookieVal);
            NameValueCollection data = new NameValueCollection();
            //all inputs
            CQ form   = sendSmsPage.Find("form[id=frm_sendsms]");
            CQ inputs = form.Find("input[type=hidden]");

            foreach (var input in inputs)
            {
                CQ inp = input.Cq();
                data.Add(inp.Attr("name"), inp.Attr("value"));
            }

            //sms input
            CQ mobileNumberBox = form.Find("input[placeholder='Enter Mobile Number or Name']")[0].Cq();

            data.Add(mobileNumberBox.Attr("name"), recipient);

            //textarea
            data.Add("sendSMSMsg", message);
            string sendSmsPost = base_url + data["fkapps"];

            data["hid_exists"]  = "no";
            data["maxwellapps"] = cookieVal;

            //additional vsls
            data.Add("messid_0", "");
            data.Add("messid_1", "");
            data.Add("messid_2", "");
            data.Add("messid_3", "");
            data.Add("messid_4", "");
            data.Add("newsExtnUrl", "");
            data.Add("reminderDate", DateTime.Now.ToString("dd-MM-yyyy"));
            data.Add("sel_hour", "");
            data.Add("sel_minute", "");
            data.Add("ulCategories", "29");

            Client.UploadValues(sendSmsPost, data);

            return(true);
        }
Exemplo n.º 20
0
        public async Task <IEnumerable <FlurlCookie> > LoginUserAsync(string userName, string password)
        {
            var request = FlurlClient.Request("login");
            var cookies = new CookieJar();
            var body    = new
            {
                username = userName,
                password
            };
            await RetryPolicy.ExecuteAsync(() => request.WithCookies(out cookies).PostUrlEncodedAsync(body));

            Cookies = cookies.Remove(cookie => !cookie.Name.StartsWith("bgg", StringComparison.OrdinalIgnoreCase));
            return(Cookies);
        }
Exemplo n.º 21
0
        public void GetRequestHeaderValueReturnsCorrectValue()
        {
            var cookieJar = new CookieJar();

            cookieJar.Add(new Uri("http://bar.ext"), new Cookie {
                Name = "a", Value = "x", Domain = "bar.ext"
            });
            cookieJar.Add(new Uri("http://foo.bar.ext"), new Cookie {
                Name = "b", Value = "y", Domain = "bar.ext"
            });

            var header = cookieJar.GetRequestHeaderValue(new Uri("http://bar.ext"));

            Assert.Equal("a=x; b=y", header);
        }
Exemplo n.º 22
0
        public static async Task <string> GetData(string date)
        {
            CookieJar cookies = new CookieJar();

            await "http://www.slagalica.tv/korisnik/prijava_submit/".WithCookies(cookies).PostUrlEncodedAsync(new { openid = "ovojeime", lozinka = "ovojesifra" });
            string response = await("http://www.slagalica.tv/play/asocijacije/" + date).WithCookies(cookies).GetStringAsync();
            string cypher   = GetStringBetween(response, "ajax_rpc_loader('", "'));");
            string key      = "F81A23D45E67B09C";
            string result   = "";

            for (int i = 0; i < cypher.Length; i += 2)
            {
                result += (char)((key.IndexOf(cypher[i]) * 16) + key.IndexOf(cypher[i + 1]));
            }
            return(GetStringBetween(Regex.Unescape(result), "{", "}"));
        }
Exemplo n.º 23
0
        public void CookieValuesAreOverwritten()
        {
            var cookieJar = new CookieJar();

            cookieJar.Add(new Uri("http://bar.ext"), new Cookie {
                Name = "a", Value = "x", Domain = "bar.ext"
            });
            cookieJar.Add(new Uri("http://foo.bar.ext"), new Cookie {
                Name = "a", Value = "y", Domain = "bar.ext"
            });

            var cookies = cookieJar.GetCookies(new Uri("http://bar.ext"));

            Assert.Equal(1, cookies.Count);
            Assert.Equal("y", cookies[0].Value);
        }
Exemplo n.º 24
0
        public static HttpWebRequest CreatePost(Uri url, CookieJar cookieJar)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.Headers["Accept-Language"] = "en-US";
            request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
            request.ContentType = "application/x-www-form-urlencoded";
            //homeViewRequest.Headers["Accept-Encoding"] = "gzip, deflate";
            request.Host = url.Host;
            request.Headers.Add("Cookie", "ASP.NET_SessionId=" + cookieJar.AspNetSessionId + "; .VCPanelAuth=" + cookieJar.VcAuthentication + "; " + ".reqid=" + cookieJar.UniqueRequestId + "; " + " .vcmach=" + cookieJar.MachineId);
            request.Headers["Pragma"] = "no-cache";
            request.Method = "POST";
            request.KeepAlive = true;

            return request;
        }
Exemplo n.º 25
0
        public async Task <IActionResult> Open()
        {
            var cookieJar = new CookieJar();

            cookieJar.Name = "Open";
            //var requirement = new OperationAuthizationRequirement(CookieJarOperatins.Open);
            //var result = await this._authorizationService.AuthorizeAsync(User, cookieJar, requirement);

            var result = await this._authorizationService.AuthorizeAsync(User, cookieJar, CookieJarAuthOperations.Open);

            if (result.Succeeded)
            {
                //to do something
                return(View());
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 26
0
        public static IFlurlClient ConfigureArkDefaults(this IFlurlClient client)
        {
            var j = new CookieJar();

            client.AllowAnyHttpStatus();
            return(client.Configure(s =>
            {
                s.BeforeCall += c => c.Request.WithCookies(j);
                s.HttpClientFactory = ArkHttpClientFactory.Instance;
                var jsonSettings = new ArkJsonSerializerSettings();

                s.JsonSerializer = new NewtonsoftJsonSerializer(jsonSettings);

                s.ConnectionLeaseTimeout = TimeSpan.FromMinutes(60);
                s.Timeout = TimeSpan.FromMinutes(5);
            }));
        }
Exemplo n.º 27
0
 static async Task <bool> WaitPingAsync(CookieJar cookies, string StintoUrl, string me, int index, CancellationToken cancellationToken)
 {
     while (!cancellationToken.IsCancellationRequested)
     {
         Trace.WriteLine("Čekam odgovor na ping drugi put");
         string result = DecodeUri(await StintoUrl.AppendPathSegment("poll").SetQueryParam("seq", index).WithCookies(cookies).GetStringAsync());
         foreach (string line in result.Trim().Split('\n'))
         {
             index++;
             string[] words = line.Split('\t');
             if (words[3] == "t" && words[4] == "private" + delimeter + yeahimhere + delimeter + me)
             {
                 return(true);
             }
         }
     }
     return(false);
 }
Exemplo n.º 28
0
        public void CanBeSerialized()
        {
            var cookieJar = new CookieJar();

            cookieJar.Add(new Uri("http://bar.ext"), new Cookie {
                Name = "a", Value = "x", Domain = "bar.ext"
            });
            cookieJar.Add(new Uri("http://foo.bar.ext"), new Cookie {
                Name = "b", Value = "y", Domain = "bar.ext"
            });

            var json = JsonConvert.SerializeObject(cookieJar);

            var cookieJarDeserialized = JsonConvert.DeserializeObject <CookieJar>(json);
            var header = cookieJarDeserialized.GetRequestHeaderValue(new Uri("http://bar.ext"));

            Assert.Equal("a=x; b=y", header);
        }
 private static List <Cookie> LoadStoredCookiesForUri(Uri uri)
 {
     try {
         CookieJar jar = IoC.inject.Get <CookieJar>(uri);
         if (jar == null)
         {
             return(new List <Cookie>());
         }
         var c = jar.GetCookies(new CookieAccessInfo(uri.Host, uri.AbsolutePath));
         if (c.IsNullOrEmpty() && uri.Scheme.Equals("https"))
         {
             c = jar.GetCookies(new CookieAccessInfo(uri.Host, uri.AbsolutePath, true));
         }
         return(c);
     }
     catch (Exception e) { Log.e(e); }
     return(new List <Cookie>());
 }
Exemplo n.º 30
0
        public void UpdateFromAllHeaderVariants()
        {
            CookieJar jar = new CookieJar();
            Dictionary <string, string> headers = new Dictionary <string, string> {
                { "Set-Cookie", "A1=B1; C1=D1 " },
                { "SET-COOKIE", "A2=B2;C2=D2" },
                { "set-cookie", "A3=B3" },
                { "Set-cookie", "A4=B4; C4=D4 " },
            };

            jar.Update(headers);
            Assert.AreEqual(7, jar.Store.Count);
            Assert.AreEqual("B1", jar.Store["A1"]);
            Assert.AreEqual("D1 ", jar.Store[" C1"]);
            Assert.AreEqual("B2", jar.Store["A2"]);
            Assert.AreEqual("B3", jar.Store["A3"]);
            Assert.AreEqual("B4", jar.Store["A4"]);
            Assert.AreEqual("D4 ", jar.Store[" C4"]);
        }
Exemplo n.º 31
0
        public void GetCookiesWillReturnAllMatchingCookies()
        {
            var cookieJar = new CookieJar();

            cookieJar.Add(new Uri("http://bar.ext"), new Cookie {
                Name = "a", Domain = "bar.ext"
            });
            cookieJar.Add(new Uri("http://foo.bar.ext"), new Cookie {
                Name = "b", Domain = "bar.ext"
            });
            cookieJar.Add(new Uri("http://foo.ext"), new Cookie {
                Name = "c", Domain = "foo.ext"
            });

            var cookies = cookieJar.GetCookies(new Uri("http://bar.ext"));

            Assert.Equal(2, cookies.Count);
            Assert.True(cookies.Cast <Cookie>().All(c => c.Domain == "bar.ext"));
        }
Exemplo n.º 32
0
        public void ClearRemovesAllCookies()
        {
            var cookieJar = new CookieJar();

            cookieJar.Add(new Uri("http://bar.ext"), new Cookie {
                Name = "a", Domain = "bar.ext"
            });
            cookieJar.Add(new Uri("http://foo.bar.ext"), new Cookie {
                Name = "b", Domain = "bar.ext"
            });
            cookieJar.Add(new Uri("http://foo.ext"), new Cookie {
                Name = "c", Domain = "foo.ext"
            });
            cookieJar.Clear();

            var cookies = cookieJar.GetCookies(new Uri("http://bar.ext"));

            Assert.Equal(0, cookies.Count);
        }
Exemplo n.º 33
0
        public static IFlurlClient ConfigureArkDefaultsSystemTextJson(this IFlurlClient client)
        {
            var j = new CookieJar();

            client.AllowAnyHttpStatus();
            return(client.Configure(s =>
            {
                s.BeforeCall += c => c.Request
                                .WithCookies(j)
                                .WithHeader("Accept-Encoding", "gzip, deflate, br")
                ;
                s.HttpClientFactory = ArkHttpClientFactory.Instance;

                s.JsonSerializer = new SystemTextJsonSerializer(ArkSerializerOptions.JsonOptions);

                s.ConnectionLeaseTimeout = TimeSpan.FromMinutes(60);
                s.Timeout = TimeSpan.FromMinutes(5);
            }));
        }
Exemplo n.º 34
0
        // Handle saved minecraft.net sessions
        bool LoadCookie(bool remember)
        {
            if (File.Exists(Paths.CookieContainerFile))
            {
                if (remember)
                {
                    // load a saved session
                    BinaryFormatter formatter = new BinaryFormatter();
                    using (Stream s = File.OpenRead(Paths.CookieContainerFile)) {
                        CookieJar = (CookieContainer)formatter.Deserialize(s);
                    }
                    CookieCollection cookies = CookieJar.GetCookies(new Uri(MinecraftNet));
                    foreach (Cookie c in cookies)
                    {
                        // look for a cookie that corresponds to the current minecraft username
                        int start = c.Value.IndexOf("username%3A" + MinecraftUsername,
                                                    StringComparison.OrdinalIgnoreCase);
                        if (start != -1)
                        {
                            MainForm.Log("MC.LoadCookie: Loaded saved session for " + MinecraftUsername);
                            return(true);
                        }
                    }

                    // if saved session was not for the current username, discard it
                    MainForm.Log("MC.LoadCookie: Discarded a saved session (username mismatch)");
                    ResetCookies();
                }
                else
                {
                    // discard a saved session
                    MainForm.Log("MC.LoadCookie: Discarded a saved session");
                    ResetCookies();
                }
            }
            else
            {
                // no session saved
                ResetCookies();
            }
            return(false);
        }
        /// <summary>
        /// Get All Cookies
        /// </summary>
        /// <returns></returns>
        public static List <Cookie> GetAllCookies()
        {
            List <Cookie> cookieCollection = new List <Cookie>();

            Hashtable table = (Hashtable)CookieJar.GetType().InvokeMember("m_domainTable",
                                                                          BindingFlags.NonPublic |
                                                                          BindingFlags.GetField |
                                                                          BindingFlags.Instance,
                                                                          null,
                                                                          cookieJar,
                                                                          new object[] { });

            foreach (var tableKey in table.Keys)
            {
                String str_tableKey = (string)tableKey;

                if (str_tableKey[0] == '.')
                {
                    str_tableKey = str_tableKey.Substring(1);
                }

                SortedList list = (SortedList)table[tableKey].GetType().InvokeMember("m_list",
                                                                                     BindingFlags.NonPublic |
                                                                                     BindingFlags.GetField |
                                                                                     BindingFlags.Instance,
                                                                                     null,
                                                                                     table[tableKey],
                                                                                     new object[] { });

                foreach (var listKey in list.Keys)
                {
                    String url     = "https://" + str_tableKey + (string)listKey;
                    var    cookies = cookieJar.GetCookies(new Uri(url));
                    foreach (Cookie c in cookies)
                    {
                        cookieCollection.Add(c);
                    }
                }
            }

            return(cookieCollection);
        }
Exemplo n.º 36
0
        public static void OnQuit()
        {
            HTTPManager.Logger.Information("HTTPManager", "OnQuit called!");

            IsQuitting = true;

            AbortAll();

#if !BESTHTTP_DISABLE_CACHING
            HTTPCacheService.SaveLibrary();
#endif

#if !BESTHTTP_DISABLE_COOKIES
            CookieJar.Persist();
#endif

            OnUpdate();

            HostManager.Clear();
        }
Exemplo n.º 37
0
        public static GeneralStatistics GetGeneralStatistics(StatisticsQueryFlags queryFlags)
        {
            GeneralStatistics result = default(GeneralStatistics);

            result.QueryFlags = queryFlags;
            if ((byte)(queryFlags & StatisticsQueryFlags.Connections) != 0)
            {
                int num = 0;
                foreach (KeyValuePair <string, List <HTTPConnection> > current in HTTPManager.Connections)
                {
                    if (current.Value != null)
                    {
                        num += current.Value.Count;
                    }
                }
                result.Connections         = num;
                result.ActiveConnections   = HTTPManager.ActiveConnections.Count;
                result.FreeConnections     = HTTPManager.FreeConnections.Count;
                result.RecycledConnections = HTTPManager.RecycledConnections.Count;
                result.RequestsInQueue     = HTTPManager.RequestQueue.Count;
            }
            if ((byte)(queryFlags & StatisticsQueryFlags.Cache) != 0)
            {
                result.CacheEntityCount = HTTPCacheService.GetCacheEntityCount();
                result.CacheSize        = HTTPCacheService.GetCacheSize();
            }
            if ((byte)(queryFlags & StatisticsQueryFlags.Cookies) != 0)
            {
                List <Cookie> all = CookieJar.GetAll();
                result.CookieCount = all.Count;
                uint num2 = 0u;
                for (int i = 0; i < all.Count; i++)
                {
                    num2 += all[i].GuessSize();
                }
                result.CookieJarSize = num2;
            }
            return(result);
        }
Exemplo n.º 38
0
        public static CookieJar UpdateLanguageAndSkinPost(CookieJar cookieJar, string environment, PanelPreferences preferences)
        {
            if (environment.Length == 0 | environment == null)
            {
                throw new Exception("Invalid environment: " + environment);
            }

            var anonymousLinkViewUrl = new Uri(preferences.PanelAdminUrl + "AnonymousLinkView.aspx");

            //Passed new parameter preferences of PanelPreferences type for Language selection
            string anonymousLinkViewFormParams = GetUpdateLanguageAndSkinPostForms(environment, preferences);
            var bytes = Encoding.ASCII.GetBytes(anonymousLinkViewFormParams);

            var homeViewRequest = AutomationHelper.CreatePost(anonymousLinkViewUrl, cookieJar);
            homeViewRequest.Referer = preferences.PanelAdminUrl + "AnonymousLinkView.aspx";
            homeViewRequest.ContentLength = bytes.Length;

            using (Stream os = homeViewRequest.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
            }

            var response = (HttpWebResponse)homeViewRequest.GetResponse();
            string cookies = response.Headers["Set-Cookie"];
            string pageSource;
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                pageSource = reader.ReadToEnd();
            }

            cookieJar.SourceCode = pageSource;
            cookieJar.VcAuthentication = AutomationHelper.GetVcAuthentication(cookies);
            cookieJar.UniqueRequestId = AutomationHelper.GetReqId(cookies);

            response.Close();
            return cookieJar;
        }
Exemplo n.º 39
0
        public static CookieJar AssetManagerDeleteNewPortalSkinZip(CookieJar cookieJar, PanelPreferences preferences)
        {
            var assetManagerUrl = new Uri(preferences.PanelAdminUrl + "AssetManagerView.aspx");
            string assetManagerDeleteFormParams = "Cart_AssetManager_MenuCallBack_Callback_Param=delete&Cart_AssetManager_MenuCallBack_Callback_Param=false|p:" + Res.NewPortalSkinPath.ToLower() + "|" + Res.NewPortalSkinPath;
            var bytes = Encoding.ASCII.GetBytes(assetManagerDeleteFormParams);

            var assetManagerRequest = AutomationHelper.CreatePost(assetManagerUrl, cookieJar);
            assetManagerRequest.Referer = preferences.PanelAdminUrl + "AssetManagerView.aspx";
            assetManagerRequest.ContentLength = bytes.Length;

            using (Stream os = assetManagerRequest.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
            }

            var response = (HttpWebResponse)assetManagerRequest.GetResponse();
            string cookies = response.Headers["Set-Cookie"];

            cookieJar.VcAuthentication = AutomationHelper.GetVcAuthentication(cookies);
            cookieJar.UniqueRequestId = AutomationHelper.GetReqId(cookies);

            response.Close();
            return cookieJar;
        }
        public static CookieJar PanelSettingsUpdatePost(CookieJar cookieJar, ContextCollection collection, PanelPreferences preferences)
        {
            var panelSettingsViewUrl = new Uri(preferences.PanelAdminUrl + "PanelSettingsManagementView.aspx");
            string panelSettingsViewFormParams = GetPanelSettingsViewFormParams(collection.GetFormString());
            var bytes = Encoding.ASCII.GetBytes(panelSettingsViewFormParams);

            var panelSettingsRequest = AutomationHelper.CreatePost(panelSettingsViewUrl, cookieJar);
            panelSettingsRequest.Referer = preferences.PanelAdminUrl + "PanelSettingsManagementView.aspx";
            panelSettingsRequest.ContentLength = bytes.Length;

            using (Stream os = panelSettingsRequest.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
            }

            var response = (HttpWebResponse)panelSettingsRequest.GetResponse();
            string cookies = response.Headers["Set-Cookie"];
            cookieJar.VcAuthentication = AutomationHelper.GetVcAuthentication(cookies);
            cookieJar.UniqueRequestId = AutomationHelper.GetReqId(cookies);

            response.Close();

            return cookieJar;
        }
Exemplo n.º 41
0
        public static CookieJar AssetManagerUploadNewSurveySkin(CookieJar cookieJar, string path, PanelPreferences preferences)
        {
            var fileData = new FileStream(path, FileMode.Open, FileAccess.Read);

            var request = (HttpWebRequest)WebRequest.Create(preferences.PanelAdminUrl + "upload.axd?up=s:portal");

            request.Headers.Add("Pragma", "no-cache");
            request.Accept = "text/*";
            request.UserAgent = "Shockwave Flash";
            request.Headers.Add("Cookie", "ASP.NET_SessionId=" + cookieJar.AspNetSessionId + "; .VCPanelAuth=" + cookieJar.VcAuthentication + "; " + ".reqid=" + cookieJar.UniqueRequestId + "; " + " .vcmach=" + cookieJar.MachineId);
            request.Method = "POST";

            string boundary = "----------" + DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture);
            request.ContentType = "multipart/form-data; boundary=" + boundary;

            var stringBuilder = new StringBuilder();

            stringBuilder.AppendFormat("--{0}\r\n", boundary);
            stringBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n", "Filename", Res.NewSurveySkinPath);
            stringBuilder.AppendFormat("--{0}\r\n", boundary);
            stringBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\n", "Filedata", Res.NewSurveySkinPath);
            stringBuilder.AppendFormat("Content-Type: {0}\r\n\r\n", "application/octet-stream");

            byte[] header = Encoding.UTF8.GetBytes(stringBuilder.ToString());
            byte[] footer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            long contentLength = header.Length + fileData.Length + footer.Length;

            request.ContentLength = contentLength;

            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(header, 0, header.Length);

                var buffer = new byte[checked((uint)Math.Min(4096, (int)fileData.Length))];
                int bytesRead;
                while ((bytesRead = fileData.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }

                requestStream.Write(footer, 0, footer.Length);
                var response = request.GetResponse();
            }

            return cookieJar;
        }
Exemplo n.º 42
0
        public static CookieJar ImportNewPxmlStudy(CookieJar cookieJar, string selectedStudyFile, PanelPreferences preferences)
        {
            var fileData = new FileStream(selectedStudyFile, FileMode.Open, FileAccess.Read);

            //Added for Panel settings will be fecthed from UI not from WebConfig
            var request = AutomationHelper.CreatePost(new Uri(preferences.PanelAdminUrl + "ImportNewStudyView.aspx"), cookieJar);
            string contentType = String.Empty;

            request.Referer = preferences.PanelAdminUrl + "ImportNewStudyView.aspx";

            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture);
            request.ContentType = "multipart/form-data; boundary=" + boundary;

            var stringBuilder = new StringBuilder();

            stringBuilder.AppendFormat("--{0}\r\n", boundary);
            stringBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n", "__EVENTTARGET", "ImportStudyFromXmlButton");
            stringBuilder.AppendFormat("--{0}\r\n", boundary);
            stringBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n", "__EVENTARGUMENT", "");
            stringBuilder.AppendFormat("--{0}\r\n", boundary);
            stringBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n", "__VisionCriticalVIEWSTATE", "93");
            stringBuilder.AppendFormat("--{0}\r\n", boundary);
            stringBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n", "__VIEWSTATE", "");
            stringBuilder.AppendFormat("--{0}\r\n", boundary);
            stringBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n", "ctl02$CurrentXPos", "0");
            stringBuilder.AppendFormat("--{0}\r\n", boundary);
            stringBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n", "ctl02$CurrentYPos", "0");
            stringBuilder.AppendFormat("--{0}\r\n", boundary);
            stringBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n", "LoggingOut", "false");
            stringBuilder.AppendFormat("--{0}\r\n", boundary);
            stringBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n", "oPersistObject_FormElement", "");
            stringBuilder.AppendFormat("--{0}\r\n", boundary);
            stringBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n", "nmPick", "");
            stringBuilder.AppendFormat("--{0}\r\n", boundary);
            stringBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n", "ctl02_NM_ContextData", "");
            stringBuilder.AppendFormat("--{0}\r\n", boundary);
            stringBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n", "ctl02_OnlineHelpCtxMenu_ContextData", "");
            stringBuilder.AppendFormat("--{0}\r\n", boundary);
            stringBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\n", "XmlFileInput", Path.GetFileName(selectedStudyFile));//something.xml/.zip
            stringBuilder.AppendFormat("Content-Type: {0}\r\n\r\n", "text/xml");

            byte[] header = Encoding.UTF8.GetBytes(stringBuilder.ToString());

            var footerBuilder = new StringBuilder();
            footerBuilder.AppendFormat("\r\n--{0}\r\n", boundary);
            footerBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n", "XmlStudyName", Path.GetFileNameWithoutExtension(selectedStudyFile) + "_" + DateTime.Now);//just the name of the study TODO account for multiple studies with the same name
            footerBuilder.AppendFormat("--" + boundary + "--\r\n");
            byte[] footer = Encoding.ASCII.GetBytes(footerBuilder.ToString());

            long contentLength = header.Length + fileData.Length + footer.Length;

            request.ContentLength = contentLength;
            string cookies = String.Empty;
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(header, 0, header.Length);

                var buffer = new byte[checked((uint)Math.Min(4096, (int)fileData.Length))];
                int bytesRead = 0;
                while ((bytesRead = fileData.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }

                requestStream.Write(footer, 0, footer.Length);
                var response = request.GetResponse();
                cookies = response.Headers["Set-Cookie"];
            }

            cookieJar.VcAuthentication = AutomationHelper.GetVcAuthentication(cookies);
            cookieJar.UniqueRequestId = AutomationHelper.GetReqId(cookies);
            return cookieJar;
        }
Exemplo n.º 43
0
 public void BeforeEachTest()
 {
     _jar = new CookieJar();
     _cookie = new Cookie("Chocolate", "Chip");
 }
Exemplo n.º 44
0
 public ContextCollection GetContextCollection(CookieJar cookieJar)
 {
     var collection = new ContextCollection(CookieJar.SourceCode);
     return collection;
 }
Exemplo n.º 45
0
 public AutomationService()
 {
     PxmlManager = new PxmlManager();
     CookieJar = new CookieJar();
     Environment = String.Empty;
 }
Exemplo n.º 46
0
 public BrowserEngine(IWebRequester requester)
 {
     _requester = requester;
     _history = new History();
     Cookies = new CookieJar();
 }