Пример #1
0
        public List <HTTPHeader> CreateHeaderCredentials()
        {
            List <HTTPHeader> headers = new List <HTTPHeader>();

            if (this.passwordAuth != null)
            {
                var passwordAuthString = this.passwordAuth.GetUserName() + ":" + this.passwordAuth.GetPassword();
                var passwordAuthData   = Encoding.UTF8.GetBytes(passwordAuthString);
                var httpHeader         = new HTTPHeader(AuthenticationConstants.HEADER_KEY_AUTH_PASSWORD, System.Convert.ToBase64String(passwordAuthData));
                headers.Add(httpHeader);
            }

            if (!string.IsNullOrEmpty(this.apiToken))
            {
                var httpHeader = new HTTPHeader(AuthenticationConstants.HEADER_KEY_AUTH_APITOKEN, this.apiToken);
                headers.Add(httpHeader);
            }

            if (this.basicAuth != null)
            {
                var basicAuthString = this.basicAuth.GetUserName() + ":" + this.basicAuth.GetPassword();
                var basicAuthData   = Encoding.UTF8.GetBytes(basicAuthString);
                var httpHeader      = new HTTPHeader(AuthenticationConstants.HEADER_KEY_AUTH_BASIC, AuthenticationConstants.AUTH_BASIC_PREFIX + System.Convert.ToBase64String(basicAuthData));
                headers.Add(httpHeader);
            }
            return(headers);
        }
Пример #2
0
 public SplitSdkApiClient(HTTPHeader header,
                          string baseUrl,
                          long connectionTimeOut,
                          long readTimeout,
                          IMetricsLog metricsLog = null) : base(header, baseUrl, connectionTimeOut, readTimeout, metricsLog)
 {
 }
Пример #3
0
        public async ValueTask <int> ConsumeAsync(ReadOnlyMemory <byte> toConsume)
        {
            if (Header == null)
            {
                if (Parser == null)
                {
                    Parser = new HTTPHeaderParser();
                }

                var consumed = await Parser.ConsumeAsync(toConsume);

                if (consumed > -1)
                {
                    toConsume = toConsume.Slice(consumed);
                    Header    = await Parser.GetProductAsync();

                    Console.WriteLine("Header done.");
                }
            }

            if (Header != null)
            {
                Console.WriteLine($"Read {Encoding.UTF8.GetString(toConsume.Span)}");
            }

            return(-1);
        }
Пример #4
0
        public void ExecuteGetWithoutResults()
        {
            //Arrange
            var baseUrl    = "https://sdk-aws-staging.split.io/api/";
            var httpHeader = new HTTPHeader()
            {
                authorizationApiKey = "0",
                splitSDKMachineIP   = "1.0.0.0",
                splitSDKMachineName = "localhost",
                splitSDKVersion     = "net-0.0.0",
                splitSDKSpecVersion = "1.2",
            };
            var sdkApiClient            = new SplitSdkApiClient(httpHeader, baseUrl, 10000, 10000);
            var apiSplitChangeFetcher   = new ApiSplitChangeFetcher(sdkApiClient);
            var sdkSegmentApiClient     = new SegmentSdkApiClient(httpHeader, baseUrl, 10000, 10000);
            var apiSegmentChangeFetcher = new ApiSegmentChangeFetcher(sdkSegmentApiClient);
            var gates = new InMemoryReadinessGatesCache();

            var segmentCache = new InMemorySegmentCache(new ConcurrentDictionary <string, Segment>());

            var selfRefreshingSegmentFetcher = new SelfRefreshingSegmentFetcher(apiSegmentChangeFetcher, gates, 30, segmentCache, 4);
            var splitParser = new InMemorySplitParser(selfRefreshingSegmentFetcher, segmentCache);
            var splitCache  = new InMemorySplitCache(new ConcurrentDictionary <string, ParsedSplit>());
            var selfRefreshingSplitFetcher = new SelfRefreshingSplitFetcher(apiSplitChangeFetcher, splitParser, gates, 30, splitCache);

            selfRefreshingSplitFetcher.Start();

            //Act
            gates.IsSDKReady(10);

            var result = splitCache.GetSplit("condition_and");

            //Assert
            Assert.IsNull(result);
        }
Пример #5
0
        public void ExecuteGetSuccessfulWithResults()
        {
            //Arrange
            var baseUrl    = "https://sdk-aws-staging.split.io/api/";
            var httpHeader = new HTTPHeader()
            {
                authorizationApiKey = "///PUT API KEY HERE///",
                splitSDKMachineIP   = "1.0.0.0",
                splitSDKMachineName = "localhost",
                splitSDKVersion     = "net-0.0.0",
                splitSDKSpecVersion = "1.2",
            };
            var sdkApiClient            = new SegmentSdkApiClient(httpHeader, baseUrl, 10000, 10000);
            var apiSegmentChangeFetcher = new ApiSegmentChangeFetcher(sdkApiClient);
            var gates        = new InMemoryReadinessGatesCache();
            var segmentCache = new InMemorySegmentCache(new ConcurrentDictionary <string, Segment>());
            var selfRefreshingSegmentFetcher = new SelfRefreshingSegmentFetcher(apiSegmentChangeFetcher, gates, 30, segmentCache, 4);

            //Act
            var name = "payed";

            selfRefreshingSegmentFetcher.InitializeSegment(name);

            while (!gates.AreSegmentsReady(1000))
            {
                Thread.Sleep(10);
            }

            //Assert
            Assert.IsTrue(segmentCache.IsInSegment(name, "abcdz"));
        }
 private static void AddHeadersToMessage(HTTPRequestMsg message,
                                         IDictionary <string, IList <string> > requestHeaders)
 {
     foreach (var kvp in requestHeaders)
     {
         var header = new HTTPHeader();
         header.Values.Add(kvp.Value);
         message.Headers.Add(kvp.Key, header);
     }
 }
Пример #7
0
        public static HTTPHeader ConvertExtToInt(this HTTPHeaderExt obj)
        {
            var convert = new HTTPHeader()
            {
                Name  = obj.Name,
                Value = obj.Value
            };

            return(convert);
        }
Пример #8
0
        public static HTTPHeaderExt ConvertIntToExt(this HTTPHeader obj)
        {
            var convert = new HTTPHeaderExt()
            {
                Name  = obj.Name,
                Value = obj.Value
            };

            return(convert);
        }
Пример #9
0
 public HandlePackage(
     HTTPHeader requestHeader,
     HTTPHeader responseHeader,
     ContentStream requestContent,
     ContentStream contentStream,
     HTTPServer server)
 {
     this.RequestHeader  = requestHeader;
     this.ResponseHeader = responseHeader;
     this.RequestContent = requestContent;
     this.ContentStream  = contentStream;
     this.Server         = server;
 }
Пример #10
0
        private void BuildSdkApiClients()
        {
            var header = new HTTPHeader();

            header.authorizationApiKey = ApiKey;
            header.encoding            = HttpEncoding;
            header.splitSDKVersion     = SdkVersion;
            header.splitSDKSpecVersion = SdkSpecVersion;
            header.splitSDKMachineName = SdkMachineName;
            header.splitSDKMachineIP   = SdkMachineIP;
            metricsSdkApiClient        = new MetricsSdkApiClient(header, EventsBaseUrl, HttpConnectionTimeout, HttpReadTimeout);
            BuildMetricsLog();
            splitSdkApiClient     = new SplitSdkApiClient(header, BaseUrl, HttpConnectionTimeout, HttpReadTimeout, metricsLog);
            segmentSdkApiClient   = new SegmentSdkApiClient(header, BaseUrl, HttpConnectionTimeout, HttpReadTimeout, metricsLog);
            treatmentSdkApiClient = new TreatmentSdkApiClient(header, EventsBaseUrl, HttpConnectionTimeout, HttpReadTimeout);
        }
Пример #11
0
            public HTTPHeader RemoveHeader(string key)
            {
                foreach (HTTPHeader current in Headers)
                {
                    if (current.Key == key)
                    {
                        HTTPHeader t = current;

                        Headers.Remove(current);

                        return(t);
                    }
                }

                return(null);
            }
Пример #12
0
        private void BuildSdkApiClients()
        {
            var header = new HTTPHeader
            {
                authorizationApiKey = ApiKey,
                splitSDKVersion     = _config.SdkVersion,
                splitSDKSpecVersion = _config.SdkSpecVersion,
                splitSDKMachineName = _config.SdkMachineName,
                splitSDKMachineIP   = _config.SdkMachineIP
            };

            _metricsSdkApiClient = new MetricsSdkApiClient(header, _config.EventsBaseUrl, _config.HttpConnectionTimeout, _config.HttpReadTimeout);
            BuildMetricsLog();
            _splitSdkApiClient     = new SplitSdkApiClient(header, _config.BaseUrl, _config.HttpConnectionTimeout, _config.HttpReadTimeout, _metricsLog);
            _segmentSdkApiClient   = new SegmentSdkApiClient(header, _config.BaseUrl, _config.HttpConnectionTimeout, _config.HttpReadTimeout, _metricsLog);
            _treatmentSdkApiClient = new TreatmentSdkApiClient(header, _config.EventsBaseUrl, _config.HttpConnectionTimeout, _config.HttpReadTimeout);
            _eventSdkApiClient     = new EventSdkApiClient(header, _config.EventsBaseUrl, _config.HttpConnectionTimeout, _config.HttpReadTimeout);
        }
Пример #13
0
        public async Task ExecuteGetShouldReturnEmptyIfNotAuthorized()
        {
            //Arrange
            var baseUrl    = "https://sdk.aws.staging.split.io/api";
            var httpHeader = new HTTPHeader()
            {
                splitSDKMachineIP   = "1.0.0.0",
                splitSDKMachineName = "localhost",
                splitSDKVersion     = "net-0.0.0",
                splitSDKSpecVersion = "1.2"
            };
            var SplitSdkApiClient = new SplitSdkApiClient(httpHeader, baseUrl, 10000, 10000);

            //Act
            var result = await SplitSdkApiClient.FetchSplitChanges(-1);

            //Assert
            Assert.IsTrue(result == string.Empty);
        }
Пример #14
0
        public async void ExecuteGetShouldReturnErrorNotAuthorized()
        {
            //Arrange
            var baseUrl    = "http://demo7064886.mockable.io";
            var httpHeader = new HTTPHeader()
            {
                splitSDKMachineIP   = "1.0.0.0",
                splitSDKMachineName = "localhost",
                splitSDKVersion     = "1",
                splitSDKSpecVersion = "2"
            };
            var SdkApiClient = new SdkApiClient(httpHeader, baseUrl, 10000, 10000);

            //Act
            var result = await SdkApiClient.ExecuteGet("/messages?item=msg2");

            //Assert
            Assert.AreEqual(result.statusCode, HttpStatusCode.Unauthorized);
        }
Пример #15
0
        public async Task ExecuteFetchSplitChangesSuccessful()
        {
            //Arrange
            var baseUrl    = "http://sdk-aws-staging.split.io/api/";
            var httpHeader = new HTTPHeader()
            {
                authorizationApiKey = "///PUT API KEY HERE///",
                splitSDKMachineIP   = "1.0.0.0",
                splitSDKMachineName = "localhost",
                splitSDKVersion     = "net-0.0.0",
                splitSDKSpecVersion = "1.2",
            };
            var SplitSdkApiClient = new SplitSdkApiClient(httpHeader, baseUrl, 10000, 10000);

            //Act
            var result = await SplitSdkApiClient.FetchSplitChanges(-1);

            //Assert
            Assert.IsTrue(result.Contains("splits"));
        }
Пример #16
0
        public async void ExecuteGetShouldReturnNotFoundOnInvalidRequest()
        {
            //Arrange
            var baseUrl    = "http://demo706abcd.mockable.io";
            var httpHeader = new HTTPHeader()
            {
                authorizationApiKey = "ABCD",
                splitSDKMachineIP   = "1.0.0.0",
                splitSDKMachineName = "localhost",
                splitSDKVersion     = "1",
                splitSDKSpecVersion = "2"
            };
            var SdkApiClient = new SdkApiClient(httpHeader, baseUrl, 10000, 10000);

            //Act
            var result = await SdkApiClient.ExecuteGet("/messages?item=msg2");

            //Assert
            Assert.AreEqual(result.statusCode, HttpStatusCode.NotFound);
        }
Пример #17
0
        public async void ExecuteGetSuccessful()
        {
            //Arrange
            var baseUrl    = "http://demo7064886.mockable.io";
            var httpHeader = new HTTPHeader()
            {
                authorizationApiKey = "ABCD",
                splitSDKMachineIP   = "1.0.0.0",
                splitSDKMachineName = "localhost",
                splitSDKVersion     = "1",
                splitSDKSpecVersion = "2"
            };
            var SdkApiClient = new SdkApiClient(httpHeader, baseUrl, 10000, 10000);

            //Act
            var result = await SdkApiClient.ExecuteGet("/messages?item=msg1");

            //Assert
            Assert.AreEqual(result.statusCode, HttpStatusCode.OK);
            Assert.IsTrue(result.content.Contains("Hello World"));
        }
Пример #18
0
        public async Task ExecuteGetShouldReturnEmptyResponseOnInvalidURL()
        {
            //Arrange
            var baseUrl    = "http://demo70e.iio";
            var httpHeader = new HTTPHeader()
            {
                authorizationApiKey = "ABCD",
                splitSDKMachineIP   = "1.0.0.0",
                splitSDKMachineName = "localhost",
                splitSDKVersion     = "1",
                splitSDKSpecVersion = "2"
            };
            var SdkApiClient = new SdkApiClient(httpHeader, baseUrl, 10000, 10000);

            //Act
            var result = await SdkApiClient.ExecuteGet("/messages?item=msg2");

            //Assert
            Assert.IsNotNull(result);
            Assert.IsNull(result.content);
        }
Пример #19
0
        public void ExecuteGetSuccessfulWithResults()
        {
            //Arrange
            var baseUrl = "https://sdk-aws-staging.split.io/api/";
            //var baseUrl = "http://localhost:3000/api/";
            var httpHeader = new HTTPHeader()
            {
                authorizationApiKey = "///PUT API KEY HERE///",
                splitSDKMachineIP   = "1.0.0.0",
                splitSDKMachineName = "localhost",
                splitSDKVersion     = "net-0.0.0",
                splitSDKSpecVersion = "1.2",
                encoding            = "gzip"
            };
            var sdkApiClient            = new SplitSdkApiClient(httpHeader, baseUrl, 10000, 10000);
            var apiSplitChangeFetcher   = new ApiSplitChangeFetcher(sdkApiClient);
            var sdkSegmentApiClient     = new SegmentSdkApiClient(httpHeader, baseUrl, 10000, 10000);
            var apiSegmentChangeFetcher = new ApiSegmentChangeFetcher(sdkSegmentApiClient);
            var gates        = new InMemoryReadinessGatesCache();
            var segmentCache = new InMemorySegmentCache(new ConcurrentDictionary <string, Segment>());
            var selfRefreshingSegmentFetcher = new SelfRefreshingSegmentFetcher(apiSegmentChangeFetcher, gates, 30, segmentCache, 4);

            var splitParser = new InMemorySplitParser(selfRefreshingSegmentFetcher, segmentCache);
            var splitCache  = new InMemorySplitCache(new ConcurrentDictionary <string, ParsedSplit>());
            var selfRefreshingSplitFetcher = new SelfRefreshingSplitFetcher(apiSplitChangeFetcher, splitParser, gates, 30, splitCache);

            selfRefreshingSplitFetcher.Start();

            //Act
            gates.IsSDKReady(1000);
            selfRefreshingSplitFetcher.Stop();
            ParsedSplit result  = (ParsedSplit)splitCache.GetSplit("Pato_Test_1");
            ParsedSplit result2 = (ParsedSplit)splitCache.GetSplit("Manu_Test_1");

            //Assert
            Assert.IsNotNull(result);
            Assert.IsTrue(result.name == "Pato_Test_1");
            Assert.IsTrue(result.conditions.Count > 0);
        }
Пример #20
0
        private void SendRequest()
        {
            // Record when we first started the download
            headerLength = 0;
            startTime    = DateTime.Now;

            // Create a HTTP request using the Deusty.Net.HTTP.HTTPHeader class.
            // The HTTP protocol is fairly straightforward, but this class helps hide protocol
            // specific information that we're not really concerned with for this AsyncSocket sameple.

            HTTPHeader request = HTTPHeader.CreateRequest("GET", FETCH_REQUEST);

            request.SetHeaderFieldValue("Host", FETCH_HOST);

            String requestStr = request.ToString();

            LogInfo("Sending Request:");
            LogMessage(requestStr);

            // Convert HTTPHeader object to a byte array.

            byte[] requestData = Encoding.UTF8.GetBytes(requestStr);
            Console.WriteLine(Data.ToHexString(requestData));

            // Now write the data over the socket.
            // This call is asynchronous, and returns immediately.
            // When finished writing, the asyncSocket_DidWrite method is called.

            asyncSocket.Write(requestData, WRITE_TIMEOUT, HTTP_HEADERS);

            // Setup http response
            response = HTTPHeader.CreateEmptyResponse();

            // And start reading in the response
            asyncSocket.Read(AsyncSocket.CRLFData, READ_HEADER_TIMEOUT, HTTP_HEADERS);

            // Reset progress bar
            progressBar.Value = 0;
        }
    private static void CompleteDownload(LocalStorageFileState state)
    {
        bool flag = true;

        object[] args = new object[] { state };
        s_log.LogDebug("Download completed for State={0}", args);
        HTTPHeader header = ParseHTTPHeader(state.FileData);

        if (header == null)
        {
            object[] objArray2 = new object[] { state };
            s_log.LogWarning("Parsinig of HTTP header failed for State={0}", objArray2);
        }
        else
        {
            byte[] destinationArray = new byte[header.ContentLength];
            Array.Copy(state.FileData, header.ContentStart, destinationArray, 0, header.ContentLength);
            if (ComputeSHA256(destinationArray) != state.CH.Sha256Digest)
            {
                object[] objArray3 = new object[] { state };
                s_log.LogWarning("Integrity check failed for State={0}", objArray3);
            }
            else
            {
                flag = false;
                DecompressStateIfPossible(state, destinationArray);
            }
        }
        if (flag || (state.FileData == null))
        {
            ExecuteFailedDownload(state);
        }
        else
        {
            ExecuteSucessfulDownload(state);
        }
    }
Пример #22
0
 public bool IsCoreRequest(HTTPHeader header)
 {
     return(header.URL.ToLower().StartsWith(this.coreString));
 }
Пример #23
0
 public MetricsSdkApiClient(HTTPHeader header, string baseUrl, long connectionTimeOut, long readTimeout)
     : base(header, baseUrl, connectionTimeOut, readTimeout)
 {
 }
Пример #24
0
        public Boolean GetHeaderAndBody(Stream myStream, out HTTPHeader myHttpHeader, out Byte[] myBody)
        {
            myHttpHeader = null;
            myBody       = null;

            #region Data Definition

            var ReadBuffer = new Byte[16 * 1024];

            Int32 BytesRead = 0;

            // TODO: Use an byte[] and resize it if needed
            var FirstBytesList = new List <Byte>();

            #endregion

            #region Read the FirstBytes until no Data is available or we read more than we can store in a List of Bytes

            do
            {
                BytesRead = myStream.Read(ReadBuffer, 0, ReadBuffer.Length);

                if (BytesRead == ReadBuffer.Length)
                {
                    FirstBytesList.AddRange(ReadBuffer);
                }

                else
                {
                    var _TempBytes = new Byte[BytesRead];
                    Array.Copy(ReadBuffer, 0, _TempBytes, 0, BytesRead);
                    FirstBytesList.AddRange(_TempBytes);
                }
            }
            //DataAvailable is not available for stream this is a problem if the saerver can't send the whole header
            //while (myStream.DataAvailable && BytesRead > 0 && FirstBytesList.Count < (Int32.MaxValue - ReadBuffer.Length));
            while (BytesRead > 0 && FirstBytesList.Count < (Int32.MaxValue - ReadBuffer.Length) && (BytesRead == ReadBuffer.Length));

            #endregion

            #region Find Header

            Int32  CurPos     = 4;
            Byte[] FirstBytes = FirstBytesList.ToArray();

            if (FirstBytes.Length <= CurPos)
            {
                // If header length < 4 we have an invalid header
                myStream.Close();

                return(false);
            }

            while ((CurPos < FirstBytes.Length) && !(FirstBytes[CurPos - 4] == 13 && FirstBytes[CurPos - 3] == 10 && FirstBytesList[CurPos - 2] == 13 && FirstBytesList[CurPos - 1] == 10))
            {
                CurPos++;
            }

            var HeaderBytes = new Byte[CurPos];
            Array.Copy(FirstBytes, 0, HeaderBytes, 0, CurPos);

            var HeaderString = Encoding.UTF8.GetString(HeaderBytes);
            myHttpHeader = new HTTPHeader(HeaderString);

            #endregion

            #region Body

            myBody = new Byte[myHttpHeader.ContentLength];

            if (myHttpHeader.ContentLength > 0)
            {
                if (myHttpHeader.ContentLength < (UInt64)(FirstBytes.Length - CurPos))
                {
                    // contentlength defined in the header is lower than the recieved bytes
                    return(false);
                }

                Array.Copy(FirstBytes, CurPos, myBody, 0, FirstBytes.Length - CurPos);

                // Read the rest of the bytes
                if (myHttpHeader.ContentLength > (UInt64)(FirstBytes.Length - CurPos))
                {
                    var TotalBytesRead = (Int64)FirstBytes.Length - CurPos;

                    while ((UInt64)TotalBytesRead < myHttpHeader.ContentLength)
                    {
                        if (!WaitForStreamDataAvailable())
                        {
                            return(true);
                        }

                        BytesRead = myStream.Read(ReadBuffer, 0, ReadBuffer.Length);
                        Array.Copy(ReadBuffer, 0, myBody, TotalBytesRead, BytesRead);
                        TotalBytesRead += (Int64)BytesRead;
                    }
                }
            }

            #endregion

            return(true);
        }
Пример #25
0
        public static HTTPError Request(HTTPMethod method, string Url, object Addition, HTTPRequest.RequestCallback callback, HTTPCookie cookie = null, HTTPHeader additionHeader = null, string PostData = null)
        {
            HTTPStateObject state   = new HTTPStateObject();
            HTTPRequest     request = new HTTPRequest()
            {
                method = method
            };
            Uri path = new Uri(Url);

            request.Cookie   = cookie?.GetCookie(path.Host);
            request.Header   = additionHeader;
            request.Callback = callback;
            request.Addition = Addition;
            request.SetUrl(path.Scheme, path.PathAndQuery, path.Host);
            request.PostData = PostData;
            return(Request(request));
        }
Пример #26
0
            public void AddHeader(HTTPHeader header)
            {

                Headers.Add(header);

            }
Пример #27
0
        public HTTPRequest MakeRequest(HTTPMethod?method, string Url, object Addition, HTTPRequest.RequestCallback callback, HTTPCookie cookie = null, HTTPHeader additionHeader = null, string PostData = null)
        {
            Uri path = new Uri(Url);

            if (path.Host != request.Host)
            {
                HTTPOp.Request(method.Value, Url, Addition, callback, cookie, additionHeader, PostData);
                return(null);
            }
            else
            {
                HTTPRequest newRequest = request.CopyTo();
                newRequest.method   = method == null ? newRequest.method : method.Value;
                newRequest.Url      = path.PathAndQuery;
                newRequest.Addition = Addition ?? newRequest.Addition;
                newRequest.Callback = callback ?? newRequest.Callback;
                //newRequest.Cookie = cookie ?? newRequest.Cookie ;
                newRequest.Cookie   = this.cookie?.AddCookie(cookie).GetCookie(path.Host);
                newRequest.PostData = PostData;
                //newRequest.Header = header ?? newRequest.Header ;
                return(newRequest);
            }
        }