コード例 #1
0
		static void Main(string[] args)
		{
			string firstArg;
			if (args.Length < 1)
			{
				firstArg = "1";
			}
			else
			{
				firstArg = args[0];
			}
			var artistId = Convert.ToInt32(firstArg);

			var appSettingsCredentials = new AppSettingsCredentials();
			var apiUri = new ApiUri();

			var api = new ApiFactory(apiUri, appSettingsCredentials);
			Console.WriteLine("Using creds: {0} - {1}", appSettingsCredentials.ConsumerKey, appSettingsCredentials.ConsumerSecret);

			// console apps can't have an async main method, so we have to call an async method 
			var task = Use7DigitalApi(api, artistId);
			task.Wait();

			Console.ReadKey();
		}
コード例 #2
0
ファイル: AuthContractTest.cs プロジェクト: WuZdd/XiaoAiTax
        public async Task RefreshToken_ReturnsTokenInfo()
        {
            if (!File.Exists(TokenSettingFilePath))
            {
                await GetToken_ReturnsTokenInfo();
            }

            var content       = File.ReadAllText(TokenSettingFilePath);
            var tokenSettings = JsonConvert.DeserializeObject <TokenSettings>(content);

            var requestModel = new RefreshTokenRequestModel()
            {
                RefreshToken = tokenSettings.RefreshToken,
            };

            TokenResponseModel result = await ApiFactory.CreateAuthClient()
                                        .RefreshToken(requestModel)
                                        .Retry(3, TimeSpan.FromSeconds(2))
                                        .WhenCatch <HttpStatusFailureException>(ex => ex.StatusCode == System.Net.HttpStatusCode.RequestTimeout);

            Assert.NotNull(result);
            Assert.NotEmpty(result.AccessToken);

            WriteTokenSettings(result);
        }
コード例 #3
0
        /// <summary>
        /// Метод вызывается платежной системой после оплаты и после сообщения нам о платеже(см. метод Result <see cref="Result"/>)
        /// </summary>
        /// <returns></returns>
        //[HttpPost]
        public ActionResult Success()
        {
            RobokassaApi           robokassaApi  = ApiFactory.GetRobokassaApi(WebSettingsConfig.Instance);
            RobokassaPaymentResult paymentResult = robokassaApi.ProcessSuccess(Request.Params);

            if (paymentResult == null)
            {
                LoggerWrapper.RemoteMessage(LoggingType.Error,
                                            "PaymentController.Success. PaymentResult is null. Params={0}",
                                            HttpContextHelper.ParamsToString(Request.Params, RobokassaApi.IsValidParamName));
                return(GetFailView());
            }

            var            purchasedGoogsQuery = new PurchasedGoodsQuery();
            PurchasedGoods purchasedGoods      = purchasedGoogsQuery.Get(paymentResult.PaymentId);

            if (purchasedGoods == null)
            {
                LoggerWrapper.RemoteMessage(LoggingType.Error,
                                            "PaymentController.Success. GetUniqueDownloadId не вернул уникальный идентификатор скачивания. PaymentId={0}, Price={1}, Params={2}",
                                            paymentResult.PaymentId, paymentResult.Price,
                                            HttpContextHelper.ParamsToString(Request.Params, RobokassaApi.IsValidParamName));
                return(GetFailView());
            }

            LoggerWrapper.RemoteMessage(LoggingType.Info,
                                        "PaymentController.Success. Перед тем как сообщить пользователю об успешном платеже на сумму {0} с идентификатором {1}",
                                        MoneyFormatter.ToRubles(paymentResult.Price), paymentResult.PaymentId);

            return(GetSuccessView(purchasedGoods));
        }
コード例 #4
0
        public ActionResult Result()
        {
            RobokassaApi           robokassaApi  = ApiFactory.GetRobokassaApi(WebSettingsConfig.Instance);
            RobokassaPaymentResult paymentResult = robokassaApi.ProcessResult(Request.Params);

            if (paymentResult == null)
            {
                LoggerWrapper.RemoteMessage(LoggingType.Error,
                                            "PaymentController.Result. PaymentResult is null. Params={0}",
                                            HttpContextHelper.ParamsToString(Request.Params, RobokassaApi.IsValidParamName));
                return(Content(ERROR_MESSAGE));
            }

            var  purchasedGoogsQuery = new PurchasedGoodsQuery();
            bool isSuccess           = purchasedGoogsQuery.SuccessfullyPurchased(paymentResult.PaymentId, paymentResult.Price);

            if (!isSuccess)
            {
                LoggerWrapper.RemoteMessage(LoggingType.Error,
                                            "PaymentController.Result. SuccessfullyPurchased вернул false. PaymentId={0}, Price={1}, Params={2}",
                                            paymentResult.PaymentId, paymentResult.Price,
                                            HttpContextHelper.ParamsToString(Request.Params, RobokassaApi.IsValidParamName));
                return(Content(ERROR_MESSAGE));
            }

            LoggerWrapper.RemoteMessage(LoggingType.Info,
                                        "PaymentController.Result. Прошла оплата на сумму {0} с идентификатором {1}",
                                        MoneyFormatter.ToRubles(paymentResult.Price), paymentResult.PaymentId);

            string response = robokassaApi.GetResponseResultOk(paymentResult.PaymentId);

            return(Content(response));
        }
コード例 #5
0
        /// <summary>
        /// Метод вызывается платежной системой если платеж не удался
        /// </summary>
        /// <returns></returns>
        //[HttpPost]
        public ActionResult Fail()
        {
            RobokassaApi           robokassaApi  = ApiFactory.GetRobokassaApi(WebSettingsConfig.Instance);
            RobokassaPaymentResult paymentResult = robokassaApi.ProcessFail(Request.Params);

            if (paymentResult == null)
            {
                LoggerWrapper.RemoteMessage(LoggingType.Error,
                                            "PaymentController.Fail. PaymentResult is null. Params={0}",
                                            HttpContextHelper.ParamsToString(Request.Params, RobokassaApi.IsValidParamName));
                return(GetCancelView());
            }

            var  purchasedGoogsQuery = new PurchasedGoodsQuery();
            bool isSuccess           = purchasedGoogsQuery.FailedPurchased(paymentResult.PaymentId);

            if (!isSuccess)
            {
                LoggerWrapper.RemoteMessage(LoggingType.Error,
                                            "PaymentController.Fail. FailedPurchased вернул false. PaymentId={0}, Price={1}, Params={2}",
                                            paymentResult.PaymentId, paymentResult.Price,
                                            HttpContextHelper.ParamsToString(Request.Params, RobokassaApi.IsValidParamName));
                return(GetCancelView());
            }

            LoggerWrapper.RemoteMessage(LoggingType.Info,
                                        "PaymentController.Fail. Перед тем как сообщить пользователю об отменене платежа на сумму {0} с идентификатором {1}",
                                        MoneyFormatter.ToRubles(paymentResult.Price), paymentResult.PaymentId);

            return(GetCancelView());
        }
コード例 #6
0
        public virtual ActionResult MyFileUploadWidget_Upload(MyFileUploadViewModel model)
        {
            // LOCAL TESTING
            var res = "Form is empty!";
            if (string.IsNullOrEmpty(model.Name))
            {
                return Content(res);
            }
            using (var api = ApiFactory.Create())
            {
                var fileId = new Guid("20CB0347-E7AF-4899-92C6-A460009F5F74");
                res = "Uploaded new file";

                var categoryTreeResponse = api.Root.Category.Nodes.Get(new GetCategoryNodesRequest { CategoryTreeId = new Guid("1BA19133-A833-4127-AD2A-A43500ECE5D2") });
                var allCategoryTreeNodes = categoryTreeResponse.Data.Items;

                var file = api.Media.File.Get(new GetFileRequest { FileId = fileId });

                var putFileRequest = file.ToPutRequest();
                putFileRequest.Data.Categories = new List<Guid>();
                putFileRequest.Data.Categories.Add(allCategoryTreeNodes[0].Id);
                api.Media.File.Put(putFileRequest);

                Thread.Sleep(1000);
                file = api.Media.File.Get(new GetFileRequest { FileId = fileId });
                putFileRequest = file.ToPutRequest();
                putFileRequest.Data.Categories = new List<Guid>();
                putFileRequest.Data.Categories.Add(allCategoryTreeNodes[1].Id);
                api.Media.File.Put(putFileRequest);

            }
            return Content(res);
        }
コード例 #7
0
        public ActionResult ChangeCulture(string lang, string returnUrl)
        {
            Session["Culture"] = new CultureInfo(lang);
            using (var api = ApiFactory.Create())
            {
                var request = new GetPageTranslationsRequest {
                    PageUrl = returnUrl
                };

                var xx = api.Pages.Page.Translations.Get(request);
                if (xx.Data.TotalCount > 1)
                {
                    List <PageTranslationModel> pages1 = xx.Data.Items.ToList();
                    foreach (var item in pages1)
                    {
                        string language = item.LanguageCode != null ? item.LanguageCode : "vi";
                        if (language == lang)
                        {
                            return(Redirect(item.PageUrl));
                        }
                    }
                }
            }
            return(Redirect(returnUrl));
        }
コード例 #8
0
        public async Task <IActionResult> Index(UrlModel urlModel)
        {
            if (urlModel.ProvidedUrl == null)
            {
                return(View(_viewModel));
            }

            this._apiFactory            = new MercuryApiFactory(ApiUris.MercuryApiUri + urlModel.ProvidedUrl, ContentTypes.Json, ApiNames.MercuryApiName, AuthorizationTypes.xKey);
            this._httpRequestController = new HttpRequestController(_apiFactory.GetApi());
            this._httpRequestController.AddContentTypeHeader();
            this._httpRequestController.AddAutorizationHeader(_parser.GetObject(ApiNames.MercuryApiName));

            var result = await _httpRequestController.Send();

            var response = JsonConvert.DeserializeObject <ResponseModel>(result);

            if (response.content == null)
            {
                TempData["Error"] = "Site is not available or doesn't exist";
                return(View(_viewModel));
            }
            if (_viewModel.ResponseModels.Count == 5)
            {
                _viewModel.ResponseModels.RemoveAt(0);
            }
            _viewModel.ResponseModels.Insert(0, response);

            HtmlCounter counter = new HtmlCounter(_viewModel.ResponseModels.Last().content);

            _viewModel.ResponseModels.Last().TagsOccurrences = counter.CountOccurrence();


            return(View(_viewModel));
        }
コード例 #9
0
ファイル: Setup.cs プロジェクト: brunathie/mobileapp
        protected override void InitializeApp(IMvxPluginManager pluginManager, IMvxApplication app)
        {
            base.InitializeApp(pluginManager, app);

#if !USE_PRODUCTION_API
            System.Net.ServicePointManager.ServerCertificateValidationCallback
                += (sender, certificate, chain, sslPolicyErrors) => true;
#endif

            var database    = new Database();
            var timeService = new TimeService(Scheduler.Default);
            var version     = NSBundle.MainBundle.InfoDictionary["CFBundleShortVersionString"];
            var userAgent   = new UserAgent("Daneel", version.ToString());

            var apiFactory   = new ApiFactory(environment, userAgent);
            var loginManager = new LoginManager(apiFactory, database, timeService, TaskPoolScheduler.Default);

            Mvx.RegisterSingleton <ITimeService>(timeService);
            Mvx.RegisterSingleton <IDialogService>(new DialogService());
            Mvx.RegisterSingleton <IBrowserService>(new BrowserService());
            Mvx.RegisterSingleton <IAccessRestrictionStorage>(
                new UserDataAccessRestrictionStorage(Version.Parse(version.ToString())));
            Mvx.RegisterSingleton <ISuggestionProviderContainer>(
                new SuggestionProviderContainer(
                    new MostUsedTimeEntrySuggestionProvider(database, timeService)
                    )
                );

            var togglApp = app as App;
            togglApp.Initialize(loginManager, navigationService);
        }
コード例 #10
0
        public async Task <bool> PushMetadataAsync()
        {
            try
            {
                Log.LogMessage(MessageImportance.High, "Starting build metadata push to the Build Asset Registry...");

                if (!Directory.Exists(ManifestsPath))
                {
                    Log.LogError($"Required folder '{ManifestsPath}' does not exist.");
                }
                else
                {
                    List <BuildData> buildsManifestMetadata = GetBuildManifestsMetadata(ManifestsPath);

                    BuildData finalBuild = MergeBuildManifests(buildsManifestMetadata);

                    IMaestroApi         client        = ApiFactory.GetAuthenticated(MaestroApiEndpoint, BuildAssetRegistryToken);
                    Client.Models.Build recordedBuild = await client.Builds.CreateAsync(finalBuild, s_cancellationToken);

                    Log.LogMessage(MessageImportance.High, $"Metadata has been pushed. Build id in the Build Asset Registry is '{recordedBuild.Id}'");
                }
            }
            catch (Exception exc)
            {
                Log.LogErrorFromException(exc, true);
            }

            return(!Log.HasLoggedErrors);
        }
コード例 #11
0
        public sealed override bool Execute()
        {
            try
            {
                HelixApi     = GetHelixApi();
                AnonymousApi = ApiFactory.GetAnonymous(BaseUri);
                System.Threading.Tasks.Task.Run(() => ExecuteCore(_cancel.Token)).GetAwaiter().GetResult();
            }
            catch (HttpOperationException ex) when(ex.Response.StatusCode == HttpStatusCode.Unauthorized)
            {
                Log.LogError(FailureCategory.Build, "Helix operation returned 'Unauthorized'. Did you forget to set HelixAccessToken?");
            }
            catch (HttpOperationException ex) when(ex.Response.StatusCode == HttpStatusCode.Forbidden)
            {
                Log.LogError(FailureCategory.Build, "Helix operation returned 'Forbidden'.");
            }
            catch (OperationCanceledException ocex) when(ocex.CancellationToken == _cancel.Token)
            {
                // Canceled
                return(false);
            }
            catch (Exception ex)
            {
                Log.LogErrorFromException(FailureCategory.Helix, ex, true, true, null);
            }

            return(!Log.HasLoggedErrors);
        }
コード例 #12
0
    protected HelixTestBase(string helixType) : base()
    {
        var helixSource = GetEnvironmentVariable("MONO_HELIX_SOURCE");

        if (helixSource.StartsWith("pr/"))
        {
            // workaround for https://github.com/dotnet/arcade/issues/1392
            var storage      = new Storage((HelixApi)_api);
            var anonymousApi = ApiFactory.GetAnonymous();
            typeof(HelixApi).GetProperty("Storage").SetValue(anonymousApi, storage, null);
            _api = anonymousApi;
        }

        var build = _api.Job.Define()
                    .WithSource(helixSource)
                    .WithType(helixType)
                    .WithBuild(GetEnvironmentVariable("MONO_HELIX_BUILD_MONIKER"));

        _job = build
               .WithTargetQueue(GetEnvironmentVariable("MONO_HELIX_TARGET_QUEUE"))
               .WithCreator(GetEnvironmentVariable("MONO_HELIX_CREATOR"))
               .WithCorrelationPayloadDirectory(GetEnvironmentVariable("MONO_HELIX_TEST_PAYLOAD_DIRECTORY"))
               .WithCorrelationPayloadFiles(GetEnvironmentVariable("MONO_HELIX_XUNIT_REPORTER_PATH"))
               // these are well-known properties used by Mission Control
               .WithProperty("architecture", GetEnvironmentVariable("MONO_HELIX_ARCHITECTURE"))
               .WithProperty("operatingSystem", GetEnvironmentVariable("MONO_HELIX_OPERATINGSYSTEM"));
    }
コード例 #13
0
ファイル: Proj4.cs プロジェクト: ptv-logistics/xserver.net
        /// <summary>
        /// Tries to load the core PROJ.4 library from a resource package.
        /// </summary>
        /// <param name="name">File name of the library.</param>
        /// <returns>True, if library was loaded, false otherwise.</returns>
        private static bool TryLoadResource(string name)
        {
            try
            {
                byte[] raw;

                using (Package resources = Package.Open(Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(CoordinateReferenceSystem).Namespace + ".resources.zip")))
                {
                    Uri partUri = new Uri("/" + name, UriKind.Relative);

                    if (!resources.PartExists(partUri))
                    {
                        return(false);
                    }

                    using (Stream dllStm = resources.GetPart(partUri).GetStream())
                        raw = Read(dllStm);
                }

                File.WriteAllBytes(name = TempSpace.TryMakeSpace() + Path.DirectorySeparatorChar + name, raw);
            }
            catch
            {
                return(false);
            }

            try { instance = ApiFactory.CreateNativeApi <ICoordinateTransformation>(name); }
            catch { instance = null; }

            return(instance != null);
        }
コード例 #14
0
        public Remote(DarcSettings settings, ILogger logger)
        {
            ValidateSettings(settings);

            _logger = logger;

            if (settings.GitType == GitRepoType.GitHub)
            {
                _gitClient = new GitHubClient(settings.PersonalAccessToken, _logger);
            }
            else if (settings.GitType == GitRepoType.AzureDevOps)
            {
                _gitClient = new AzureDevOpsClient(settings.PersonalAccessToken, _logger);
            }

            // Only initialize the file manager if we have a git client, which excludes "None"
            if (_gitClient != null)
            {
                _fileManager = new GitFileManager(_gitClient, _logger);
            }

            // Initialize the bar client if there is a password
            if (!string.IsNullOrEmpty(settings.BuildAssetRegistryPassword))
            {
                if (!string.IsNullOrEmpty(settings.BuildAssetRegistryBaseUri))
                {
                    _barClient = ApiFactory.GetAuthenticated(settings.BuildAssetRegistryBaseUri, settings.BuildAssetRegistryPassword);
                }
                else
                {
                    _barClient = ApiFactory.GetAuthenticated(settings.BuildAssetRegistryPassword);
                }
            }
        }
コード例 #15
0
        public override void Destory()
        {
            base.Destory();
            IStorageManager storageManager = ApiFactory.Get <IStorageManager>(this);

            storageManager.ClearCache();
        }
コード例 #16
0
ファイル: SitemapController.cs プロジェクト: Creaser10/TSV
        public virtual ActionResult Index()
        {
            var menuItems = new List <MenuItemViewModel>();

            using (var api = ApiFactory.Create())
            {
                var sitemapId = GetSitemapId(api);
                if (sitemapId.HasValue)
                {
                    var request = new GetSitemapTreeRequest {
                        SitemapId = sitemapId.Value
                    };

                    var response = api.Pages.Sitemap.Tree.Get(request);
                    if (response.Data.Count > 0)
                    {
                        menuItems = response.Data.Select(mi => new MenuItemViewModel {
                            Caption = mi.Title, Url = mi.Url
                        }).ToList();
                    }
                }
            }

            return(View(menuItems));
        }
コード例 #17
0
        public IntegrationTestsFixture(ApiFactory <TStartup> apiFactory, HttpClient httpClient)
        {
            //WebApplicationFactoryClientOptions factoryClientOptions = new WebApplicationFactoryClientOptions() { };

            ApiFactory = new ApiFactory <TStartup>();
            HttpClient = ApiFactory.CreateClient();
        }
コード例 #18
0
        public void Sitemap_Crud()
        {
            using (var api = ApiFactory.Create())
            {
                var sitemaps = api.Pages.Sitemaps.Get(new GetSitemapsRequest());

                // Sitemap:
                var sitemap = api.Pages.SitemapNew.Get(new GetSitemapRequest
                {
                    SitemapId = sitemaps.Data.Items.First().Id,
                    Data      = new GetSitemapModel
                    {
                        IncludeAccessRules = true,
                        IncludeNodes       = true,
                    }
                });
                var saveSitmapRequest = sitemap.ToPutRequest();

                // Sitemap nodes:
                var node = api.Pages.SitemapNew.Node.Get(new GetNodeRequest
                {
                    SitemapId = sitemap.Data.Id,
                    NodeId    = sitemap.Nodes.First().Id
                });
                var saveNodeRequest = node.ToPutRequest();
            }
        }
コード例 #19
0
        public ActionResult SitemapMenu(string languageCode)
        {
            var menuItems = new List <MenuItemViewModel>();

            using (var api = ApiFactory.Create())
            {
                var languageId = GetLanguageId(api, languageCode);
                var sitemapId  = GetSitemapId(api);
                if (sitemapId.HasValue)
                {
                    var request = new GetSitemapTreeRequest {
                        SitemapId = sitemapId.Value
                    };
                    request.Data.LanguageId = languageId;
                    var response = api.Pages.Sitemap.Tree.Get(request);
                    if (response.Data.Count > 0)
                    {
                        menuItems = response.Data.Select(mi => new MenuItemViewModel {
                            Caption = mi.Title, Url = mi.Url, IsPublished = mi.PageIsPublished
                        }).ToList();
                    }
                }
            }

            return(View("~/Views/SitemapMenu/Index.cshtml", menuItems));
        }
コード例 #20
0
 private void TheCallToCreateAPaymentIsMade()
 {
     using (var apiBuilder = new ApiFactory())
     {
         var api = apiBuilder.Create();
         this.response = api.CreatePayment(this.paymentReference.ToString(), this.payment).Result;
     }
 }
コード例 #21
0
        public void ShouldNotDisposeHttpClient_WhenHttpClientIsProvidedByConsumer()
        {
            var fakeHttpClient = A.Fake <IHttpClient>();
            var api            = new ApiFactory().Create <IApi>(fakeHttpClient, false, new DefaultApiSettings());

            api.Dispose();
            A.CallTo(() => fakeHttpClient.Dispose()).MustNotHaveHappened();
        }
コード例 #22
0
 protected Task <T> RetryAsync <T>(Func <Task <T> > function)
 {
     // Grab the retry logic from the helix api client
     return(ApiFactory.GetAnonymous().RetryAsync(
                async() => await function(),
                ex => Log.LogMessage(MessageImportance.Low, $"Azure Dev Ops Operation failed: {ex}\nRetrying..."),
                CancellationToken.None));
 }
コード例 #23
0
        private static IApi CreateApi(SiteData site)
        {
            var apiFactory = new ApiFactory("https://rest.trackmatic.co.za/api/v2");
            var api        = apiFactory.Create();

            api.Login(site.ApiKey).Wait();
            return(api);
        }
コード例 #24
0
        public void ShouldDisposeHttpClient_WhenHttpClientIsCreatedInternally()
        {
            var fakeHttpClient = A.Fake <IHttpClient>();
            var api            = new ApiFactory().Create <IApi>(fakeHttpClient, true, new DefaultApiSettings());

            api.Dispose();
            A.CallTo(() => fakeHttpClient.Dispose()).MustHaveHappened();
        }
コード例 #25
0
 public AuthorizeTests(ApiFactory <ApiProject.Startup> factory)
 {
     _factory = factory;
     _client  = factory.CreateClient(new WebApplicationFactoryClientOptions()
     {
         AllowAutoRedirect = false,
     });
 }
コード例 #26
0
 public YunpianClient Init()
 {
     // create httpclient
     _clnt = CreateHttpClient(_conf);
     // create ApiFactory
     _api = new ApiFactory(this);
     return(this);
 }
コード例 #27
0
        /// <summary>
        /// Get the HelixApi based on the settings of this pool provider
        /// </summary>
        /// <returns>For now, just an unauthenticated api client</returns>
        private IHelixApi GetHelixApi()
        {
            IHelixApi api = ApiFactory.GetAuthenticated(_configuration.ApiAuthorizationPat);

            // Alter the base URI based on configuration.  It's also useful to note that in the current version of the API, the endpoint isn't
            // defaulted to https, and so unless this is done every request will fail.
            api.BaseUri = new Uri(_configuration.HelixEndpoint);
            return(api);
        }
コード例 #28
0
            public async Task UsesApiWithoutCredentials()
            {
                await LoginManager.ResetPassword(Email.FromString("*****@*****.**"));

                ApiFactory.Received().CreateApiWith(Arg.Is <Credentials>(
                                                        arg => arg.Header.Name == null &&
                                                        arg.Header.Value == null &&
                                                        arg.Header.Type == HttpHeader.HeaderType.None));
            }
コード例 #29
0
            protected override void AdditionalSetup()
            {
                Location.CountryCode.Returns("LV");
                Location.CountryName.Returns("Latvia");

                Api.Location.Get().Returns(Observable.Return(Location));

                ApiFactory.CreateApiWith(Arg.Any <Credentials>()).Returns(Api);
            }
コード例 #30
0
        public ActionResult BlogPosts(RenderWidgetViewModel model)
        {
            IList <BlogItem> posts;

            var isPagingEnabled = model.GetOptionValue <bool>("ShowPager");
            var pageSize        = model.GetOptionValue <int>("PageSize");
            var page            = Request.QueryString["blogpage"].ToIntOrDefault();
            int postsCount;

            using (var api = ApiFactory.Create())
            {
                var request = new GetBlogPostsModel {
                    Take = pageSize, IncludeTags = true, IncludeCategories = true
                };

                SortAndFilterRequest(request);

                if (isPagingEnabled)
                {
                    var skipCount = page == 0 ? 0 : (page - 1) * pageSize;
                    request.Skip = skipCount;
                }

                request.Take = pageSize;

                var pages = api.Blog.BlogPosts.Get(new GetBlogPostsRequest {
                    Data = request
                });

                posts = pages.Data.Items.Select(
                    x => new BlogItem
                {
                    IntroText   = x.IntroText,
                    PublishedOn = x.ActivationDate,
                    Title       = x.Title,
                    Url         = x.BlogPostUrl,
                    Author      = x.AuthorName,
                    Tags        = x.Tags,
                    Categories  = x.Categories
                }).ToList();
                postsCount = pages.Data.TotalCount;
            }

            var items = new BlogItemsModel
            {
                Items          = posts,
                ShowAuthor     = model.GetOptionValue <bool>("ShowAuthor"),
                ShowDate       = model.GetOptionValue <bool>("ShowDate"),
                ShowCategories = model.GetOptionValue <bool>("ShowCategories"),
                ShowTags       = model.GetOptionValue <bool>("ShowTags"),
                ShowPager      = isPagingEnabled,
                NumberOfPages  = (int)Math.Ceiling((double)postsCount / pageSize),
                CurrentPage    = page > 0 ? page : 1
            };

            return(View(items));
        }
コード例 #31
0
        public async Task <bool> PushMetadataAsync(CancellationToken cancellationToken)
        {
            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                Log.LogMessage(MessageImportance.High, "Starting build metadata push to the Build Asset Registry...");

                if (!Directory.Exists(ManifestsPath))
                {
                    Log.LogError($"Required folder '{ManifestsPath}' does not exist.");
                }
                else
                {
                    List <BuildData> buildsManifestMetadata = GetBuildManifestsMetadata(ManifestsPath, cancellationToken);

                    BuildData finalBuild = MergeBuildManifests(buildsManifestMetadata);

                    IMaestroApi client = ApiFactory.GetAuthenticated(MaestroApiEndpoint, BuildAssetRegistryToken);

                    var deps = await GetBuildDependenciesAsync(client, cancellationToken);

                    Log.LogMessage(MessageImportance.High, "Calculated Dependencies:");
                    foreach (var dep in deps)
                    {
                        Log.LogMessage(MessageImportance.High, $"    {dep.BuildId}, IsProduct: {dep.IsProduct}");
                    }
                    finalBuild.Dependencies = deps;

                    Client.Models.Build recordedBuild = await client.Builds.CreateAsync(finalBuild, cancellationToken);

                    Log.LogMessage(MessageImportance.High, $"Metadata has been pushed. Build id in the Build Asset Registry is '{recordedBuild.Id}'");

                    // Only 'create' the AzDO (VSO) variables if running in an AzDO build
                    if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("BUILD_BUILDID")))
                    {
                        var defaultChannels = await client.DefaultChannels.ListAsync(
                            recordedBuild.GitHubBranch ?? recordedBuild.AzureDevOpsBranch,
                            channelId : null,
                            enabled : true,
                            recordedBuild.GitHubRepository ?? recordedBuild.AzureDevOpsRepository);

                        var defaultChannelsStr = "[" + string.Join("][", defaultChannels.Select(x => x.Channel.Id)) + "]";

                        Console.WriteLine($"##vso[task.setvariable variable=BARBuildId]{recordedBuild.Id}");
                        Console.WriteLine($"##vso[task.setvariable variable=DefaultChannels]{defaultChannelsStr}");
                        Console.WriteLine($"##vso[task.setvariable variable=IsStableBuild]{IsStableBuild}");
                    }
                }
            }
            catch (Exception exc)
            {
                Log.LogErrorFromException(exc, true, true, null);
            }

            return(!Log.HasLoggedErrors);
        }