Ejemplo n.º 1
0
        public void DisableGuestAccess()
        {
            var url     = _adminRemoteUri.AppendPath("_user/GUEST");
            var request = new HttpRequestMessage(HttpMethod.Put, url);
            var data    = Manager.GetObjectMapper().WriteValueAsBytes(new Dictionary <string, object> {
                { "disabled", true }
            }).ToArray();

            request.Content = new ByteArrayContent(data);
            _httpClient.SendAsync(request).Wait();
        }
Ejemplo n.º 2
0
        public void VerifyDocumentExists(string docId)
        {
            var pathToDoc = _remoteUri.AppendPath(docId);

            Log.D(Tag, "Send http request to " + pathToDoc);

            var httpRequestDoneSignal = new CountdownEvent(1);

            Task.Factory.StartNew(() =>
            {
                HttpResponseMessage response;
                string responseString = null;
                try
                {
                    var responseTask = _httpClient.GetAsync(pathToDoc.ToString());
                    response         = responseTask.Result;
                    var statusLine   = response.StatusCode;
                    Assert.IsTrue(statusLine == HttpStatusCode.OK);
                    if (statusLine == HttpStatusCode.OK)
                    {
                        var responseStringTask = response.Content.ReadAsStringAsync();
                        responseStringTask.Wait(TimeSpan.FromSeconds(10));
                        responseString = responseStringTask.Result;
                        Assert.IsTrue(responseString.Contains(docId));
                        Log.D(Tag, "result: " + responseString);
                    }
                    else
                    {
                        var statusReason = response.ReasonPhrase;
                        response.Dispose();
                        throw new IOException(statusReason);
                    }
                }
                catch (ProtocolViolationException e)
                {
                    Assert.IsNull(e, "Got ClientProtocolException: " + e.Message);
                }
                catch (IOException e)
                {
                    Assert.IsNull(e, "Got IOException: " + e.Message);
                }

                httpRequestDoneSignal.Signal();
            });

            var result = httpRequestDoneSignal.Wait(TimeSpan.FromSeconds(30));

            Assert.IsTrue(result, "Could not retrieve the new doc from the sync gateway.");
        }
            public void WhenSegmentsIsEmpty_ThenReturnSameUri()
            {
                var sut = new Uri("http://local");

                var result = sut.AppendPath();

                Assert.That(result, Is.SameAs(sut));
            }
            public void WhenPathHasEndSlash_ThenAppendPath()
            {
                var sut = new Uri("https://example.com:8080/over/there/?name=John#myfrag");

                var result = sut.AppendPath("path/path2");

                Assert.That(result, Is.EqualTo(new Uri("https://example.com:8080/over/there/path/path2/?name=John#myfrag")));
            }
            public void WhenHasPath_ThenAppendPath(string path)
            {
                var sut = new Uri("https://example.com:8080/over/there?name=John#myfrag");

                var result = sut.AppendPath(path);

                Assert.That(result, Is.EqualTo(new Uri($"https://example.com:8080/over/there/{path}?name=John#myfrag")));
            }
            public void WhenPathIsNullOrEmpty_ThenReturnSameUri(string path)
            {
                var sut = new Uri("http://local/myapp");

                var result = sut.AppendPath(path);

                Assert.That(sut, Is.SameAs(result));
            }
            public void WhenHasNoPath_AndStartsWithSlash_ThenAppendPath(string path)
            {
                var sut = new Uri("http://local/");

                var result = sut.AppendPath(path);

                Assert.That(result, Is.EqualTo(new Uri("http://local" + path)));
            }
            public void WhenHasNoPath_ThenAppendPath()
            {
                var sut = new Uri("https://example.com:8080/?name=John#myfrag");

                var result = sut.AppendPath("path1", "path2");

                Assert.That(result, Is.EqualTo(new Uri("https://example.com:8080/path1/path2?name=John#myfrag")));
            }
            public void WhenTwoSegments_ThenAppendPath(string segment1, string segment2)
            {
                var sut = new Uri("https://example.com:8080/over/there?name=John#myfrag");

                var result = sut.AppendPath(segment1, segment2);

                Assert.That(result, Is.EqualTo(new Uri("https://example.com:8080/over/there/path1/path2?name=John#myfrag")));
            }
            public void WhenOneSegment_ThenAppendPath(string segment)
            {
                var sut = new Uri("https://example.com:8080/over/there?name=John#myfrag");

                var result = sut.AppendPath(new[] { segment });

                Assert.That(result, Is.EqualTo(new Uri("https://example.com:8080/over/there/path?name=John#myfrag")));
            }
            public void WhenHasPath_AndStartsWithSlash_ThenAppendPath(string path)
            {
                var sut = new Uri("https://example.com:8080/over/there?name=John#myfrag");

                var result = sut.AppendPath(path);

                var pathNoStartSlash = path.RemoveStartsWith("/");

                Assert.That(result, Is.EqualTo(new Uri($"https://example.com:8080/over/there/{pathNoStartSlash}?name=John#myfrag")));
            }
Ejemplo n.º 12
0
        public WcfChannelProxy(Fiber fiber, Uri serviceUri, string pipeName)
        {
            _fiber     = fiber;
            Serializer = new FastTextSerializer();
            ServiceUri = serviceUri;
            PipeName   = pipeName;

            _address = new EndpointAddress(serviceUri.AppendPath(pipeName));
            _proxy   = System.ServiceModel.ChannelFactory <WcfChannel <WcfMessageEnvelope> > .CreateChannel(new NetNamedPipeBinding(),
                                                                                                            _address);
        }
Ejemplo n.º 13
0
 public void Renew(Uri BaseUri, TimeSpan NewDuration)
 {
     try
     {
         var NewReservation = Utils.InvokeAPI <Reservation>(BaseUri.AppendPath("api/v1/reservations/" + Guid.ToString()), "PUT", NewDuration);
         Copy(NewReservation);
     }
     catch (Exception ex)
     {
         throw new AutomationException(ex, "Failed to renew device reservation.");
     }
 }
Ejemplo n.º 14
0
 public void Delete(Uri BaseUri)
 {
     try
     {
         Utils.InvokeAPI(BaseUri.AppendPath("api/v1/reservations/" + Guid.ToString()), "DELETE");
         Console.WriteLine("Successfully deleted device reservation \"{0}\".", Guid);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Failed to delete device reservation: {0}", ex.Message);
     }
 }
Ejemplo n.º 15
0
        public void VerifyDocumentExists(string docId)
        {
            var pathToDoc = _remoteUri.AppendPath(docId);

            LiteTestCase.WriteDebug("Send http request to " + pathToDoc);

            var httpRequestDoneSignal = new CountdownEvent(1);
            var t = Task.Factory.StartNew(() =>
            {
                HttpResponseMessage response;
                string responseString = null;
                var responseTask      = _httpClient.GetAsync(pathToDoc.ToString());
                response       = responseTask.Result;
                var statusLine = response.StatusCode;
                try {
                    Assert.IsTrue(statusLine == HttpStatusCode.OK);
                    if (statusLine == HttpStatusCode.OK)
                    {
                        var responseStringTask = response.Content.ReadAsStringAsync();
                        responseStringTask.Wait(TimeSpan.FromSeconds(10));
                        responseString = responseStringTask.Result;
                        Assert.IsTrue(responseString.Contains(docId));
                        LiteTestCase.WriteDebug("result: {0}", responseString);
                    }
                    else
                    {
                        var statusReason = response.ReasonPhrase;
                        response.Dispose();
                        throw new IOException(statusReason);
                    }
                } finally {
                    httpRequestDoneSignal.Signal();
                }
            });

            var result = httpRequestDoneSignal.Wait(TimeSpan.FromSeconds(30));

            Assert.IsTrue(result, "Could not retrieve the new doc from the sync gateway.");
            Assert.IsNull(t.Exception);
        }
Ejemplo n.º 16
0
        TResponse makeStatsRequest <TResponse>(string key, Method verb) where TResponse : new()
        {
            var requestUrl = _root.AppendPath("v2").AppendPath("stats").AppendPath(key);
            var request    = new RestRequest(requestUrl, verb);

            var response = _client.Execute <TResponse>(request);

            if (checkForError(response))
            {
                throw constructException(response);
            }

            return(response.Data);
        }
Ejemplo n.º 17
0
        /// <summary>
        ///     Sets up a watch on a keyspace and will call the callback when triggered
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="followUp">callback</param>
        /// <param name="recursive">watch subkeys?</param>
        /// <param name="timeout">How long will we watch?</param>
        /// <param name="waitIndex">Index to wait from</param>
        public void Watch(string key, Action <EtcdResponse> followUp, bool recursive = false, int?timeout = null, int?waitIndex = null)
        {
            var requestUrl = _keysRoot.AppendPath(key);
            var getRequest = new RestRequest(requestUrl, Method.GET);

            getRequest.AddParameter("wait", "true");

            if (recursive)
            {
                getRequest.AddParameter("recursive", "true");
            }

            if (timeout.HasValue)
            {
                getRequest.Timeout = timeout.Value * 1000;
            }

            if (waitIndex.HasValue)
            {
                getRequest.AddParameter("waitIndex", waitIndex);
            }

            _client.ExecuteAsync <EtcdResponse>(getRequest, r => followUp(processRestResponse(r)));
        }
        public async Task <TokenConfigurationModel> GetAsync(Uri authorityUrl, ILoggingContext context, CancellationToken cancellationToken)
        {
            var url    = authorityUrl.AppendPath("api/v1/token/configuration");
            var client = HttpClientContext.Client;
            var result = await client.GetAsync(url, cancellationToken);

            result.EnsureSuccessStatusCode();

            var body = await result.Content.ReadAsStringAsync(cancellationToken);

            var model = await JsonConvert.DeserializeAsync <TokenConfigurationModel>(body, JsonConvert.CammelCaseOptions, cancellationToken);

            Debug.Assert(model != null);
            return(model);
        }
Ejemplo n.º 19
0
        private static string AppendRelativeURLString(Uri remote, string relativePath)
        {
            var uri = remote.AppendPath(relativePath);

            return(uri.AbsoluteUri);
            // the following code is a band-aid for a system problem in the codebase
            // where it is appending "relative paths" that start with a slash, eg:
            //     http://dotcom/db/ + /relpart == http://dotcom/db/relpart
            // which is not compatible with the way the java url concatonation works.
//            var remoteUrlString = remote.AbsolutePath;
//            if (remoteUrlString.EndsWith ("/", StringComparison.Ordinal)
//                && relativePath.StartsWith ("/", StringComparison.Ordinal))
//            {
//                remoteUrlString = remoteUrlString.Substring(0, remoteUrlString.Length - 1);
//            }
//            return remoteUrlString + relativePath;
        }
Ejemplo n.º 20
0
        TResponse makeStatsRequest <TResponse>(string key, Method verb) where TResponse : new()
        {
            var requestUrl = _root.AppendPath("v2").AppendPath("stats").AppendPath(key);
            var request    = new RestRequest(requestUrl, verb);

            //needed due to issue 469 - https://github.com/coreos/etcd/issues/469
            request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

            var response = _client.Execute <TResponse>(request);

            if (checkForError(response))
            {
                throw constructException(response);
            }

            return(response.Data);
        }
Ejemplo n.º 21
0
        public static Reservation Create(Uri BaseUri, string[] DeviceTypes, TimeSpan Duration)
        {
            bool bFirst = true;

            while (true)
            {
                if (!bFirst)
                {
                    TimeSpan RetryTime = TimeSpan.FromMinutes(1);
                    Console.WriteLine("Retrying in {0} seconds ...", RetryTime.TotalSeconds);
                    Thread.Sleep(RetryTime);
                }
                bFirst = false;

                Console.WriteLine("Requesting device reservation...");

                Exception UnknownException;

                try
                {
                    return(Utils.InvokeAPI <Reservation>(BaseUri.AppendPath("api/v1/reservations"), "POST", new CreateReservationData()
                    {
                        DeviceTypes = DeviceTypes,
                        Hostname = Environment.MachineName,
                        Duration = Duration
                    }));
                }
                catch (WebException WebEx)
                {
                    if ((WebEx.Response as HttpWebResponse).StatusCode == HttpStatusCode.Conflict)
                    {
                        Console.WriteLine("No devices currently available.");
                        continue;                         // Retry
                    }

                    UnknownException = WebEx;
                }
                catch (Exception Ex)
                {
                    UnknownException = Ex;
                }

                Console.WriteLine("Warning: Device reservation unsuccessful: {0}", UnknownException.Message);
            }
        }
Ejemplo n.º 22
0
        TResponse makeMemberRequest <TResponse>(string key = null, Method method = Method.GET, Action <IRestRequest> action = null) where TResponse : new()
        {
            var requestUrl = _root.AppendPath("v2").AppendPath("members");

            if (!string.IsNullOrEmpty(key))
            {
                requestUrl = requestUrl.AppendPath(key);
            }

            var request = new RestRequest(requestUrl, method);

            request.AddHeader("Accept", "*/*");
            request.AddHeader("Accept-Encoding", "");

            var response = _client.Execute <TResponse>(request);

            return(response.Data);
        }
        static public void ReportDeviceError(string InBaseUri, string DeviceName, string Error)
        {
            if (String.IsNullOrEmpty(InBaseUri) || String.IsNullOrEmpty(DeviceName))
            {
                return;
            }

            try
            {
                Uri BaseUri = new Uri(InBaseUri);
                Utils.InvokeAPI(BaseUri.AppendPath("api/v1/deviceerror/" + DeviceName), "PUT");
                Console.WriteLine("Reported device problem: {0} : {1}", DeviceName, Error);
            }
            catch (Exception Ex)
            {
                Console.WriteLine("Failed to report device: {0} : {1}", DeviceName, Ex.Message);
            }
        }
Ejemplo n.º 24
0
        private static Uri GetRedirectUri(Uri originalUri, HttpResponseMessage response)
        {
            var locationUri = response.Headers.Location;

            if (locationUri == null)
            {
                return(null);
            }

            if (locationUri.IsAbsoluteUri)
            {
                return(locationUri);
            }

            if (locationUri.IsRelativeUriWithAbsolutePath())
            {
                return(new Uri(originalUri, locationUri));
            }

            return(originalUri.AppendPath(locationUri));
        }
Ejemplo n.º 25
0
        TResponse makeMachineRequest <TResponse>(string key = null) where TResponse : new()
        {
            var requestUrl = _root.AppendPath("v2").AppendPath("admin").AppendPath("machines");

            if (!string.IsNullOrEmpty(key))
            {
                requestUrl = requestUrl.AppendPath(key);
            }

            var request = new RestRequest(requestUrl, Method.GET);

            request.AddHeader("Accept", "*/*");
            request.AddHeader("Accept-Encoding", "");

            //needed due to issue 469 - https://github.com/coreos/etcd/issues/469
            request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

            var response = _client.Execute <TResponse>(request);

            return(response.Data);
        }
 public ConfigurationFreeChannelFactory(Uri serviceUri, string pipeName)
     : base(new NetNamedPipeBinding(), new EndpointAddress(serviceUri.AppendPath(pipeName)))
 {
 }
Ejemplo n.º 27
0
        public static Reservation Create(Uri BaseUri, string[] DeviceTypes, TimeSpan Duration, int RetryMax = 5)
        {
            bool     bFirst     = true;
            TimeSpan RetryTime  = TimeSpan.FromMinutes(1);
            int      RetryCount = 0;

            while (true)
            {
                if (!bFirst)
                {
                    Thread.Sleep(RetryTime);
                }

                bFirst = false;

                Console.WriteLine("Requesting device reservation...");

                Exception UnknownException;

                try
                {
                    return(Utils.InvokeAPI <Reservation>(BaseUri.AppendPath("api/v1/reservations"), "POST", new CreateReservationData()
                    {
                        DeviceTypes = DeviceTypes,
                        Hostname = Environment.MachineName,
                        Duration = Duration,
                        ReservationDetails = ReservationDetails
                    }));
                }
                catch (WebException WebEx)
                {
                    Console.WriteLine(String.Format("WebException on reservation request: {0} : {1}", WebEx.Message, WebEx.Status));

                    if (RetryCount == RetryMax)
                    {
                        Console.WriteLine("Device reservation unsuccessful");
                        throw new AutomationException(WebEx, "Device reservation unsuccessful, devices unavailable");
                    }

                    string RetryMessage = String.Format("retry {0} of {1} in {2} minutes", RetryCount + 1, RetryMax, RetryTime.Minutes);
                    string Message      = String.Format("Unknown device server error, {0}", RetryMessage);

                    if (WebEx.Response == null)
                    {
                        Message = String.Format("Devices service currently not available, {0}", RetryMessage);
                    }
                    else if ((WebEx.Response as HttpWebResponse).StatusCode == HttpStatusCode.Conflict)
                    {
                        Message = String.Format("No devices currently available, {0}", RetryMessage);
                    }

                    Console.WriteLine(Message);
                    RetryCount++;
                    UnknownException = WebEx;
                }
                catch (Exception Ex)
                {
                    UnknownException = Ex;

                    string Line = UnknownException.Message;

                    string[] TriggersSrc = { "Warning:", "Error:", "Exception:" };
                    string[] TriggersDst = { "Warn1ng:", "Err0r:", "Except10n:" };

                    for (int Index = 0; Index < TriggersSrc.Length; ++Index)
                    {
                        if (Line.IndexOf(TriggersSrc[Index], StringComparison.OrdinalIgnoreCase) != -1)
                        {
                            Line = Regex.Replace(Line, TriggersSrc[Index], TriggersDst[Index], RegexOptions.IgnoreCase);
                        }
                    }

                    Console.WriteLine("Device reservation unsuccessful: {0}", Line);
                }
            }
        }
Ejemplo n.º 28
0
 public static Device Get(Uri BaseUri, string DeviceName)
 {
     return(Utils.InvokeAPI <Device>(BaseUri.AppendPath("api/v1/devices/" + DeviceName), "GET", null));
 }
Ejemplo n.º 29
0
        private static string AppendRelativeURLString(Uri remote, string relativePath)
        {
            var uri = remote.AppendPath(relativePath);

            return(uri.AbsoluteUri);
        }
        public static Reservation Create(Uri BaseUri, string[] DeviceTypes, TimeSpan Duration, int RetryMax = 5, string PoolID = "")
        {
            bool     bFirst     = true;
            TimeSpan RetryTime  = TimeSpan.FromMinutes(1);
            int      RetryCount = 0;

            while (true)
            {
                if (!bFirst)
                {
                    Thread.Sleep(RetryTime);
                }

                bFirst = false;

                Console.WriteLine("Requesting device reservation...");

                Exception UnknownException;

                try
                {
                    return(Utils.InvokeAPI <Reservation>(BaseUri.AppendPath("api/v1/reservations"), "POST", new CreateReservationData()
                    {
                        DeviceTypes = DeviceTypes,
                        Hostname = Environment.MachineName,
                        Duration = Duration,
                        ReservationDetails = ReservationDetails,
                        PoolID = PoolID
                    }));
                }
                catch (WebException WebEx)
                {
                    Console.WriteLine(String.Format("WebException on reservation request: {0} : {1}", SanitizeErrorMessage(WebEx.Message), WebEx.Status));

                    if (RetryCount == RetryMax)
                    {
                        Console.WriteLine("Device reservation unsuccessful");
                        throw new AutomationException(WebEx, "Device reservation unsuccessful, devices unavailable");
                    }

                    string RetryMessage = String.Format("retry {0} of {1} in {2} minutes", RetryCount + 1, RetryMax, RetryTime.Minutes);
                    string Message      = String.Format("Unknown device server error, {0}", RetryMessage);

                    if (WebEx.Response == null)
                    {
                        Message = String.Format("Devices service currently not available, {0}", RetryMessage);
                    }
                    else if ((WebEx.Response as HttpWebResponse).StatusCode == HttpStatusCode.Conflict)
                    {
                        Message = String.Format("No devices currently available, {0}", RetryMessage);
                    }

                    Console.WriteLine(Message);
                    RetryCount++;
                    UnknownException = WebEx;
                }
                catch (Exception Ex)
                {
                    UnknownException = Ex;
                    Console.WriteLine("Device reservation unsuccessful: {0}", SanitizeErrorMessage(UnknownException.Message));
                }
            }
        }