Beispiel #1
0
        public async Task CanUpdateCategory()
        {
            var count    = categories.Count;
            var id       = categories[count - 1].Id ?? null;
            var category = new CategoryDto()
            {
                Title = "Updated Title", Description = "Updated Description"
            };

            var response = await client.PutAsync(@$ "/api/categories/{id}", HttpClientUtils.CreateContent(category));

            Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode);

            response = await client.GetAsync(@$ "/api/categories/{id}");

            var updatedCategory = await response.Content.ReadFromJsonAsync <CategoryDto>();

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.AreEqual("Updated Title", updatedCategory.Title);
            Assert.AreEqual("Updated Description", updatedCategory.Description);
        }
        public async Task It_supports_odata_attribute_routing()
        {
            using (WebApp.Start(HttpClientUtils.BaseAddress, appBuilder => Configuration(appBuilder, typeof(AccountsController)))) {
                // Arrange
                var httpClient = HttpClientUtils.GetHttpClient(HttpClientUtils.BaseAddress);

                // Act
                var swaggerDocument = await httpClient.GetJsonAsync <SwaggerDocument>("swagger/docs/v1");

                // Assert
                PathItem pathItem;
                swaggerDocument.paths.TryGetValue("/odata/Accounts({accountId})/PayinPIs({paymentInstrumentId})", out pathItem);
                pathItem.Should().NotBeNull();
                pathItem.get.Should().NotBeNull();
                pathItem.get.produces.Should().NotBeNull();
                pathItem.get.produces.Count.Should().Be(1);
                pathItem.get.produces.First().Should().Be("application/json");

                await ValidationUtils.ValidateSwaggerJson();
            }
        }
Beispiel #3
0
        public R Post <T, R>(string aiRessource, T aiRequestBody)
        {
            R obj = default(R);

            using (MemoryStream ms = new MemoryStream())
            {
                SerializationContainer.JsonSerializer.WriteObject(ms, aiRequestBody);                byte[] requestInJson = ms.ToArray();
                HttpCompletionOption       option   = HttpCompletionOption.ResponseContentRead;
                HttpRequestMessage         request  = AddBasicAuthentication(HttpClientUtils.CreateBlankRequestMessage(HttpMethod.Post, aiRessource).AddContentToRequest(aiRequestBody));
                Task <HttpResponseMessage> response = _httpClient.SendAsync(request, option);
                HttpResponseMessage        message  = response.Result;
                string contentForDebug = message.Content.ReadAsStringAsync().Result;//Save content temporarly for messaging-process.
                message.EnsureSuccessStatusCode();
                if (message.Content != null)
                {
                    var result = message.Content.ReadAsStreamAsync();
                    obj = SerializationContainer.JsonSerializer.ReadObject <R>(result.Result);
                }
            }
            return(obj);
        }
Beispiel #4
0
        private async void IsUpdate(bool isIos, string version, bool expected)
        {
            string content = GetTestJson(JSON_VERSION1);

            var jsonContent = new StringContent(
                content,
                Encoding.UTF8,
                "application/json"
                );
            var client = HttpClientUtils.CreateHttpClient(HttpStatusCode.OK, jsonContent);

            _mockClientService.Setup(x => x.Create()).Returns(client);

            _mockEssentialsService.Setup(x => x.IsIos).Returns(isIos);
            _mockEssentialsService.Setup(x => x.AppVersion).Returns(version);

            ICheckVersionService service = CreateService();

            bool isUpdated = await service.IsUpdateVersionExistAsync();

            Assert.Equal(expected, isUpdated);
        }
Beispiel #5
0
        public async Task GetExposureConfigurationTest_updated_but_not_cache_expired()
        {
            var date = Date;

            string testJson1 = GetTestJson(JSON_EXPOSURE_CONFIGURATION1);

            using (var writer = File.CreateText(CURRENT_EXPOSURE_CONFIGURATION_FILE_PATH))
            {
                await writer.WriteAsync(testJson1);
            }
            ExposureConfiguration result1 = JsonConvert.DeserializeObject <ExposureConfiguration>(testJson1);

            string testJson2   = GetTestJson(JSON_EXPOSURE_CONFIGURATION2);
            var    jsonContent = new StringContent(
                testJson2,
                Encoding.UTF8,
                "application/json"
                );
            var client = HttpClientUtils.CreateHttpClient(HttpStatusCode.OK, jsonContent);

            mockClientService.Setup(x => x.Create()).Returns(client);

            mockLocalPathService.Setup(x => x.ExposureConfigurationDirPath).Returns("./");
            mockLocalPathService.Setup(x => x.CurrentExposureConfigurationPath).Returns(CURRENT_EXPOSURE_CONFIGURATION_FILE_PATH);
            mockServerConfigurationRepository.Setup(x => x.ExposureConfigurationUrl).Returns("https://example.com/exposure_configuration.json");
            mockDateTimeUtility.Setup(x => x.UtcNow).Returns(date);

            mockPreferencesService.Setup(x => x.GetValue(PreferenceKey.ExposureConfigurationDownloadedEpoch, It.IsAny <long>())).Returns(date.ToUnixEpoch());
            mockPreferencesService.Setup(x => x.GetValue(PreferenceKey.IsDiagnosisKeysDataMappingConfigurationUpdated, false)).Returns(false);

            var unitUnderTest = CreateRepository();
            var result2       = await unitUnderTest.GetExposureConfigurationAsync();

            mockPreferencesService.Verify(s => s.SetValue(PreferenceKey.ExposureConfigurationDownloadedEpoch, date.ToUnixEpoch()), Times.Never());
            mockPreferencesService.Verify(s => s.SetValue(PreferenceKey.ExposureConfigurationAppliedEpoch, date.ToUnixEpoch()), Times.Never());
            mockPreferencesService.Verify(s => s.SetValue(PreferenceKey.IsDiagnosisKeysDataMappingConfigurationUpdated, true), Times.Never());

            Assert.Equal(result1, result2);
        }
        public async Task GetExposureRiskConfigurationTest_not_updated()
        {
            string currentConfigurationJson = GetTestJson(JSON_EXPOSURE_RISK_CONFIGURATION1);

            File.WriteAllText(CURRENT_EXPOSURE_RISK_CONFIGURATION_FILE_PATH, currentConfigurationJson);
            V1ExposureRiskCalculationConfiguration currentConfiguration
                = JsonConvert.DeserializeObject <V1ExposureRiskCalculationConfiguration>(currentConfigurationJson);

            string newConfigurationJson = GetTestJson(JSON_EXPOSURE_RISK_CONFIGURATION2);
            V1ExposureRiskCalculationConfiguration newConfiguration
                = JsonConvert.DeserializeObject <V1ExposureRiskCalculationConfiguration>(newConfigurationJson);

            var jsonContent = new StringContent(
                newConfigurationJson,
                Encoding.UTF8,
                "application/json"
                );
            var client = HttpClientUtils.CreateHttpClient(HttpStatusCode.OK, jsonContent);

            mockClientService.Setup(x => x.Create()).Returns(client);

            mockLocalPathService.Setup(x => x.ExposureConfigurationDirPath).Returns("./");
            mockLocalPathService.Setup(x => x.CurrentExposureRiskCalculationConfigurationPath).Returns(CURRENT_EXPOSURE_RISK_CONFIGURATION_FILE_PATH);
            mockServerConfigurationRepository.Setup(x => x.ExposureRiskCalculationConfigurationUrl).Returns("https://example.com/exposure_risk_configuration.json");

            var unitUnderTest = CreateRepository();
            var result        = await unitUnderTest.GetExposureRiskCalculationConfigurationAsync(preferCache : false);

            result = await unitUnderTest.GetExposureRiskCalculationConfigurationAsync(preferCache : false);

            mockServerConfigurationRepository.Verify(s => s.LoadAsync(), Times.Exactly(2));
            mockLoggerService.Verify(x => x.Info("ExposureRiskCalculationConfiguration have not been changed.", It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>()), Times.Once);

            Assert.NotNull(result);

            Assert.NotEqual(result, currentConfiguration);
            Assert.Equal(result, newConfiguration);
        }
Beispiel #7
0
        public async Task GetExposureConfigurationTest_firsttime()
        {
            var date = Date;

            string content     = GetTestJson(JSON_EXPOSURE_CONFIGURATION1);
            var    jsonContent = new StringContent(
                content,
                Encoding.UTF8,
                "application/json"
                );
            var client = HttpClientUtils.CreateHttpClient(HttpStatusCode.OK, jsonContent);

            mockClientService.Setup(x => x.Create()).Returns(client);

            mockLocalPathService.Setup(x => x.ExposureConfigurationDirPath).Returns("./");
            mockLocalPathService.Setup(x => x.CurrentExposureConfigurationPath).Returns(CURRENT_EXPOSURE_CONFIGURATION_FILE_PATH);
            mockServerConfigurationRepository.Setup(x => x.ExposureConfigurationUrl).Returns("https://example.com/exposure_configuration.json");
            mockDateTimeUtility.Setup(x => x.UtcNow).Returns(date);

            var unitUnderTest = CreateRepository();
            var result        = await unitUnderTest.GetExposureConfigurationAsync();

            mockServerConfigurationRepository.Verify(s => s.LoadAsync(), Times.Once());
            mockPreferencesService.Verify(s => s.SetValue(PreferenceKey.ExposureConfigurationDownloadedEpoch, date.ToUnixEpoch()), Times.AtLeastOnce());
            mockPreferencesService.Verify(s => s.SetValue(PreferenceKey.IsDiagnosisKeysDataMappingConfigurationUpdated, true), Times.AtLeastOnce());

            Assert.NotNull(result);

            Assert.NotNull(result.GoogleExposureConfig);
            Assert.NotNull(result.AppleExposureConfigV1);

            // Google ExposureWindow mode
            Assert.NotNull(result.GoogleDailySummariesConfig);
            Assert.NotNull(result.GoogleDiagnosisKeysDataMappingConfig);

            // Apple ENv2
            Assert.NotNull(result.AppleExposureConfigV2);
        }
Beispiel #8
0
        private async Task RefreshToken()
        {
            Logger.LogInformation("Refresh token");

            var res = await _httpClient.PostAsync(TokenAuthUrl,
                                                  HttpClientUtils.BuildFormParams(
                                                      new KeyValuePair <string, string>("grant_type", "refresh_token"),
                                                      new KeyValuePair <string, string>("refresh_token", _spotifyVault.AccessToken.RefreshToken),
                                                      new KeyValuePair <string, string>("client_id", Config.ClientSecret.ClientId),
                                                      new KeyValuePair <string, string>("client_secret", Config.ClientSecret.ClientSecret)));

            var st = await res.Content.ReadAsStringAsync();

            var newToken = st.FromJson <OAuthTokenResult>();

            _spotifyVault.AccessToken.AccessToken = newToken.AccessToken;
            _spotifyVault.AccessToken.ExpireOn    = DateTime.Now.AddSeconds(newToken.ExpiresIn);
            SaveVault(_spotifyVault);

            Logger.LogInformation($"Token refresh expire on: {_spotifyVault.AccessToken.ExpireOn}");

            InitSpotifyClient();
        }
Beispiel #9
0
        public async Task Initialize()
        {
            factory = new CustomWebApplicationFactory <Startup>();
            client  = factory.CreateClient(new WebApplicationFactoryClientOptions
            {
                BaseAddress = new Uri(BaseURL)
            });

            var loginRequest = new Login.Request()
            {
                Email = UserEmail, Password = Password
            };
            var response = await client.PostAsync("/api/auth/login", HttpClientUtils.CreateContent(loginRequest));

            var data = await response.Content.ReadFromJsonAsync <AuthData>();

            clientUser = factory.CreateClient(new WebApplicationFactoryClientOptions
            {
                BaseAddress = new Uri(BaseURL)
            });

            clientUser.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", data.Token);
        }
Beispiel #10
0
        public async Task <ObservableCollection <FamousPerson> > FindAllAsync()
        {
            #region 测试
            using (var httpClient = new HttpClient())
            {
                try
                {
                    var response = await httpClient.GetAsync(FIND_URL);

                    if (response.IsSuccessStatusCode)
                    {
                        var result = await response.Content.ReadAsAsync <ObservableCollection <Fhr.ModernHistory.Models.FamousPerson> >();

                        var result2 = await response.Content.ReadAsAsync <ObservableCollection <FamousPerson> >();
                    }
                    else
                    {
                        var apiErrorModel = await response.Content.ReadAsAsync <ApiErrorModel>();

                        throw new ApiErrorException(apiErrorModel);
                    }
                }
                catch (Exception e)
                {
                    var apiErrorModel = new ApiErrorModel()
                    {
                        StatusCode = HttpStatusCode.NotFound,
                        Message    = "网络连接错误",
                        Code       = 3
                    };
                    throw new ApiErrorException(apiErrorModel);
                }
            }
            #endregion
            return(await HttpClientUtils.GetAsync <ObservableCollection <FamousPerson> >(FIND_URL));
        }
Beispiel #11
0
 public async Task <PersonEventRelation> SaveAsync(PersonEventRelation personEventRelation)
 {
     return(await HttpClientUtils.PostJsonAsync <PersonEventRelation, PersonEventRelation>(SAVE_URL, personEventRelation));
 }
Beispiel #12
0
 public async Task UpdateAsync(PersonEventRelation personEventRelation)
 {
     var address = string.Format("{0}/{1}", UPDATE_URL, personEventRelation.PersonEventRelationId);
     await HttpClientUtils.PostJsonNoReturnAsync <PersonEventRelation>(address, personEventRelation);
 }
Beispiel #13
0
 public async Task <ObservableCollection <PersonEventRelation> > FindAllAsync()
 {
     return(await HttpClientUtils.GetAsync <ObservableCollection <PersonEventRelation> >(FIND_URL));
 }
Beispiel #14
0
        public async Task PullMaterialAsync(string accessTokenOrAppId, MaterialType materialType, int groupId)
        {
            var count = await MediaApi.GetMediaCountAsync(accessTokenOrAppId);

            if (materialType == MaterialType.Message)
            {
                if (count.news_count > 0)
                {
                    var newsList = await MediaApi.GetNewsMediaListAsync(accessTokenOrAppId, 0, count.news_count);

                    newsList.item.Reverse();

                    foreach (var message in newsList.item)
                    {
                        if (await _materialMessageRepository.IsExistsAsync(message.media_id))
                        {
                            continue;
                        }

                        //var news = await MediaApi.GetForeverNewsAsync(accessTokenOrAppId, message.media_id);
                        var messageItems = new List <MaterialMessageItem>();
                        foreach (var item in message.content.news_item)
                        {
                            var imageUrl = string.Empty;
                            if (!string.IsNullOrEmpty(item.thumb_media_id) && !string.IsNullOrEmpty(item.thumb_url))
                            {
                                await using var ms = new MemoryStream();
                                await MediaApi.GetForeverMediaAsync(accessTokenOrAppId, item.thumb_media_id, ms);

                                ms.Seek(0, SeekOrigin.Begin);

                                var extName = "png";
                                if (StringUtils.Contains(item.thumb_url, "wx_fmt="))
                                {
                                    extName = item.thumb_url.Substring(item.thumb_url.LastIndexOf("=", StringComparison.Ordinal) + 1);
                                }

                                var materialFileName     = PathUtils.GetMaterialFileNameByExtName(extName);
                                var virtualDirectoryPath = PathUtils.GetMaterialVirtualDirectoryPath(UploadType.Image);

                                var directoryPath = PathUtils.Combine(_settingsManager.WebRootPath, virtualDirectoryPath);
                                var filePath      = PathUtils.Combine(directoryPath, materialFileName);

                                await FileUtils.WriteStreamAsync(filePath, ms);

                                imageUrl = PageUtils.Combine(virtualDirectoryPath, materialFileName);
                            }
                            else if (!string.IsNullOrEmpty(item.thumb_url))
                            {
                                var extName = "png";
                                if (StringUtils.Contains(item.thumb_url, "wx_fmt="))
                                {
                                    extName = item.thumb_url.Substring(item.thumb_url.LastIndexOf("=", StringComparison.Ordinal) + 1);
                                }

                                var materialFileName     = PathUtils.GetMaterialFileNameByExtName(extName);
                                var virtualDirectoryPath = PathUtils.GetMaterialVirtualDirectoryPath(UploadType.Image);

                                var directoryPath = PathUtils.Combine(_settingsManager.WebRootPath, virtualDirectoryPath);
                                var filePath      = PathUtils.Combine(directoryPath, materialFileName);

                                await HttpClientUtils.DownloadAsync(item.thumb_url, filePath);

                                imageUrl = PageUtils.Combine(virtualDirectoryPath, materialFileName);
                            }

                            var commentType = CommentType.Block;
                            if (item.need_open_comment == 1)
                            {
                                commentType = item.only_fans_can_comment == 1 ? CommentType.OnlyFans : CommentType.Everyone;
                            }

                            messageItems.Add(new MaterialMessageItem
                            {
                                MessageId        = 0,
                                MaterialType     = MaterialType.Article,
                                MaterialId       = 0,
                                Taxis            = 0,
                                ThumbMediaId     = item.thumb_media_id,
                                Author           = item.author,
                                Title            = item.title,
                                ContentSourceUrl = item.content_source_url,
                                Content          = await SaveImagesAsync(item.content),
                                Digest           = item.digest,
                                ShowCoverPic     = item.show_cover_pic == "1",
                                ThumbUrl         = imageUrl,
                                Url         = item.url,
                                CommentType = commentType
                            });
                        }

                        await _materialMessageRepository.InsertAsync(groupId, message.media_id, messageItems);
                    }
                }
            }
            else if (materialType == MaterialType.Image)
            {
                if (count.image_count > 0)
                {
                    var list = await MediaApi.GetOthersMediaListAsync(accessTokenOrAppId, UploadMediaFileType.image, 0, count.image_count);

                    foreach (var image in list.item)
                    {
                        if (await _materialImageRepository.IsExistsAsync(image.media_id))
                        {
                            continue;
                        }

                        await using var ms = new MemoryStream();
                        await MediaApi.GetForeverMediaAsync(accessTokenOrAppId, image.media_id, ms);

                        ms.Seek(0, SeekOrigin.Begin);

                        var extName = image.url.Substring(image.url.LastIndexOf("=", StringComparison.Ordinal) + 1);

                        var materialFileName     = PathUtils.GetMaterialFileNameByExtName(extName);
                        var virtualDirectoryPath = PathUtils.GetMaterialVirtualDirectoryPath(UploadType.Image);

                        var directoryPath = PathUtils.Combine(_settingsManager.WebRootPath, virtualDirectoryPath);
                        var filePath      = PathUtils.Combine(directoryPath, materialFileName);

                        await FileUtils.WriteStreamAsync(filePath, ms);

                        var material = new MaterialImage
                        {
                            GroupId = groupId,
                            Title   = image.name,
                            Url     = PageUtils.Combine(virtualDirectoryPath, materialFileName),
                            MediaId = image.media_id
                        };

                        await _materialImageRepository.InsertAsync(material);
                    }
                }
            }
            else if (materialType == MaterialType.Audio)
            {
                if (count.voice_count > 0)
                {
                    var list = await MediaApi.GetOthersMediaListAsync(accessTokenOrAppId, UploadMediaFileType.voice, 0, count.voice_count);

                    foreach (var voice in list.item)
                    {
                        if (await _materialAudioRepository.IsExistsAsync(voice.media_id))
                        {
                            continue;
                        }

                        await using var ms = new MemoryStream();
                        await MediaApi.GetForeverMediaAsync(accessTokenOrAppId, voice.media_id, ms);

                        ms.Seek(0, SeekOrigin.Begin);

                        var extName = voice.url.Substring(voice.url.LastIndexOf("=", StringComparison.Ordinal) + 1);

                        var materialFileName     = PathUtils.GetMaterialFileNameByExtName(extName);
                        var virtualDirectoryPath = PathUtils.GetMaterialVirtualDirectoryPath(UploadType.Audio);

                        var directoryPath = PathUtils.Combine(_settingsManager.WebRootPath, virtualDirectoryPath);
                        var filePath      = PathUtils.Combine(directoryPath, materialFileName);

                        await FileUtils.WriteStreamAsync(filePath, ms);

                        var audio = new MaterialAudio
                        {
                            GroupId  = groupId,
                            Title    = voice.name,
                            FileType = extName.ToUpper().Replace(".", string.Empty),
                            Url      = PageUtils.Combine(virtualDirectoryPath, materialFileName),
                            MediaId  = voice.media_id
                        };

                        await _materialAudioRepository.InsertAsync(audio);
                    }
                }
            }
            else if (materialType == MaterialType.Video)
            {
                if (count.video_count > 0)
                {
                    var list = await MediaApi.GetOthersMediaListAsync(accessTokenOrAppId, UploadMediaFileType.video, 0, count.video_count);

                    foreach (var video in list.item)
                    {
                        if (await _materialVideoRepository.IsExistsAsync(video.media_id))
                        {
                            continue;
                        }

                        await using var ms = new MemoryStream();
                        await MediaApi.GetForeverMediaAsync(accessTokenOrAppId, video.media_id, ms);

                        ms.Seek(0, SeekOrigin.Begin);

                        var extName = "mp4";

                        if (!string.IsNullOrEmpty(video.url))
                        {
                            extName = video.url.Substring(video.url.LastIndexOf("=", StringComparison.Ordinal) + 1);
                        }

                        var materialFileName     = PathUtils.GetMaterialFileNameByExtName(extName);
                        var virtualDirectoryPath = PathUtils.GetMaterialVirtualDirectoryPath(UploadType.Video);

                        var directoryPath = PathUtils.Combine(_settingsManager.WebRootPath, virtualDirectoryPath);
                        var filePath      = PathUtils.Combine(directoryPath, materialFileName);

                        await FileUtils.WriteStreamAsync(filePath, ms);

                        var material = new MaterialVideo
                        {
                            GroupId  = groupId,
                            Title    = video.name,
                            FileType = extName.ToUpper().Replace(".", string.Empty),
                            Url      = PageUtils.Combine(virtualDirectoryPath, materialFileName),
                            MediaId  = video.media_id
                        };

                        await _materialVideoRepository.InsertAsync(material);
                    }
                }
            }
        }
Beispiel #15
0
        private T RunRequest <T, Model>(string api, HttpMethodType method, HttpContent content = null) where T : IResponseBase <Model> where Model : class
        {
            var result = Activator.CreateInstance <T>();

            try
            {
                using (var client = new HttpClient())
                {
                    client.SetBasicAuthentication(GetAPIKey(_site), DEFAULT_PASSWORD);
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var uri = new UriBuilder(new Uri(new Uri(GetEndpoint(_site)), api));

                    HttpResponseMessage httpResponse;

                    switch (method)
                    {
                    case HttpMethodType.Get:
                        httpResponse = client.GetAsync(uri.Uri).Result;
                        break;

                    case HttpMethodType.Post:
                        if (content != null)
                        {
                            httpResponse = client.PostAsync(uri.Uri, content).Result;
                        }
                        else
                        {
                            //todo: create ChargifyException
                            throw new Exception("POST HTTP Content header is missing.");
                        }
                        break;

                    case HttpMethodType.Put:
                        if (content != null)
                        {
                            httpResponse = client.PutAsync(uri.Uri, content).Result;
                        }
                        else
                        {
                            //todo: create ChargifyException
                            throw new Exception("PUT HTTP Content header is missing.");
                        }
                        break;

                    case HttpMethodType.Delete:
                        httpResponse = client.DeleteAsync(uri.Uri).Result;
                        break;

                    default:
                        //todo: create ChargifyException
                        throw new Exception("Invalid Http method");
                    }

                    var response = HttpClientUtils.ParseResponse <Model>(httpResponse);
                    result.IsError = response.IsError;
                    result.Message = response.Message;
                    result.Model   = response.Model;
                }
            }
            catch (Exception ex)
            {
                //todo: logger
                result.IsError = true;
                result.Message = ex.Message;
                throw;
            }
            return(result);
        }
Beispiel #16
0
        /// <summary>
        /// 等待JenkinsBuildTask并返回任务结果
        /// </summary>
        /// <param name="appName">应用名称</param>
        /// <param name="environment">所属环境</param>
        /// <param name="logDirName">日志输出文件夹名</param>
        /// <returns>Tuple bool--是否编译成功, string--成功则为任务id 则是异常信息或空, string--编译的SVN的版本 </returns>
        private static Tuple <bool, string, string> WaitJkbtAndGetResult(string appName, string environment,
                                                                         string logDirName)
        {
            var jkbtId = "";

            try
            {
                //第一步:检查Jenkins的任务队列是否有等待执行的任务,没人排队任务则继续第二步
                var jenkinsQueueUrl = GetJenkinsConfig("JenkinsQueueApiUrl", "");
                LogInfoWriter.GetInstance(logDirName).Info($"start check jenkins build task queue is empty, JenkinsQueueApiUrl:{jenkinsQueueUrl}");
                var isJkQueueEmpty = ExecExtensions.RetryUntilTrueWithTimeout(() =>
                {
                    var queueInfo     = HttpClientUtils.GetJson(jenkinsQueueUrl);
                    var queueInfoJObj = JObject.Parse(queueInfo);
                    Console.WriteLine("jenkins build task queue is not empty");
                    return(!queueInfoJObj["items"].Values <JObject>().Any());
                }, ConfigManager.GetConfigObject("JenkinsQueueCheckTimeout", 5) * OneMinute);
                if (!isJkQueueEmpty)
                {
                    throw new Exception("wait jenkins build task finish error; ErrorMsg:check wether jenkins build task queue is empty timout");
                }
                LogInfoWriter.GetInstance(logDirName).Info("check jenkins build task queue is empty end");

                //第二步:获取Jenkins的编译任务Id
                var getJkbtNumberUrl = GetJenkinsConfig("JenkinsGetBuildTaskIdApiUrl", "");
                getJkbtNumberUrl = String.Format(getJkbtNumberUrl, appName, environment);
                LogInfoWriter.GetInstance(logDirName).Info($"start get jenkins build task id, JenkinsGetBuildTaskIdApiUrl:{getJkbtNumberUrl}");
                var jkbtNumberInfo = HttpClientUtils.Get(getJkbtNumberUrl);
                jkbtId = GetJenkinsXmlValue(jkbtNumberInfo);
                if (String.IsNullOrWhiteSpace(jkbtId))
                {
                    throw new Exception("get jenkins build task id error,the jenkins build task id is null or empty!");
                }
                LogInfoWriter.GetInstance(logDirName).Info($"get jenkins build task id:{jkbtId} end");

                //第三步:根据Jenkins的编译任务Id获取其执行结果
                var getJkbtResultUrl = GetJenkinsConfig("JenkinsGetBuildTaskResultApiUrl", "");
                getJkbtResultUrl = String.Format(getJkbtResultUrl, appName, environment, jkbtId);
                LogInfoWriter.GetInstance(logDirName).Info($"start get jenkins build task:{jkbtId} result, JenkinsGetBuildTaskResultApiUrl:{getJkbtResultUrl}");
                var isJkbtFinish = ExecExtensions.RetryUntilTrueWithTimeout(() =>
                {
                    if (String.Equals(JkbtResultSuccess, HttpClientUtils.Get(getJkbtResultUrl),
                                      StringComparison.OrdinalIgnoreCase))
                    {
                        return(ExecExtensions.ResultType.Success);
                    }
                    if (String.Equals(JkbtResultFailure, HttpClientUtils.Get(getJkbtResultUrl),
                                      StringComparison.OrdinalIgnoreCase))
                    {
                        return(ExecExtensions.ResultType.Failure);
                    }
                    return(ExecExtensions.ResultType.Continue);
                }, ConfigManager.GetConfigObject("JenkinsGetBuildTaskResultTimeout", 10) * OneMinute);
                LogInfoWriter.GetInstance(logDirName).Info($"get jenkins build task:{jkbtId} result end");

                //第四步:根据Jenkins编译任务结果返回最终结果
                switch (isJkbtFinish)
                {
                case ExecExtensions.ResultType.Success:
                    var getJkbtSvnNumberUrl = GetJenkinsConfig("JenkinsGetBuildTaskSvnNumberUrl", "");
                    getJkbtSvnNumberUrl = String.Format(getJkbtSvnNumberUrl, appName, environment, jkbtId);
                    LogInfoWriter.GetInstance(logDirName).Info($"start get jenkins build task:{jkbtId} svn number,JenkinsGetBuildTaskSvnNumberUrl:{getJkbtSvnNumberUrl}");
                    var jkbtSvnNumberInfo = HttpClientUtils.Get(getJkbtSvnNumberUrl);
                    var jkbtSvnNumber     = GetJenkinsXmlValue(jkbtSvnNumberInfo);
                    if (String.IsNullOrWhiteSpace(jkbtSvnNumber))
                    {
                        throw new Exception("$the jenkins build task:{jkbtId} svn number is null or empty!");
                    }
                    return(Tuple.Create(true, jkbtId, jkbtSvnNumber));

                case ExecExtensions.ResultType.Failure:
                    return(Tuple.Create(false, jkbtId, "jenkins build task failure"));

                case ExecExtensions.ResultType.Timeout:
                    return(Tuple.Create(false, jkbtId, "jenkins build task timeout"));
                }
            }
            catch (Exception ex)
            {
                return(Tuple.Create(false, jkbtId, ex.ToString()));
            }
            return(Tuple.Create(false, jkbtId, "unknow error"));
        }
Beispiel #17
0
 public async Task <ObservableCollection <FamousPersonType> > FindAllAsync()
 {
     return(await HttpClientUtils.GetAsync <ObservableCollection <FamousPersonType> >(FIND_URL));
 }
Beispiel #18
0
 public async Task DeleteAsync(int id)
 {
     var address = string.Format("{0}/{1}", DELETE_URL, id);
     await HttpClientUtils.PostAsync(address);
 }
Beispiel #19
0
 public async Task UpdateAsync(FamousPerson famousePerson)
 {
     var address = string.Format("{0}/{1}", UPDATE_URL, famousePerson.FamousPersonId);
     await HttpClientUtils.PostJsonNoReturnAsync <FamousPerson>(address, famousePerson);
 }
Beispiel #20
0
        public async Task <Image> DownLoadEventImgAsync(int eventId)
        {
            string address = string.Format("{0}\\{1}", WEBAPI_BASE_EVENT_PICURE, eventId);

            return(await HttpClientUtils.DownLoadImage(address));
        }
Beispiel #21
0
        public async Task <Image> DownLoadPersonImgAsync(int personId)
        {
            string address = string.Format("{0}\\{1}", WEBAPI_BASE_PERSON_PICURE, personId);

            return(await HttpClientUtils.DownLoadImage(address));
        }
 public async Task <ObservableCollection <HistoryEvent> > SearchAsync(EventSearchModel searchModel)
 {
     return(await HttpClientUtils.PostJsonAsync <EventSearchModel, ObservableCollection <HistoryEvent> >(SEARCH_URL, searchModel));
 }
 public async Task UploadPersonImgAsync(int personId, string pictureName)
 {
     var address = string.Format("{0}/{1}/", UPLOAD_PERSON_IMG_URL, personId);
     await HttpClientUtils.UploadFileAsync(address, pictureName);
 }
        /// <summary>
        /// 提交内容到远程服务器, 并返回回应的内容
        /// </summary>
        protected Task <string> HttpInvokeAsync(HttpMethod method, string endpoint, object body)
        {
            var host = Parameters["Host"];

            return(HttpClientUtils.HttpInvokeAsync(host, method, endpoint, body));
        }
Beispiel #25
0
        public async Task <FamousPerson> FindByIdAsync(int id)
        {
            var address = string.Format("{0}/{1}", FIND_URL, id);

            return(await HttpClientUtils.GetAsync <FamousPerson>(address));
        }
 public async Task UploadEventImgAsync(int eventId, string pictureName)
 {
     var address = string.Format("{0}/{1}/", UPLOAD_EVENT_IMG_URL, eventId);
     await HttpClientUtils.UploadFileAsync(address, pictureName);
 }
Beispiel #27
0
 public async Task <FamousPerson> SaveAsync(FamousPerson famousePerson)
 {
     return(await HttpClientUtils.PostJsonAsync <FamousPerson, FamousPerson>(SAVE_URL, famousePerson));
 }
 public async Task <ObservableCollection <HistoryEventType> > FindAllAsync()
 {
     return(await HttpClientUtils.GetAsync <ObservableCollection <HistoryEventType> >(FIND_URL));
 }
Beispiel #29
0
 public async Task <ObservableCollection <FamousPerson> > SearchAsync(PersonSearchModel searchModel)
 {
     return(await HttpClientUtils.PostJsonAsync <PersonSearchModel, ObservableCollection <FamousPerson> >(SEARCH_URL, searchModel));
 }
        public async Task <HistoryEventType> FindByIdAsync(int id)
        {
            var address = string.Format("{0}/{1}", FIND_URL, id);

            return(await HttpClientUtils.GetAsync <HistoryEventType>(address));
        }