private void RunRequestLineTest(string expectedValue)
        {
            WebRequestClient  wrClient  = new WebRequestClient();
            TrafficViewerFile dataStore = new TrafficViewerFile();
            TrafficViewerFile mockSite  = new TrafficViewerFile();
            MockProxy         mockProxy = new MockProxy(dataStore, mockSite);

            mockProxy.Start();

            HttpRequestInfo expectedRequest = new HttpRequestInfo(expectedValue);

            expectedRequest.Host = mockProxy.Host;
            expectedRequest.Port = mockProxy.Port;

            //set the webrequest to use a proxy

            HttpResponseInfo respInfo = wrClient.SendRequest(expectedRequest);

            mockProxy.Stop();
            if (!expectedRequest.IsConnect)
            {
                Assert.AreEqual(1, dataStore.RequestCount);

                byte[] receivedReqBytes = dataStore.LoadRequestData(0);

                HttpRequestInfo receivedRequest = new HttpRequestInfo(receivedReqBytes);

                Assert.AreEqual(expectedValue, receivedRequest.RequestLine);
            }
            else
            {
                Assert.AreEqual("HTTP/1.1 200 Connection established", respInfo.StatusLine);
            }
        }
Exemple #2
0
        public void Test_HTTP_ReusingClient()
        {
            string testRequest1  = "GET http://site.com/ HTTP/1.1\r\n\r\n";
            string testResponse1 = "HTTP/1.1 302 Redirect\r\nLocation: http://site.com/a\r\n\r\n";
            string testRequest2  = "GET http://site.com/a HTTP/1.1\r\n\r\n";
            string testResponse2 = "HTTP/1.1 200 OK\r\n\r\n";

            WebRequestClient client = new WebRequestClient();

            TrafficViewerFile mockSite = new TrafficViewerFile();

            mockSite.AddRequestResponse(testRequest1, testResponse1);
            mockSite.AddRequestResponse(testRequest2, testResponse2);
            TrafficViewerFile dataStore = new TrafficViewerFile();
            MockProxy         mockProxy = new MockProxy(dataStore, mockSite);

            mockProxy.Start();

            client.SetProxySettings(mockProxy.Host, mockProxy.Port, null);

            CheckResponseStatus(testRequest1, client, 302);
            CheckResponseStatus(testRequest2, client, 200);

            mockProxy.Stop();
        }
Exemple #3
0
        protected void CheckResponseStatus(string testRequest, WebRequestClient client, int expectedStatus)
        {
            HttpRequestInfo  reqInfo          = new HttpRequestInfo(testRequest);
            HttpResponseInfo receivedResponse = client.SendRequest(reqInfo);

            Assert.AreEqual(expectedStatus, receivedResponse.Status);
        }
Exemple #4
0
        public string SendTest(string mutatedRequest, string host, int port, bool useSSL)
        {
            IHttpClient     client  = new WebRequestClient();
            HttpRequestInfo reqInfo = new HttpRequestInfo(mutatedRequest);

            reqInfo.IsSecure = useSSL;
            reqInfo.Host     = host;
            reqInfo.Port     = port;
            HttpResponseInfo resp = null;

            try
            {
                resp = client.SendRequest(reqInfo);
            }
            catch
            { }
            string response;

            if (resp != null)
            {
                PatternTracker.Instance.UpdatePatternValues(resp);
                response = resp.ToString();
            }
            else
            {
                response = String.Empty;
            }

            return(response);
        }
Exemple #5
0
        public static void RunTest()
        {
            var client  = new WebRequestClient();
            var request = new Request(HttpMethod.Get, "https://api.twilio.com:8443");

            Response response = null;

            try
            {
                response = client.MakeRequest(request);
            }
            catch (Exception e)
            {
                Console.WriteLine("ERROR:");
                Console.WriteLine(e);
            }

            Console.WriteLine();
            if (response?.StatusCode == HttpStatusCode.OK)
            {
                Console.WriteLine("Result: SUCCESS!");
            }
            else
            {
                Console.WriteLine("Result: FAILURE");
            }

            Console.WriteLine();
            Console.Write("Press any key to continue.");
            Console.ReadKey();
        }
Exemple #6
0
 /// <summary>
 /// Gets an account from the servers.
 /// </summary>
 /// <param name="userId">The account ID of the user.</param>
 /// <returns>An account.</returns>
 public static Account Get(int userId) =>
 RobtopAnalyzer.DeserializeObject <Account>(WebRequestClient.SendRequest(new WebRequest
 {
     Url     = "http://boomlings.com/database/getGJUserInfo20.php",
     Content = new FormUrlEncodedContent(new Dictionary <string, string>
     {
         { "targetAccountID", userId.ToString() },
         { "secret", "Wmfd2893gb7" }
     })
 }));
Exemple #7
0
 /// <summary>
 /// Gets an account from the servers.
 /// </summary>
 /// <param name="userId">The account ID of the user.</param>
 /// <returns>An account.</returns>
 public static string GetString(int userId) =>
 WebRequestClient.SendRequest(new WebRequest
 {
     Url     = "http://boomlings.com/database/getGJUserInfo20.php",
     Content = new FormUrlEncodedContent(new Dictionary <string, string>
     {
         { "targetAccountID", userId.ToString() },
         { "secret", "Wmfd2893gb7" }
     })
 });
 /// <summary>
 /// Constructor for the manual proxy connection
 /// </summary>
 /// <param name="tcpClient">TCP client being used</param>
 /// <param name="isSecure">Whether the connection is secure or not</param>
 /// <param name="dataStore">The data store being used</param>
 /// <param name="description">Description to add to the data store for each request</param>
 /// <param name="networkSettings">Network settings to be used for the connection</param>
 public SampleProxyConnection(TcpClient tcpClient,
                              bool isSecure,
                              ITrafficDataAccessor dataStore,
                              string description,
                              INetworkSettings networkSettings)
     : base(tcpClient, isSecure, dataStore, description)
 {
     _httpClient = new WebRequestClient();
     _httpClient.SetNetworkSettings(networkSettings);
 }
 /// <summary>
 /// Network settings
 /// </summary>
 /// <param name="netSettings"></param>
 public RequestSender(INetworkSettings netSettings)
 {
     _httpClient = new WebRequestClient();
     if (netSettings == null)
     {
         netSettings = new DefaultNetworkSettings();
         netSettings.CertificateValidationCallback = _certificateValidationCallback;
     }
     _httpClient.SetNetworkSettings(netSettings);
     _httpClient.ShouldHandleCookies = true;
 }
Exemple #10
0
        public void TestSendDirectRequest()
        {
            string funky = WebRequestClient.SendRequest(new WebRequest
            {
                Url    = @"http://boomlings.com/database/accounts/loginGJAccount.php",
                Method = HttpMethod.Post
            }, new WebRequestClientOptions()
            {
                IgnoreGdExceptions = true
            });

            Assert.AreEqual(funky, "-1", "HTTP Requests are working.");
        }
Exemple #11
0
        private IHttpClient GetTrackingProxyHttpClient()
        {
            IHttpClient            webClient   = new WebRequestClient();
            DefaultNetworkSettings netSettings = new DefaultNetworkSettings();

            //send the referer request to the tracking proxy
            netSettings.CertificateValidationCallback = _networkSettings.CertificateValidationCallback;


            netSettings.WebProxy = new WebProxy(_parentProxy.Host, _parentProxy.Port);
            webClient.SetNetworkSettings(netSettings);
            return(webClient);
        }
Exemple #12
0
        string ResolveXml()
        {
            XmlDocument parms = null;

            if (HasInheritedValues)
            {
                parms = (XmlDocument)InheritedValues;
            }

            if (HasUri)
            {
                string      uriContent = WebRequestClient.GetString(Uri);
                XmlDocument uriXml     = new XmlDocument();
                uriXml.LoadXml(uriContent);

                if (parms != null)
                {
                    Utilities.MergeHelpers.MergeXml(ref parms, uriXml);
                }
                else
                {
                    parms = uriXml;
                }
            }

            //merge parms
            if (HasValues)
            {
                XmlDocument values = new XmlDocument();
                values.LoadXml(Values.ToString());

                if (parms != null)
                {
                    Utilities.MergeHelpers.MergeXml(ref parms, values);
                }
                else
                {
                    parms = values;
                }
            }

            //kv_replace
            if (HasDynamic)
            {
                Utilities.MergeHelpers.MergeXml(ref parms, Dynamic, _dynamicData);
            }

            //todo: XmlSerializer
            return(parms.ToString());
        }
Exemple #13
0
        private static IHttpClient GetHttpClient()
        {
            SdkSettings.Instance.HttpRequestTimeout = 60;

            WebRequestClient client = new WebRequestClient();

            DefaultNetworkSettings networkSettings = new DefaultNetworkSettings();

            networkSettings.CertificateValidationCallback = new RemoteCertificateValidationCallback(CertificateValidator.ValidateRemoteCertificate);
            networkSettings.WebProxy = HttpWebRequest.GetSystemWebProxy();


            client.SetNetworkSettings(networkSettings);

            return(client);
        }
Exemple #14
0
        string ResolveYaml()
        {
            object parms = null;

            //make rest call
            if (HasUri)
            {
                string uriContent = WebRequestClient.GetString(Uri);

                string uri =
                    @"Magical: Mystery
Lucy: In the sky
Kitten:
  Cat: Tommy
  Color: Rat";
                using (StringReader sr = new StringReader(uri))
                {
                    Deserializer deserializer = new Deserializer(ignoreUnmatched: true);
                    parms = deserializer.Deserialize(sr);
                }
            }

            Dictionary <object, object> p = (Dictionary <object, object>)parms;

            //merge parms
            if (HasValues)
            {
                Utilities.MergeHelpers.MergeYaml(ref p, (Dictionary <object, object>)Values);
            }

            //kv_replace
            if (HasDynamic)
            {
                Utilities.MergeHelpers.MergeYaml(ref p, Dynamic, _dynamicData);
            }

            string v = null;

            using (StringWriter sw = new StringWriter())
            {
                Serializer serializer = new Serializer();
                serializer.Serialize(sw, parms);
                v = sw.ToString();
            }

            return(v);
        }
Exemple #15
0
        /// <summary>
        /// A method to login to an account, creating a <see cref="UserAccount" /> object.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="password">The password</param>
        /// <returns>A user account, if successful.</returns>
        public static UserAccount Login(string username, string password)
        {
            var response = WebRequestClient.SendRequest(new WebRequest
            {
                Url     = @"http://boomlings.com/database/accounts/loginGJAccount.php",
                Content = new FormUrlEncodedContent(new Dictionary <string, string>
                {
                    { "userName", username },
                    { "password", password },
                    { "secret", "Wmfv3899gc9" },
                    { "udid", "GDNET" }
                }),
                Method = HttpMethod.Post
            });

            return(RobtopAnalyzer.DeserializeObject <UserAccount>(GetString(int.Parse(response.Split(',')[0]))));
        }
        public void Test_NetworkSettings_ProxyUsesAProxy()
        {
            MockProxy mockProxy;
            string    testRequest  = "GET http://site.com/ HTTP/1.1\r\n\r\n";
            string    testResponse = "HTTP/1.1 200 OK\r\n\r\n";

            TrafficViewerFile dataStore = new TrafficViewerFile();

            mockProxy = SetupMockProxy(testRequest, testResponse, dataStore);


            mockProxy.Start();



            ManualExploreProxy meProxy = new ManualExploreProxy("127.0.0.1", 0, null);             //use a random port

            meProxy.NetworkSettings.WebProxy = new WebProxy(mockProxy.Host, mockProxy.Port);
            meProxy.Start();

            WebRequestClient client          = new WebRequestClient();
            INetworkSettings networkSettings = new DefaultNetworkSettings();

            networkSettings.WebProxy = new WebProxy(meProxy.Host, meProxy.Port);

            client.SetNetworkSettings(networkSettings);

            HttpRequestInfo testReqInfo = new HttpRequestInfo(testRequest);

            Assert.AreEqual(0, dataStore.RequestCount);

            HttpResponseInfo respInfo = client.SendRequest(testReqInfo);


            meProxy.Stop();
            mockProxy.Stop();

            //test that the request goes through the mock proxy by checking the data store

            Assert.AreEqual(200, respInfo.Status);
            Assert.AreEqual(1, dataStore.RequestCount);
        }
Exemple #17
0
        protected IHttpClient GetHttpClient(ClientType clientType, int proxyPort = -1)
        {
            IHttpClient client;

            if (clientType == ClientType.WebRequestClient)
            {
                client = new WebRequestClient();
            }
            else
            {
                client = new TrafficViewerHttpClient();
            }

            if (proxyPort != -1)
            {
                INetworkSettings netSettings = new DefaultNetworkSettings();
                netSettings.WebProxy = new WebProxy("127.0.0.1", proxyPort);
                client.SetNetworkSettings(netSettings);
            }

            return(client);
        }
Exemple #18
0
        public void Init()
        {
            this._requestUrl  = null;
            this._requestBody = null;

            this._mockFactory         = Substitute.For <HttpWebRequestFactory>();
            this._mockRequest         = Substitute.For <IHttpWebRequestWrapper>();
            this._mockRequest.Headers = new NameValueCollection();

            this._mockResponse = Substitute.For <IHttpWebResponseWrapper>();
            this._mockResponse.GetResponseStream().Returns(new MemoryStream());

            this._mockFactory.Create(Arg.Do <Uri>(arg => this._requestUrl = arg))
            .Returns(this._mockRequest);

            this._mockRequest.GetResponse().Returns(this._mockResponse);
            this._mockRequest.WriteBody(Arg.Do <byte[]>(arg =>
                                                        this._requestBody = Encoding.UTF8.GetString(arg, 0, arg.Length)
                                                        ));

            this.TwilioClient = new WebRequestClient(this._mockFactory);
        }
        string ResolveUnspecified(object parentExitData)
        {
            StringBuilder sb = new StringBuilder();

            if (HasInheritedValues)
            {
                sb.Append(InheritedValues.ToString());
            }

            //make rest call
            if (HasUri)
            {
                sb.Append(WebRequestClient.GetString(Uri));
            }

            //merge parms
            if (HasValues)
            {
                sb.Append(Values.ToString());
            }

            if (HasDynamic)
            {
                foreach (string key in _dynamicData.Keys)
                {
                    sb.Append($"{key}:{_dynamicData[key]},");
                }
            }

            if (HasParentExitData)
            {
                sb.Append(parentExitData.ToString());
            }

            return(sb.ToString().TrimEnd(','));
        }
Exemple #20
0
        string ResolveJson()
        {
            object parms = null;

            if (HasInheritedValues)
            {
                parms = InheritedValues;
            }

            //make rest call
            if (HasUri)
            {
                string uriContent = WebRequestClient.GetString(Uri);

                if (parms != null)
                {
                    object values = null;
                    string uri    = "{  \"ApplicationName\": \"steve\",  \"EnvironmentName\": \"dev\",  \"Tier\": {    \"Name\": \"webserver\",    \"Type\": \"python\",    \"Version\": \"0.0\"  }}";
                    using (StringReader sr = new StringReader(uri))
                    {
                        Deserializer deserializer = new Deserializer(ignoreUnmatched: true);
                        values = deserializer.Deserialize(sr);
                    }

                    Dictionary <object, object> ip = (Dictionary <object, object>)parms;
                    Dictionary <object, object> uv = (Dictionary <object, object>)values;
                    Utilities.MergeHelpers.MergeYaml(ref ip, uv);
                }
                else
                {
                    string uri = "{  \"ApplicationName\": \"steve\",  \"EnvironmentName\": \"dev\",  \"Tier\": {    \"Name\": \"webserver\",    \"Type\": \"python\",    \"Version\": \"0.0\"  }}";
                    using (StringReader sr = new StringReader(uri))
                    {
                        Deserializer deserializer = new Deserializer(ignoreUnmatched: true);
                        parms = deserializer.Deserialize(sr);
                    }
                }
            }

            Dictionary <object, object> p = (Dictionary <object, object>)parms;

            //merge parms
            if (HasValues)
            {
                Utilities.MergeHelpers.MergeYaml(ref p, (Dictionary <object, object>)Values);
            }

            //kv_replace
            if (HasDynamic)
            {
                Utilities.MergeHelpers.MergeYaml(ref p, Dynamic, _dynamicData);
            }

            string v = null;

            using (StringWriter sw = new StringWriter())
            {
                Serializer serializer = new Serializer();
                serializer.Serialize(sw, parms);
                v = sw.ToString();
            }

            return(v);
        }
Exemple #21
0
        public void Test_HTTP_WebRequestClient_Cookies()
        {
            string[] testRequestList  = new string[5];
            string[] testResponseList = new string[5];
            testRequestList[0]  = "GET http://site.com/a/1 HTTP/1.1\r\n\r\n";
            testResponseList[0] = "HTTP/1.1 302 Redirect\r\nSet-Cookie:a=1; Path=/a\r\nLocation: http://site.com/a\r\n\r\n";
            testRequestList[1]  = "GET http://site.com/a/2 HTTP/1.1\r\n\r\n";
            testResponseList[1] = "HTTP/1.1 302 OK\r\n\r\n";
            testRequestList[2]  = "GET http://site.com/b HTTP/1.1\r\nCookie:b=2\r\n\r\n";
            testResponseList[2] = "HTTP/1.1 302 OK\r\n\r\n";
            testRequestList[3]  = "GET http://site.com/a/3 HTTP/1.1\r\n\r\n";
            testResponseList[3] = "HTTP/1.1 302 Redirect\r\nSet-Cookie:a=2; Path=/a; Expires=Thu, 01-Jan-1970 00:00:01 GMT;\r\nLocation: http://site.com/a\r\n\r\n";
            testRequestList[4]  = "GET http://site.com/a/4 HTTP/1.1\r\n\r\n";
            testResponseList[4] = "HTTP/1.1 200 OK\r\n\r\n";

            WebRequestClient client = new WebRequestClient();

            client.ShouldHandleCookies = true;

            TrafficViewerFile mockSite = new TrafficViewerFile();

            for (int idx = 0; idx < testRequestList.Length; idx++)
            {
                mockSite.AddRequestResponse(testRequestList[idx], testResponseList[idx]);
            }

            TrafficViewerFile dataStore = new TrafficViewerFile();
            MockProxy         mockProxy = new MockProxy(dataStore, mockSite);

            mockProxy.Start();

            client.SetProxySettings(mockProxy.Host, mockProxy.Port, null);
            for (int idx = 0; idx < testRequestList.Length; idx++)
            {
                client.SendRequest(new HttpRequestInfo(testRequestList[idx]));
            }

            //second request should have the extra cookie
            byte[] receivedRequestBytes = dataStore.LoadRequestData(1);//index starts from 0
            Assert.IsNotNull(receivedRequestBytes, "Missing second request");

            HttpRequestInfo receivedRequest = new HttpRequestInfo(receivedRequestBytes, true);

            Assert.IsNotNull(receivedRequest.Cookies);
            Assert.AreEqual(1, receivedRequest.Cookies.Count);
            Assert.IsTrue(receivedRequest.Cookies.ContainsKey("a"));

            //third request should not have the a cookie it's sent to /b but should have the b cookie
            receivedRequestBytes = dataStore.LoadRequestData(2);
            Assert.IsNotNull(receivedRequestBytes, "Missing third request");
            receivedRequest = new HttpRequestInfo(receivedRequestBytes, true);
            Assert.IsNotNull(receivedRequest.Cookies);
            Assert.AreEqual(1, receivedRequest.Cookies.Count, "Request to /b should have 1 cookie");
            Assert.IsTrue(receivedRequest.Cookies.ContainsKey("b"));

            //last request should have no cookies because the a cookie is expired
            receivedRequestBytes = dataStore.LoadRequestData(4);
            Assert.IsNotNull(receivedRequestBytes, "Missing fifth request");
            receivedRequest = new HttpRequestInfo(receivedRequestBytes, true);
            Assert.IsNotNull(receivedRequest.Cookies);
            Assert.AreEqual(0, receivedRequest.Cookies.Count, "Last request should have no cookies");


            mockProxy.Stop();
        }
        private void DrawRects(List <TrackedObject> objList, float imageWidth, float imageHeight)
        {
            TrackedObject[]    objs         = objList.ToArray();
            UnityEngine.Rect[] overlayRects = new UnityEngine.Rect[objs.Length];

            // Cleanup missing face
            Dictionary <int, Person> tmpPeople = new Dictionary <int, Person>();

            for (int i = 0; i < objs.Length; i++)
            {
                if (people.ContainsKey(objs[i].id))
                {
                    //Debug.Log("people[objs[i].id].recognizeState" + people[objs[i].id].recognizeState);
                    tmpPeople.Add(objs[i].id, people[objs[i].id]);
                }
            }
            people.Clear();
            people = tmpPeople;

            // Retrun fail recognize
            for (int i = 0; i < objs.Length; i++)
            {
                if (!people.ContainsKey(objs[i].id))
                {
                    Person           person = new Person(objs[i].position, grayMat4Thread);
                    WebRequestClient wrc    = new WebRequestClient();
                    StartCoroutine(wrc.Post(person));
                    people.Add(objs[i].id, person);
                }
                else
                {
                    if (people[objs[i].id].recognizeState == Person.RecognizeState.NOTRECOGNIZED)
                    {
                        if (people[objs[i].id].failReturnCount < FAILRETURNCOUNT)
                        {
                            // delay 24 frame for next recognize
                            if (people[objs[i].id].delayFrameCount > SKIPFRAMEPREFAIL)
                            {
                                people[objs[i].id].UpdateFace(objs[i].position, grayMat4Thread);
                                WebRequestClient wrc = new WebRequestClient();
                                StartCoroutine(wrc.Post(people[objs[i].id]));
                                people[objs[i].id].delayFrameCount = 0;
                                people[objs[i].id].failReturnCount++;
                            }
                            else
                            {
                                people[objs[i].id].delayFrameCount++;
                            }
                        }
                    }
                }

                var rect = rectangleTracker.GetSmoothingRect(i);
                //var rect = objs[i].position;


                overlayRects[i] = new UnityEngine.Rect(rect.x / imageWidth
                                                       , rect.y / imageHeight
                                                       , rect.width / imageWidth
                                                       , rect.height / imageHeight);
            }
            GameObject[] rst = rectOverlay.DrawRects(overlayRects);
            // Assume target spawned prefab are contain PersonOverlayer.
            if (rst != null)
            {
                int cnt = rst.Length;
                PersonOverlayer[] personOverlays = new PersonOverlayer[cnt];
                for (int i = 0; i < cnt; i++)
                {
                    personOverlays[i] = rst[i].GetComponent <PersonOverlayer>();

                    string username = "";
                    string detail   = "";
                    Color  color    = Color.yellow;
                    if (people.ContainsKey(objs[i].id))
                    {
                        username = people[objs[i].id].username;
                        detail   = people[objs[i].id].detail;
                        color    = people[objs[i].id].color;
                    }
                    //Debug.Log("username is " + username);
                    personOverlays[i].SetText(username, detail, color);
                }
            }
        }
        XmlDocument ResolveXml(ref List <object> forEachParms, object parentExitData, Dictionary <string, ParameterInfo> globalParamSets)
        {
            string context = "ResolveXml";
            string errData = __nodata;

            try
            {
                XmlDocument parms = null;

                if (HasInheritedValues)
                {
                    context = "InheritedValues=>Clone";
                    errData = InheritedValues.GetType().ToString();
                    parms   = (XmlDocument)((XmlDocument)((ParameterInfo)InheritedValues).Values).Clone();
                }

                if (HasUri)
                {
                    context = "Uri=>Fetch";
                    try { errData = new Uri(Uri).ToString(); } catch { errData = Uri.ToString(); }

                    string uriContent = WebRequestClient.GetString(Uri);
                    context = "Uri=>Fetch, LoadXml";
                    errData = uriContent;
                    XmlDocument uriXml = new XmlDocument();
                    uriXml.LoadXml(uriContent);

                    context = parms != null ? "Merge->Inherited" : "Assign to parms";
                    context = $"Uri=>{context}";
                    errData = XmlHelpers.Serialize <XmlDocument>(uriXml);
                    if (parms != null)
                    {
                        XmlHelpers.Merge(ref parms, uriXml);
                    }
                    else
                    {
                        parms = uriXml;
                    }
                }

                //merge parms
                if (HasValues)
                {
                    context = "HasValues=>LoadXml";
                    errData = Values.ToString();
                    XmlDocument values = new XmlDocument();
                    values.LoadXml(Values.ToString());

                    context = parms != null ? "Merge->Inherited+Uri+Values" : "Assign to parms";
                    context = $"Uri=>{context}";
                    errData = XmlHelpers.Serialize <XmlDocument>(values);
                    if (parms != null)
                    {
                        XmlHelpers.Merge(ref parms, values);
                    }
                    else
                    {
                        parms = values;
                    }
                }


                if (parms == null)
                {
                    parms = new XmlDocument();
                }


                //kv_replace
                if (HasDynamic)
                {
                    context = "HasDynamic=>Merge->Inherited+Uri+Values+Dynamic";
                    try { errData = YamlHelpers.Serialize(_dynamicData); } catch { errData = __nodata; }   //YamlHelpers not a mistake, used it on purpose for easy to read error data
                    XmlHelpers.Merge(ref parms, Dynamic, _dynamicData);
                }

                if (HasParentExitData && parentExitData != null)
                {
                    context = "ParentExitData=>Init Xml Source";
                    errData = parentExitData.GetType().ToString();

                    XmlDocument xd = new XmlDocument();
                    if (parentExitData is XmlNode)
                    {
                        xd.InnerXml = ((XmlNode)parentExitData).OuterXml;
                    }
                    else if (parentExitData is XmlNode[])
                    {
                        xd.InnerXml = ((XmlNode[])parentExitData)[0].OuterXml;
                    }
                    else if (parentExitData is string)
                    {
                        xd.InnerXml = (string)parentExitData;
                    }
                    else
                    {
                        xd = (XmlDocument)parentExitData;
                    }

                    context = "ParentExitData=>Merge->Inhetited+Uri+Values+Dynamic+ParentExitData";
                    errData = XmlHelpers.Serialize <XmlDocument>(xd);
                    XmlHelpers.Merge(ref parms, ParentExitData, ref xd);
                }

                if (HasForEach && parms != null)
                {
                    //assemble ForEach variables
                    if (ForEach.HasParameterSourceItems)
                    {
                        context = "ForEach=>HasParameterSourceItems";
                        errData = null;
                        XmlHelpers.SelectForEachFromValues(ForEach.ParameterSourceItems, ref parms, globalParamSets, parentExitData);
                    }

                    //expand ForEach variables
                    context = "ForEach=>ExpandForEach";
                    try { errData = XmlHelpers.Serialize <XmlDocument>(parms); } catch { errData = __nodata; }
                    forEachParms = XmlHelpers.ExpandForEachAndApplyPatchValues(ref parms, ForEach);
                }


                return(parms);
            }
            catch (Exception ex)
            {
                throw new Exception(GetResolveExceptionMessage(context, errData), ex);
            }
        }
        Dictionary <object, object> ResolveYamlJson(ref List <object> forEachParms, object parentExitData, Dictionary <string, ParameterInfo> globalParamSets)
        {
            string context = "ResolveYamlJson";
            string errData = __nodata;

            try
            {
                object parms = null;

                if (HasInheritedValues)
                {
                    context = "InheritedValues=>Serialize";
                    string tmp = YamlHelpers.Serialize(((ParameterInfo)InheritedValues).Values);
                    errData = tmp;
                    context = "InheritedValues=>Deserialize";
                    parms   = YamlHelpers.Deserialize(tmp);
                }


                //make rest call
                if (HasUri)
                {
                    context = "Uri=>Fetch";
                    try { errData = new Uri(Uri).ToString(); } catch { errData = Uri.ToString(); }

                    string uriContent = WebRequestClient.GetString(Uri);
                    errData = uriContent;

                    if (parms != null)
                    {
                        context = "Uri=>Desrialize, Merge->Inherited+Uri";
                        object values = YamlHelpers.Deserialize <object>(uriContent);

                        Dictionary <object, object> ip = (Dictionary <object, object>)parms;
                        Dictionary <object, object> uv = (Dictionary <object, object>)values;
                        YamlHelpers.Merge(ref ip, uv);
                    }
                    else
                    {
                        context = "Uri=>Desrialize only";
                        parms   = YamlHelpers.Deserialize <object>(uriContent);
                    }
                }


                if (parms == null)
                {
                    parms = new Dictionary <object, object>();
                }


                context = "Parms=>Cast to Dictionary";
                errData = parms.GetType().ToString();
                Dictionary <object, object> p = (Dictionary <object, object>)parms;


                //merge parms
                if (HasValues && p != null)
                {
                    context = "HasValues=>Merge->Inhetited+Uri+Values";
                    try { errData = YamlHelpers.Serialize(p); } catch { errData = __nodata; }
                    YamlHelpers.Merge(ref p, (Dictionary <object, object>)Values);
                }


                //kv_replace
                if (HasDynamic && p != null)
                {
                    context = "HasDynamic=>Merge->Inhetited+Uri+Values+Dynamic";
                    try { errData = YamlHelpers.Serialize(_dynamicData); } catch { errData = __nodata; }
                    YamlHelpers.Merge(ref p, Dynamic, _dynamicData);
                }


                if (HasParentExitData && p != null && parentExitData != null)
                {
                    context = "ParentExitData=>Serialize";
                    errData = __nodata;

                    string xd = parentExitData is string?parentExitData.ToString() : YamlHelpers.Serialize(parentExitData);

                    errData = xd;
                    context = "ParentExitData=>Deserialize";
                    object values = YamlHelpers.Deserialize(xd);
                    //select the exact values

                    context = "ParentExitData=>Merge->Inhetited+Uri+Values+Dynamic+ParentExitData";
                    Dictionary <object, object> ip = (Dictionary <object, object>)parms;
                    Dictionary <object, object> pv = (Dictionary <object, object>)values;
                    YamlHelpers.Merge(ref ip, ParentExitData, ref pv);
                }


                if (HasForEach && p != null)
                {
                    //assemble ForEach variables
                    if (ForEach.HasParameterSourceItems)
                    {
                        context = "ForEach=>HasParameterSourceItems";
                        errData = null;
                        YamlHelpers.SelectForEachFromValues(ForEach.ParameterSourceItems, ref p, globalParamSets, parentExitData);
                    }

                    //expand ForEach variables
                    context = "ForEach=>ExpandForEach";
                    try { errData = YamlHelpers.Serialize(p); } catch { errData = __nodata; }
                    forEachParms = YamlHelpers.ExpandForEachAndApplyPatchValues(ref p, ForEach);
                }


                return(p);
            }
            catch (Exception ex)
            {
                throw new Exception(GetResolveExceptionMessage(context, errData), ex);
            }
        }
Exemple #25
0
        //[TestMethod]
        public void Test_ReverseProxy()
        {
            string testRequest   = "GET / HTTP/1.1\r\n";
            string site1Response = "HTTP/1.1 200 OK\r\n\r\nThis is site1";
            string site2Response = "HTTP/1.1 200 OK\r\n\r\nThis is site2";
            //create two mock sites each on a different port and a http client that send a request to the first but in fact gets redirected to the other
            TrafficViewerFile site1Source = new TrafficViewerFile();

            site1Source.AddRequestResponse(testRequest, site1Response);
            TrafficViewerFile site2Source = new TrafficViewerFile();

            site2Source.AddRequestResponse(testRequest, site2Response);

            TrafficStoreProxy mockSite1 = new TrafficStoreProxy(
                site1Source, null, "127.0.0.1", 0, 0);

            mockSite1.Start();

            TrafficStoreProxy mockSite2 = new TrafficStoreProxy(
                site2Source, null, "127.0.0.1", 0, 0);

            mockSite2.Start();

            HttpRequestInfo reqInfo = new HttpRequestInfo(testRequest);

            //request will be sent to site 1
            reqInfo.Host = mockSite1.Host;
            reqInfo.Port = mockSite1.Port;

            ReverseProxy revProxy = new ReverseProxy("127.0.0.1", 0, 0, null);

            revProxy.ExtraOptions[ReverseProxy.FORWARDING_HOST_OPT] = mockSite2.Host;
            revProxy.ExtraOptions[ReverseProxy.FORWARDING_PORT_OPT] = mockSite2.Port.ToString();
            revProxy.Start();

            //make an http client
            IHttpClient            client   = new WebRequestClient();
            DefaultNetworkSettings settings = new DefaultNetworkSettings();

            settings.WebProxy = new WebProxy(revProxy.Host, revProxy.Port);

            client.SetNetworkSettings(settings);

            //send the request Http and verify the target site received it

            HttpResponseInfo respInfo = client.SendRequest(reqInfo);
            string           respBody = respInfo.ResponseBody.ToString();


            Assert.IsTrue(respBody.Contains("This is site2"));

            //check over ssl

            reqInfo.IsSecure = true;
            respInfo         = client.SendRequest(reqInfo);
            respBody         = respInfo.ResponseBody.ToString();
            Assert.IsTrue(respBody.Contains("This is site2"));

            mockSite1.Stop();
            mockSite2.Stop();
            revProxy.Stop();
        }
Exemple #26
0
        /// <summary>
        /// Gets an array of levels.
        /// </summary>
        /// <param name="search">A search query</param>
        /// <param name="options">Level search options.</param>
        /// <returns>The array.</returns>
        public static Level[] GetLevels(string search = "", LevelSearchOptions options = null)

        {
            if (options == null)
            {
                options = new LevelSearchOptions();
            }

            Dictionary <string, string> content = new Dictionary <string, string>();

            content = new Dictionary <string, string>
            {
                { "gameVersion", "21" },
                { "binaryVersion", "35" },

                { "type", ((int)options.SearchType).ToString() },
                { "str", search },

                { "len", (options.Length.Length > 0) ? options.Length.FormatEnum(",") : "-" },
                { "diff", (options.Difficulty.Length > 0) ? options.Difficulty.FormatEnum(",") : "-" },

                { "coins", Convert.ToInt32(options.HasCoins).ToString() },
                { "noStar", Convert.ToInt32(options.IsUnrated).ToString() },
                { "twoPlayer", Convert.ToInt32(options.TwoPlayer).ToString() },
                { "featured", Convert.ToInt32(options.Featured).ToString() },
                { "epic", Convert.ToInt32(options.Epic).ToString() },
                { "original", Convert.ToInt32(options.Original).ToString() },

                { "secret", "Wmfd2893gb7" }
            };

            // extraneous/optional params
            if (options.DemonType != DemonType.None)
            {
                content["diff"] = "-2";
                content.Add("demonFilter", ((int)options.DemonType).ToString());
            }

            if (options.CustomSongId > 0 && options.Song > 0)
            {
                throw new ArgumentException("You may not use NewGrounds Song ID's and In-game Song enums at once.");
            }

            if (options.CustomSongId > 0 || options.Song > 0)
            {
                if (options.CustomSongId > 0)
                {
                    content.Add("customSong", options.CustomSongId.ToString());
                }
                else if (options.Song > 0)
                {
                    content.Add("song", ((int)options.Song).ToString());
                }
            }

            string result = WebRequestClient.SendRequest(new WebRequest
            {
                Url     = "http://boomlings.com/database/getGJLevels21.php",
                Content = new FormUrlEncodedContent(content)
            });

            List <Level> levels = RobtopAnalyzer.DeserializeObjectList <Level>(result.Split("#")[0]);

            return(levels.ToArray());
        }
Exemple #27
0
 public string GetFileUri(string uri)
 {
     return(WebRequestClient.GetString(uri));
 }