Ejemplo n.º 1
0
        /// <summary>
        /// Uploads a stream to CloudFoundry via HTTP
        /// </summary>
        /// <param name="uploadUri">Uri to upload to</param>
        /// <param name="zipStream">The compressed stream to upload</param>
        /// <param name="resources">The json payload describing the files of the app</param>
        /// <returns></returns>
        private async Task <HttpResponseMessage> UploadZip(Uri uploadUri, Stream zipStream, string resources)
        {
            string boundary = DateTime.Now.Ticks.ToString("x");

            using (SimpleHttpClient httpClient = new SimpleHttpClient(this.Client.CancellationToken, AppsEndpoint.DefaultUploadTimeout, this.Client.SkipCertificateValidation))
            {
                // http://apidocs.cloudfoundry.org/210/apps/uploads_the_bits_for_an_app.html
                httpClient.HttpProxy = Client.HttpProxy;
                httpClient.SkipCertificateValidation = Client.SkipCertificateValidation;

                httpClient.Headers.Add("Authorization", string.Format("bearer {0}", this.Client.AuthorizationToken));

                httpClient.Uri    = uploadUri;
                httpClient.Method = HttpMethod.Put;

                List <HttpMultipartFormData> mpd = new List <HttpMultipartFormData>();
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resources)))
                {
                    ms.Position = 0;
                    mpd.Add(new HttpMultipartFormData("resources", string.Empty, string.Empty, ms));
                    mpd.Add(new HttpMultipartFormData("application", "application.zip", "application/zip", zipStream));
                    HttpResponseMessage response = await httpClient.SendAsync(mpd);

                    return(response);
                }
            }
        }
Ejemplo n.º 2
0
 public FlatContainerChecker(
     SimpleHttpClient simpleHttpClient,
     string endpoint)
 {
     _simpleHttpClient = simpleHttpClient;
     _endpoint         = endpoint.TrimEnd('/');
 }
Ejemplo n.º 3
0
        public void SetUp()
        {
            unitTestContext = new UnitTestContext();

            mtgStore = new MtgStore(
                testConfig.Url,
                testConfig.Database,
                unitTestContext.QueryStatisticsStoreMock.Object,
                unitTestContext.LoggingServiceMock.Object,
                unitTestContext.SearchUtilityMock.Object);

            unitTestContext.BotServicesMock.SetupGet(b => b.Store)
            .Returns(mtgStore);

            var httpClient = new SimpleHttpClient(unitTestContext.LoggingServiceMock.Object);

            unitTestContext.BotServicesMock.SetupGet(b => b.HttpClient)
            .Returns(httpClient);

            plugin = new CardPricePlugin(
                unitTestContext.BotServicesMock.Object,
                unitTestContext.BotConfig);

            plugin.LoggingService = unitTestContext.LoggingServiceMock.Object;
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Uploads a stream to CloudFoundry via HTTP
        /// </summary>
        /// <param name="uploadUri">Uri to upload to</param>
        /// <param name="zipStream">The compressed stream to upload</param>
        /// <param name="resources">The json payload describing the files of the app</param>
        /// <returns></returns>
        private async Task <SimpleHttpResponse> UploadZip(Uri uploadUri, Stream zipStream, string resources)
        {
            string boundary = DateTime.Now.Ticks.ToString("x");

            using (SimpleHttpClient httpClient = new SimpleHttpClient(this.Client.CancellationToken))
            {
                httpClient.HttpProxy = Client.HttpProxy;
                httpClient.SkipCertificateValidation = Client.SkipCertificateValidation;

                httpClient.Headers.Add("Authorization", string.Format("bearer {0}", this.Client.AuthorizationToken));

                httpClient.Uri    = uploadUri;
                httpClient.Method = HttpMethod.Post;

                List <HttpMultipartFormData> mpd = new List <HttpMultipartFormData>();
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resources)))
                {
                    ms.Position = 0;
                    mpd.Add(new HttpMultipartFormData("resources", string.Empty, string.Empty, ms));
                    mpd.Add(new HttpMultipartFormData("application", "app.zip", "application/zip", zipStream));
                    SimpleHttpResponse response = await httpClient.SendAsync(mpd);

                    return(response);
                }
            }
        }
Ejemplo n.º 5
0
        private void DeletePerson( object sender, RoutedEventArgs e )
        {
            Person person = this.uxPeople.SelectedItem as Person;

            if ( person != null )
            {
                SimpleHttpClient client = new SimpleHttpClient( "http://localhost:1182/people" );

                var query = client.CreateQuery<Person>().Delete( person.ID );

                uxQueryText.Text = query.GetFullyQualifiedQuery( client ).ToString();

                var task = query.ExecuteSingleAsync();
                task.ContinueWith( t =>
                {
                    Execute.OnUIThread( () =>
                    {
                        if ( !t.IsFaulted && t.IsCompleted && t.Result != null )
                        {
                            Debug.WriteLine( "Person: {0}", t.Result );

                            _people.Remove( _people.First( p => p.ID == t.Result.ID ) );
                        }
                    } );
                } );
            }
        }
Ejemplo n.º 6
0
        private void CreatePerson(object sender, RoutedEventArgs e)
        {
            Uri uri = new Uri("http://localhost:1182/people");

            SimpleHttpClient client = new SimpleHttpClient(uri.ToString());

            var person = new Person { ID = 0, Name = personName.Text };

            var query = client.CreateQuery<Person>();
            query.Create(person);

            var task = query.ExecuteSingleAsync();

            task.ContinueWith(t =>
            {
                Execute.OnUIThread(() =>
                {
                    if (!t.IsFaulted && t.IsCompleted && t.Result != null)
                    {
                        Debug.WriteLine("Person: {0}", t.Result);

                        _people.Add(t.Result);
                    }
                });
            });
        }
        internal async Task <SimpleHttpResponse> SendAsync(SimpleHttpClient client, int expectedReturnStatus)
        {
            var result = await client.SendAsync();

            if (((int)result.StatusCode) != expectedReturnStatus)
            {
                // Check if we can deserialize the response
                CloudFoundryException cloudFoundryException;
                try
                {
                    string response = await result.Content.ReadAsStringAsync();

                    var exceptionObject = Utilities.DeserializeJson <CloudFoundryExceptionObject>(response);
                    cloudFoundryException          = new CloudFoundryException(exceptionObject);
                    cloudFoundryException.Response = result;
                    throw cloudFoundryException;
                }
                catch (CloudFoundryException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    throw new CloudFoundryException(string.Format(CultureInfo.InvariantCulture, "An error occurred while talking to the server ({0})", result.StatusCode), ex);
                }
            }

            return(result);
        }
Ejemplo n.º 8
0
        /// <inheritdoc/>
        public async Task <List <RetrieveFileResponse> > RetrieveFile(Guid?app_guid, int?instance_index, string file_path)
        {
            List <RetrieveFileResponse> callResult = new List <RetrieveFileResponse>();

            UriBuilder uriBuilder = new UriBuilder(this.Client.CloudTarget);

            if (string.IsNullOrWhiteSpace(file_path))
            {
                uriBuilder.Path = string.Format(CultureInfo.InvariantCulture, "/v2/apps/{0}/instances/{1}/files", app_guid, instance_index);
            }
            else
            {
                uriBuilder.Path = string.Format(CultureInfo.InvariantCulture, "/v2/apps/{0}/instances/{1}/files/{2}", app_guid, instance_index, file_path);
            }

            using (SimpleHttpClient httpClient = new SimpleHttpClient(this.Client.CancellationToken, new TimeSpan(0, 5, 0), this.Client.SkipCertificateValidation))
            {
                httpClient.SkipCertificateValidation = Client.SkipCertificateValidation;

                var authHeader = await BuildAuthenticationHeader();

                if (!string.IsNullOrWhiteSpace(authHeader.Key))
                {
                    httpClient.Headers.Add(authHeader);
                }

                httpClient.Uri    = uriBuilder.Uri;
                httpClient.Method = HttpMethod.Get;

                var response = await httpClient.SendAsync();

                var responseString = await response.Content.ReadAsStringAsync();

                if (!uriBuilder.Path.EndsWith("/") && !uriBuilder.Path.EndsWith("files"))
                {
                    callResult.Add(new RetrieveFileResponse()
                    {
                        FileContent = responseString
                    });
                }
                else
                {
                    string[] instanceContent = responseString.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
                    foreach (string info in instanceContent)
                    {
                        if (string.IsNullOrWhiteSpace(info) == false)
                        {
                            string[] nameAndSize = info.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                            callResult.Add(new RetrieveFileResponse()
                            {
                                FileName = nameAndSize[0].Trim(), FileSize = nameAndSize[1].Trim()
                            });
                        }
                    }
                }
            }

            return(callResult);
        }
Ejemplo n.º 9
0
        public void GetTimeAsyncTest()
        {
            var client = new SimpleHttpClient();
            var time   = client.GetTimeAsync().Result;

            Console.WriteLine("GetTimeAsync: " + time);

            Assert.True(!string.IsNullOrEmpty(time));
        }
Ejemplo n.º 10
0
        public void GetTimeTest()
        {
            var client = new SimpleHttpClient();
            var time   = client.GetTime();

            Console.WriteLine("GetTime: " + time);

            Assert.True(string.IsNullOrEmpty(time));
        }
Ejemplo n.º 11
0
        public static bool Track(string[] pluginIds)
        {
            var trackRequest = new TrackRequest
            {
                PlayerHash       = PlayerHash,
                EnabledPluginIds = pluginIds
            };

            return(SimpleHttpClient.Post(TrackUri, trackRequest));
        }
Ejemplo n.º 12
0
        // GET: Endpoint
        public ActionResult Process(string endpoint)
        {
            DataBaseConfigure dataBaseConfigure = _db.DB.First(b => b.endpoint == endpoint);
            SimpleHttpClient  simpleHttpClient  = new SimpleHttpClient();

            string        url         = dataBaseConfigure.url;
            string        plainText   = simpleHttpClient.Get(url);
            SlackResponse wrappedText = new SlackResponse(plainText);

            return(Json(wrappedText, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 13
0
        public ContentResult SiteVerify([FromBody] ReCaptchaModel model)
        {
            string reqData = string.Format(
                "secret={0}&response={1}&remoteip={2}",
                secret_key,
                model.ReCaptchaResponse,
                Request.HttpContext.Connection.RemoteIpAddress.ToString()
                );
            string resJson = SimpleHttpClient.PostAsync("https://www.google.com/recaptcha/api/siteverify", reqData, "application/x-www-form-urlencoded").Result;

            return(Content(resJson, "application/json"));
        }
Ejemplo n.º 14
0
        void locator_DeviceStatusUpdate(object sender, DiscoveredEventArgs e)
        {
            SimpleHttpClient client  = new SimpleHttpClient();
            DeviceFactory    factory = new DeviceFactory(client);
            var device = factory.Create(new Uri(e.Device.Location));

            if (device == null)
            {
                return;
            }
            devicesList.Add(device);
            foundDevices.Enqueue(device);
        }
Ejemplo n.º 15
0
        protected override void Init(IDictionary <string, string> arguments, CancellationToken cancellationToken)
        {
            ServicePointManager.DefaultConnectionLimit = DegreeOfParallelism;

            var verbose              = arguments.GetOrDefault(Arguments.Verbose, false);
            var packageStorageBase   = arguments.GetOrThrow <string>(Arguments.ContentBaseAddress);
            var failCacheTime        = arguments.GetOrDefault(FailCacheTime, TimeSpan.FromHours(1));
            var auxStorageFactory    = CreateAuxStorageFactory(arguments, verbose);
            var targetStorageFactory = CreateTargetStorageFactory(arguments, verbose);
            var packageStorage       = new AzureStorage(
                storageBaseUri: new Uri(packageStorageBase),
                maxExecutionTime: TimeSpan.FromMinutes(15),
                serverTimeout: TimeSpan.FromMinutes(10),
                useServerSideCopy: true,
                compressContent: false,
                verbose: true,
                throttle: null);
            var source               = arguments.GetOrThrow <string>(Arguments.Source);
            var iconProcessor        = new IconProcessor(TelemetryService, LoggerFactory.CreateLogger <IconProcessor>());
            var httpHandlerFactory   = CommandHelpers.GetHttpMessageHandlerFactory(TelemetryService, verbose);
            var httpMessageHandler   = httpHandlerFactory();
            var httpClient           = new HttpClient(httpMessageHandler);
            var simpleHttpClient     = new SimpleHttpClient(httpClient, LoggerFactory.CreateLogger <SimpleHttpClient>());
            var catalogClient        = new CatalogClient(simpleHttpClient, LoggerFactory.CreateLogger <CatalogClient>());
            var httpResponseProvider = new HttpClientWrapper(httpClient);
            var externalIconProvider = new ExternalIconContentProvider(httpResponseProvider, LoggerFactory.CreateLogger <ExternalIconContentProvider>());
            var iconCopyResultCache  = new IconCopyResultCache(auxStorageFactory.Create(), failCacheTime, LoggerFactory.CreateLogger <IconCopyResultCache>());

            var leafProcessor = new CatalogLeafDataProcessor(
                packageStorage,
                iconProcessor,
                externalIconProvider,
                iconCopyResultCache,
                TelemetryService,
                LoggerFactory.CreateLogger <CatalogLeafDataProcessor>());

            _collector = new IconsCollector(
                new Uri(source),
                TelemetryService,
                targetStorageFactory,
                catalogClient,
                leafProcessor,
                iconCopyResultCache,
                auxStorageFactory,
                CommandHelpers.GetHttpMessageHandlerFactory(TelemetryService, verbose),
                LoggerFactory.CreateLogger <IconsCollector>());
            var cursorStorage = auxStorageFactory.Create();

            _front = new DurableCursor(cursorStorage.ResolveUri("c2icursor.json"), cursorStorage, DateTime.MinValue.ToUniversalTime());
        }
Ejemplo n.º 16
0
        internal SimpleHttpClient GetHttpClient()
        {
            var httpClient = new SimpleHttpClient(this.Client.CancellationToken);

            try
            {
                httpClient.HttpProxy = this.Client.HttpProxy;
                httpClient.SkipCertificateValidation = this.Client.SkipCertificateValidation;
            }
            catch
            {
                httpClient.Dispose();
                throw;
            }

            return(httpClient);
        }
Ejemplo n.º 17
0
        internal async Task <HttpResponseMessage> SendAsync(SimpleHttpClient client, int[] expectedReturnStatus)
        {
            var result = await client.SendAsync();

            bool success = false;

            foreach (int code in expectedReturnStatus)
            {
                if (((int)result.StatusCode) == code)
                {
                    success = true;
                    break;
                }
            }

            if (!success && !this.Client.UseStrictStatusCodeChecking)
            {
                success = IsSuccessStatusCode(result.StatusCode);
            }

            if (!success)
            {
                // Check if we can deserialize the response
                CloudFoundryException cloudFoundryException;
                try
                {
                    string response = await result.Content.ReadAsStringAsync();

                    var exceptionObject = Utilities.DeserializeJson <CloudFoundryExceptionObject>(response);
                    cloudFoundryException          = new CloudFoundryException(exceptionObject);
                    cloudFoundryException.Response = result;
                    throw cloudFoundryException;
                }
                catch (CloudFoundryException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    throw new CloudFoundryException(string.Format(CultureInfo.InvariantCulture, "An error occurred while talking to the server ({0})", result.StatusCode), ex);
                }
            }

            return(result);
        }
Ejemplo n.º 18
0
        public static bool Consent(bool consent)
        {
            if (consent)
            {
                LogFile.WriteLine($"Registering player consent on the statistics server");
            }
            else
            {
                LogFile.WriteLine($"Withdrawing player consent, removing user data from the statistics server");
            }

            var consentRequest = new ConsentRequest()
            {
                PlayerHash = PlayerHash,
                Consent    = consent
            };

            return(SimpleHttpClient.Post(ConsentUri, consentRequest));
        }
Ejemplo n.º 19
0
        // This function may be called from another thread.
        public static PluginStats DownloadStats()
        {
            if (!PlayerConsent.ConsentGiven)
            {
                MyLog.Default.WriteLine("Downloading plugin statistics anonymously...");
                votingToken = null;
                return(SimpleHttpClient.Get <PluginStats>(StatsUri));
            }

            MyLog.Default.WriteLine("Downloading plugin statistics, ratings and votes for " + PlayerHash);

            var parameters = new Dictionary <string, string> {
                ["playerHash"] = PlayerHash
            };
            var pluginStats = SimpleHttpClient.Get <PluginStats>(StatsUri, parameters);

            votingToken = pluginStats?.VotingToken;

            return(pluginStats);
        }
Ejemplo n.º 20
0
        public static PluginStat Vote(string pluginId, int vote)
        {
            if (votingToken == null)
            {
                LogFile.WriteLine($"Voting token is not available, cannot vote");
                return(null);
            }

            LogFile.WriteLine($"Voting {vote} on plugin {pluginId}");
            var voteRequest = new VoteRequest
            {
                PlayerHash  = PlayerHash,
                PluginId    = pluginId,
                VotingToken = votingToken,
                Vote        = vote
            };

            var stat = SimpleHttpClient.Post <PluginStat, VoteRequest>(VoteUri, voteRequest);

            return(stat);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Uploads a stream to CloudFoundry via HTTP
        /// </summary>
        /// <param name="uploadUri">Uri to upload to</param>
        /// <param name="zipStream">The compressed stream to upload</param>
        /// <returns></returns>
        private async Task <HttpResponseMessage> UploadZip(Uri uploadUri, Stream zipStream)
        {
            string boundary = DateTime.Now.Ticks.ToString("x");

            using (SimpleHttpClient httpClient = new SimpleHttpClient(this.Client.CancellationToken, PackagesExperimentalEndpoint.DefaultUploadTimeout, this.Client.SkipCertificateValidation))
            {
                // http://apidocs.cloudfoundry.org/212/packages_(experimental)/upload_bits_for_a_package_of_type_bits.html
                httpClient.HttpProxy = Client.HttpProxy;
                httpClient.SkipCertificateValidation = Client.SkipCertificateValidation;

                httpClient.Headers.Add("Authorization", string.Format("bearer {0}", this.Client.AuthorizationToken));

                httpClient.Uri    = uploadUri;
                httpClient.Method = HttpMethod.Post;

                List <HttpMultipartFormData> mpd = new List <HttpMultipartFormData>();
                mpd.Add(new HttpMultipartFormData("bits", "application.zip", "application/zip", zipStream));
                HttpResponseMessage response = await httpClient.SendAsync(mpd);

                return(response);
            }
        }
Ejemplo n.º 22
0
        internal SimpleHttpClient GetHttpClient(bool authenticate = true)
        {
            var httpClient = new SimpleHttpClient(this.Client.CancellationToken, this.Client.RequestTimeout, this.Client.SkipCertificateValidation);

            try
            {
                httpClient.HttpProxy = this.Client.HttpProxy;
                httpClient.SkipCertificateValidation = this.Client.SkipCertificateValidation;

                if (authenticate)
                {
                    httpClient.AddAuthentication(this.Client.AuthorizationToken);
                }
            }
            catch
            {
                httpClient.Dispose();
                throw;
            }

            return(httpClient);
        }
Ejemplo n.º 23
0
        static async Task MainAsync()
        {
            ServicePointManager.DefaultConnectionLimit = 64;

            var idPattern      = "Jver.TestPackage.IngestionTime4";
            var versionPattern = "0.0.1-v{0}";
            var testDuration   = TimeSpan.FromMinutes(60);
            var packageCount   = 240;
            var outputFile     = $"results-{DateTimeOffset.UtcNow:yyyyMMddHHmmssFFFFFFF}.csv";

            var pushEndpoint     = "https://dev.nugettest.org/api/v2/package";
            var apiKey           = "";
            var galleryEndpoints = new[]
            {
                "https://dev.nugettest.org",
            };
            var flatContainerEndpoints = new[]
            {
                "https://apidev.nugettest.org/v3-flatcontainer",
                "https://nugetgallerydev.blob.core.chinacloudapi.cn/v3-flatcontainer"
            };
            var registrationEndpoints = new[]
            {
                "https://apidev.nugettest.org/v3/registration3",
                "https://apidev.nugettest.org/v3/registration3-gz",
                "https://apidev.nugettest.org/v3/registration3-gz-semver2",
                "https://nugetgallerydev.blob.core.chinacloudapi.cn/v3-registration3",
                "https://nugetgallerydev.blob.core.chinacloudapi.cn/v3-registration3-gz",
                "https://nugetgallerydev.blob.core.chinacloudapi.cn/v3-registration3-gz-semver2",
            };
            var searchEndpoints = new[]
            {
                "https://nuget-dev-usnc-v2v3search.nugettest.org/query",
                "https://nuget-dev-ussc-v2v3search.nugettest.org/query",
                "https://nuget-dev-eastasia-search.nugettest.org/query",
                "https://nuget-dev-southeastasia-search.nugettest.org/query",
            };
            var expandableSearchEndpoints = new string[0];

            //var pushEndpoint = "https://int.nugettest.org/api/v2/package";
            //var apiKey = "";
            //var galleryEndpoints = new[]
            //{
            //    "https://int.nugettest.org",
            //};
            //var flatContainerEndpoints = new[]
            //{
            //    "https://apiint.nugettest.org/v3-flatcontainer",
            //};
            //var registrationEndpoints = new[]
            //{
            //    "https://apiint.nugettest.org/v3/registration3",
            //    "https://apiint.nugettest.org/v3/registration3-gz",
            //    "https://apiint.nugettest.org/v3/registration3-gz-semver2",
            //};
            //var searchEndpoints = new[]
            //{
            //    "http://localhost:21751/query",
            //};
            //var expandableSearchEndpoints = new[]
            //{
            //    "https://nuget-usnc-v2v3search.int.nugettest.org/query",
            //    "https://nuget-ussc-v2v3search.int.nugettest.org/query",
            //};

            var loggerFactory     = new LoggerFactory().AddConsole();
            var httpClientHandler = new HttpClientHandler {
                AutomaticDecompression = DecompressionMethods.GZip
            };
            var httpClient         = new HttpClient(httpClientHandler);
            var simpleHttpClient   = new SimpleHttpClient(httpClient, loggerFactory.CreateLogger <SimpleHttpClient>());
            var registrationClient = new RegistrationClient(simpleHttpClient);
            var portTester         = new PortTester();
            var portDiscovery      = new SimplePortDiscoverer(portTester);
            var portExpander       = new PortExpander(portDiscovery);
            var packagePusher      = new PackagePusher(httpClient, pushEndpoint);
            var packageChecker     = new PackageChecker(loggerFactory.CreateLogger <PackageChecker>());
            var tester             = new Tester(packageChecker, loggerFactory.CreateLogger <Tester>());

            var endpointCheckers = new List <IEndpointChecker>();

            endpointCheckers.AddRange(galleryEndpoints
                                      .Select(endpoint => new GalleryChecker(httpClient, endpoint))
                                      .ToList());

            endpointCheckers.AddRange(flatContainerEndpoints
                                      .Select(endpoint => new FlatContainerChecker(simpleHttpClient, endpoint))
                                      .ToList());

            endpointCheckers.AddRange(registrationEndpoints
                                      .Select(endpoint => new RegistrationChecker(registrationClient, endpoint))
                                      .ToList());

            endpointCheckers.AddRange(searchEndpoints
                                      .Select(endpoint => new SearchChecker(simpleHttpClient, endpoint))
                                      .ToList());

            endpointCheckers.AddRange(expandableSearchEndpoints
                                      .Select(endpoint => new SearchChecker(simpleHttpClient, endpoint, portExpander))
                                      .ToList());

            var writeLock = new object();

            AppendLine(writeLock, outputFile, GetCsvHeader(endpointCheckers));

            var testParameters = new TestParameters
            {
                PackagePusher    = packagePusher,
                ApiKey           = apiKey,
                IdPattern        = idPattern,
                VersionPattern   = versionPattern,
                EndpointCheckers = endpointCheckers,
                TestDuration     = testDuration,
                PackageCount     = packageCount,
                OnPackageResult  = x => AppendResult(writeLock, outputFile, x),
            };

            var results = await tester.ExecuteAsync(testParameters);

            Console.WriteLine(GetCsvHeader(endpointCheckers));
            foreach (var result in results)
            {
                Console.WriteLine(GetCsvLine(result));
            }
        }
        public void TestInitialize()
        {
            Logger = MockRepository.GenerateMock<ILogger>();
            Client = MockRepository.GeneratePartialMock<SimpleHttpClient>("AnAPIKey", Logger);
            Request = MockRepository.GenerateMock<WebRequestWrapper>();
            Response = MockRepository.GenerateMock<WebResponseWrapper>();

            ReqStream = new MemoryStream();
            RespStream = new MemoryStream();
        }
Ejemplo n.º 25
0
        private void GetAllPeople(object sender, RoutedEventArgs e)
        {
            _people.Clear();

            SimpleHttpClient client = new SimpleHttpClient("http://localhost:1182/people");

            IHttpQueryProvider queryProvider = new HttpQueryProvider(client);

            var query = new HttpQuery<Person>(queryProvider);
            // query.ToString() == http://localhost:1182/people

            //var query = new HttpQuery<Person>(new HttpQueryProvider(new SimpleHttpClient("http://localhost:1182")), /* resource name*/ "people");
            //// query.ToString() == http://localhost:1182/people

            //var query = new HttpQuery<Person>(queryProvider).Skip(5).Take(10);
            //// query.ToString() == http://localhost:1182/people?$skip=5$top=10

            //int id = 1;
            //var query = new HttpQuery<Person>(queryProvider).Where(c => c.ID, id);
            //// query.ToString() == http://localhost:1182/people?$filter=ID eq 1

            //var query = new HttpQuery<Person>(null, /* resource name*/ "people");
            //// query.ToString() == people

            //var query = new HttpQuery<Person>(null, /* resource name*/ "people").Take(10);
            //// query.ToString() == people?$top=10

            uxQueryText.Text = query.GetFullyQualifiedQuery(client).ToString();

            HandleQuery(query);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Pushes an application to the cloud.
        /// <remarks>
        /// </remarks>
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        /// <param name="appGuid">Application guid</param>
        /// <param name="appPath">Path of origin from which the application will be deployed</param>
        /// <param name="stack">The name of the stack the app will be running on</param>
        /// <param name="buildpackGitUrl">Git URL of the buildpack</param>
        /// <param name="startApplication">True if the app should be started after upload is complete, false otherwise</param>
        /// <param name="diskLimit">Memory limit used to stage package</param>
        /// <param name="memoryLimit">Disk limit used to stage package</param>
        public async Task Push(Guid appGuid, string appPath, string stack, string buildpackGitUrl, bool startApplication, int memoryLimit, int diskLimit)
        {
            if (appPath == null)
            {
                throw new ArgumentNullException("appPath");
            }

            IAppPushTools pushTools = new AppPushTools(appPath);
            int           usedSteps = 1;

            // Step 1 - Check if application exists
            this.TriggerPushProgressEvent(usedSteps, "Checking if application exists");
            var app = await this.Client.AppsExperimental.GetApp(appGuid);

            usedSteps += 1;

            // Step 2 - Create package
            var createPackage   = new Model.Package(appGuid);
            var packageResponse = await this.Client.PackagesExperimental.CreatePackage(createPackage);

            Guid packageId = new Guid(packageResponse.guid.ToString());

            if (this.CheckCancellation())
            {
                return;
            }

            usedSteps += 1;

            // Step 3 - Zip all needed files and get a stream back from the PushTools
            this.TriggerPushProgressEvent(usedSteps, "Creating zip package ...");
            using (Stream zippedPayload = pushTools.GetZippedPayload(this.Client.CancellationToken))
            {
                if (this.CheckCancellation())
                {
                    return;
                }

                usedSteps += 1;

                // Step 4 - Upload zip to CloudFoundry ...
                this.TriggerPushProgressEvent(usedSteps, "Uploading zip package ...");
                await this.Client.PackagesExperimental.UploadBits(packageId, zippedPayload);


                bool uploadProcessed = false;
                while (!uploadProcessed)
                {
                    var getPackage = await this.Client.PackagesExperimental.GetPackage(packageId);

                    Console.WriteLine(getPackage.state);

                    switch (getPackage.state)
                    {
                    case "FAILED":
                    {
                        throw new Exception(string.Format(CultureInfo.InvariantCulture, "Upload failed: {0}", getPackage.data["error"]));
                    }

                    case "READY":
                    {
                        uploadProcessed = true;
                        break;
                    }

                    default: continue;
                    }

                    if (this.CheckCancellation())
                    {
                        return;
                    }

                    Task.Delay(500).Wait();
                }

                usedSteps += 1;
            }

            var buildResponse = await this.Client.Builds.CreateBuild(packageId);

            if (this.CheckCancellation())
            {
                return;
            }

            usedSteps += 1;
            Guid dropLetGuid;

            if (startApplication)
            {
                bool staged = false;
                while (!staged)
                {
                    var getBuild = await this.Client.Builds.GetBuild(buildResponse.guid.Value);

                    Console.WriteLine(getBuild.state);
                    switch (getBuild.state)
                    {
                    case "FAILED":
                    {
                        throw new Exception(string.Format(CultureInfo.InvariantCulture, "Staging failed: {0}", getBuild.error));
                    }

                    case "STAGED":
                    {
                        staged      = true;
                        dropLetGuid = getBuild.droplet.guid.Value;
                        break;
                    }

                    default: continue;
                    }

                    if (this.CheckCancellation())
                    {
                        return;
                    }

                    Task.Delay(500).Wait();
                }

                //check droplets..
                using (SimpleHttpClient httpClient = new SimpleHttpClient(this.Client.CancellationToken, new TimeSpan(0, 30, 0), true))
                {
                    httpClient.SkipCertificateValidation = true;

                    httpClient.Headers.Add("Authorization", string.Format("bearer {0}", this.Client.AuthorizationToken));

                    httpClient.Uri    = new Uri($"https://api.system.cf.singel.home/v3/apps/{appGuid}/droplets");
                    httpClient.Method = HttpMethod.Get;

                    //var fap = new { package = new { guid = packageId } };

                    HttpResponseMessage dropResponse = await httpClient.SendAsync();

                    var beun = dropResponse.Content.ReadAsStringAsync().Result;
                }


                // Step 6 - Assign droplet
                //var assignRequest = new AssignDropletAsAppsCurrentDropletRequest(dropLetGuid);
                var assignDroplet = await this.AssignDropletAsAppsCurrentDroplet(appGuid, dropLetGuid);

                if (this.CheckCancellation())
                {
                    return;
                }

                usedSteps += 1;

                //create route
                var routeRequest = new CreateRouteRequest();
                routeRequest.Host       = "test-route";
                routeRequest.SpaceGuid  = new Guid("ef1c944d-c7ec-4ceb-8177-317130a005da");
                routeRequest.DomainGuid = new Guid("ff8129d7-6304-49da-8345-9c7317ac9d02");
                var routeResponse = await this.Client.V2.Routes.CreateRoute(routeRequest);


                //map route
                // var mapRouteRequest = new MapRouteRequest();
                // mapRouteRequest.RouteGuid = routeResponse.EntityMetadata.Guid;
                await this.Client.V2.Routes.AssociateAppWithRoute(routeResponse.EntityMetadata.Guid, appGuid);


                // Step 7 - Start Application
                var response = await this.Client.AppsExperimental.StartingApp(appGuid);

                if (this.CheckCancellation())
                {
                    return;
                }

                usedSteps += 1;
            }

            // Step 8 - Done
            this.TriggerPushProgressEvent(usedSteps, "Application {0} pushed successfully", app.name);
        }
Ejemplo n.º 27
0
        static async Task MainAsync()
        {
            const string connectionString     = "DefaultEndpointsProtocol=https;AccountName=mystorageaccount;AccountKey=***";
            const string cursorValue          = "2019-04-29T12:19:24.1091293";
            const string newBaseContainerName = "v3-registration4";
            const string newBaseUrl           = "https://mystorageaccount.blob.core.windows.net/" + newBaseContainerName;

            ServicePointManager.DefaultConnectionLimit = 64;

            var loggerFactory     = new LoggerFactory().AddConsole();
            var httpClientHandler = new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
            };
            var httpClient         = new HttpClient(httpClientHandler);
            var simpleHttpClient   = new SimpleHttpClient(httpClient, loggerFactory.CreateLogger <SimpleHttpClient>());
            var registrationClient = new RegistrationClient(simpleHttpClient);
            var copier             = new RegistrationHiveCopier(
                registrationClient,
                simpleHttpClient,
                loggerFactory.CreateLogger <RegistrationHiveCopier>());

            var cloudBlobClient = new CloudBlobClientWrapper(connectionString, readAccessGeoRedundant: false);

            var hives = new[]
            {
                new
                {
                    OldBaseUrl       = "https://api.nuget.org/v3/registration3",
                    NewBaseUrl       = newBaseUrl,
                    NewContainerName = newBaseContainerName,
                    Gzip             = false,
                    Cursor           = true,
                },
                new
                {
                    OldBaseUrl       = "https://api.nuget.org/v3/registration3-gz",
                    NewBaseUrl       = newBaseUrl + "-gz",
                    NewContainerName = newBaseContainerName + "-gz",
                    Gzip             = true,
                    Cursor           = true,
                },
                new
                {
                    OldBaseUrl       = "https://api.nuget.org/v3/registration3-gz-semver2",
                    NewBaseUrl       = newBaseUrl + "-gz-semver2",
                    NewContainerName = newBaseContainerName + "-gz-semver2",
                    Gzip             = true,
                    Cursor           = false,
                },
            };

            var ids = new[]
            {
                "DDPlanet.Logging",
                "IBA.ECL.Services.Shared.Enums",
                "Lith.FlatFile",
                "Momentum.Pm.Api",
                "Momentum.Pm.PortalApi",
                "MSBuild.Obfuscar",
                "Sensus",
                "TIKSN-Framework",
                "Vostok.ServiceDiscovery",
            };

            var hiveTasks = hives
                            .Select(async hive =>
            {
                await Task.Yield();

                var container = cloudBlobClient.GetContainerReference(hive.NewContainerName);
                await container.CreateIfNotExistAsync();

                var idTasks = ids
                              .Select(async id =>
                {
                    await Task.Yield();
                    await copier.CopyAsync(
                        container,
                        hive.OldBaseUrl,
                        hive.NewBaseUrl,
                        id,
                        hive.Gzip);
                })
                              .ToList();
                await Task.WhenAll(idTasks);

                if (hive.Cursor)
                {
                    var cursorBlob = container.GetBlobReference("cursor.json");
                    cursorBlob.Properties.ContentType = "application/json";
                    var cursorJObject      = new JObject();
                    cursorJObject["value"] = cursorValue;
                    var cursorJson         = cursorJObject.ToString(Formatting.Indented);
                    var cursorBytes        = Encoding.UTF8.GetBytes(cursorJson);
                    using (var memoryStream = new MemoryStream(cursorBytes))
                    {
                        await cursorBlob.UploadFromStreamAsync(memoryStream, overwrite: true);
                    }
                }
            })
                            .ToList();
            await Task.WhenAll(hiveTasks);
        }
        /// <summary>
        /// Returns a LogMessage containing recent logs
        /// </summary>
        /// <param name="appGuid">The Cloud Foundry app unique identifier.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <exception cref="System.ArgumentNullException">appGuid</exception>
        /// <returns></returns>
        public async Task <ApplicationLog[]> Recent(string appGuid, CancellationToken cancellationToken)
        {
            if (appGuid == null)
            {
                throw new ArgumentNullException("appGuid");
            }

            UriBuilder appLogUri = new UriBuilder(this.LoggregatorEndpoint);

            if (appLogUri.Scheme == "ws")
            {
                appLogUri.Scheme = "http";
            }
            else
            {
                appLogUri.Scheme = "https";
            }

            appLogUri.Path  = "recent";
            appLogUri.Query = string.Format(CultureInfo.InvariantCulture, "app={0}", appGuid);

            SimpleHttpClient client;

            if (httpClient != null)
            {
                client = httpClient as SimpleHttpClient;
                client.cancellationToken = cancellationToken;
            }
            else
            {
                client = new SimpleHttpClient(cancellationToken);
            }
            client.Uri    = appLogUri.Uri;
            client.Method = HttpMethod.Get;
            client.Headers.Add("AUTHORIZATION", this.AuthenticationToken);
            client.HttpProxy = this.HttpProxy;
            client.SkipCertificateValidation = this.SkipCertificateValidation;

            SimpleHttpResponse response = await client.SendAsync();

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                string errorMessage = await response.ReadContentAsStringAsync();

                throw new LoggregatorException(string.Format(CultureInfo.InvariantCulture, "Server returned error code {0} with message: '{1}'", response.StatusCode, errorMessage));
            }

            MultipartMemoryStreamProvider multipart = null;

            try
            {
                multipart = await response.Content.ReadAsMultipartAsync();
            }
            catch (IOException multipartException)
            {
                // There are no recent Logs. We need to investigate a better way for handling this
                if (multipartException.Message.Contains("MIME multipart message is not complete"))
                {
                    return(new ApplicationLog[] { new ApplicationLog()
                                                  {
                                                      Message = "(Server did not return any recent logs)"
                                                  } });
                }
                else
                {
                    throw;
                }
            }

            List <ApplicationLog> messages = new List <ApplicationLog>();

            foreach (var msg in multipart.Contents)
            {
                messages.Add(this.protobufSerializer.DeserializeApplicationLog(await msg.ReadAsByteArrayAsync()));
            }

            return(messages.ToArray());
        }
Ejemplo n.º 29
0
 internal async Task <HttpResponseMessage> SendAsync(SimpleHttpClient client, int expectedReturnStatus)
 {
     int[] codes = new int[] { expectedReturnStatus };
     return(await this.SendAsync(client, codes));
 }
Ejemplo n.º 30
0
        private void GetTop3People(object sender, RoutedEventArgs e)
        {
            _people.Clear();

            SimpleHttpClient client = new SimpleHttpClient("http://localhost:1182/people");

            var query = client.CreateQuery<Person>().Take(3);

            uxQueryText.Text = query.GetFullyQualifiedQuery(client).ToString();

            HandleQuery(query);
        }
Ejemplo n.º 31
0
 public DiscordApiClient(SimpleHttpClient httpClient, string clientId, string clientSecret)
 {
     _httpClient   = httpClient;
     _clientId     = clientId;
     _clientSecret = clientSecret;
 }
Ejemplo n.º 32
0
        private void GetPersonWithID(object sender, RoutedEventArgs e)
        {
            int id;

            if (Int32.TryParse(this.uxPersonID.Text, out id))
            {
                _people.Clear();

                SimpleHttpClient client = new SimpleHttpClient("http://localhost:1182/people");

                var query = client.CreateQuery<Person>().Where(c => c.ID, id);

                uxQueryText.Text = query.GetFullyQualifiedQuery(client).ToString();

                HandleQuery(query);
            }
        }