Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding Polly Example #197

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>

<PropertyGroup Condition=" '$(RunConfiguration)' == 'commercetools.Sdk.HttpApi.MvcExample' " />
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using commercetools.Sdk.Client;
using commercetools.Sdk.Domain.Categories;
using commercetools.Sdk.HttpApi.CommandBuilders;
using Microsoft.AspNetCore.Mvc;

namespace commercetools.Sdk.PollyExample.Controllers
{
public class Categories : Controller
{
private readonly IClient _AdminClient;
private readonly IClient _AnonymousClient;

public Categories(IEnumerable<IClient> clients)
{
this._AdminClient = clients.FirstOrDefault(c => c.Name.Equals("AdminClient"));
this._AnonymousClient = clients.FirstOrDefault(c => c.Name.Equals("AnonymousClient"));
}
// GET
public async Task<IActionResult> Index()
{
var categories = await _AnonymousClient.ExecuteAsync(new QueryCommand<Category>());

//if you want to Debug NotFound Retry Policy enable this
/*
var category = await _AdminClient.Builder()
.Categories()
.GetById("NotFoundId")
.ExecuteAsync();
*/
return View(categories);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace commercetools.Sdk.PollyExample
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:54146",
"sslPort": 44346
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"commercetools.Sdk.PollyExample": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
using System.Collections.Generic;
using commercetools.Sdk.HttpApi.Tokens;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Polly;
using Polly.Extensions.Http;

namespace commercetools.Sdk.PollyExample
{
public class Startup
{
private readonly IConfiguration configuration;

public Startup(IConfiguration configuration)
{
this.configuration = configuration;
}

// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore();
services.AddControllersWithViews();

//Creating the policy
var registry = services.AddPolicyRegistry();
var policy = HttpPolicyExtensions
.HandleTransientHttpError()
//.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.Forbidden)
.RetryAsync(3, onRetry: (exception, retryCount, context) =>
{
var exceptionText = exception?.Exception == null
? string.Empty
: $" exception:{exception.Exception.Message}";
// logging here
});
registry.Add("commercetoolsRetryPolicy", policy);

var clients = new Dictionary<string, TokenFlow>()
{
{"AdminClient", TokenFlow.ClientCredentials},
{"AnonymousClient", TokenFlow.AnonymousSession}
};
// services.UseCommercetools(configuration, "AdminClient")
// .AddPolicyHandlerFromRegistry("commercetoolsRetryPolicy");
services.UseCommercetools(configuration, clients)
.ConfigureAllClients(
builder => builder.AddPolicyHandlerFromRegistry("commercetoolsRetryPolicy"));
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseRouting();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Categories}/{action=Index}/{id?}");
});
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
@using commercetools.Sdk.Domain
@using commercetools.Sdk.Domain.Categories
@model PagedQueryResult<Category>
@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<title>Categories</title>
</head>
<body>
<h1>There are @Model.Count categories</h1>
<div>
<ul>
@foreach (var category in Model.Results)
{
<li>
@category.Name["en"]
</li>
}
</ul>
</div>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AdminClient": {
"ClientId": "",
"ClientSecret": "",
"ProjectKey": "",
"Scope": "",
"ApiBaseAddress": "https://api.europe-west1.gcp.commercetools.com/",
"AuthorizationBaseAddress": "https://auth.europe-west1.gcp.commercetools.com/"
},
"AnonymousClient": {
"ClientId": "",
"ClientSecret": "",
"ProjectKey": "",
"Scope": "",
"ApiBaseAddress": "https://api.europe-west1.gcp.commercetools.com/",
"AuthorizationBaseAddress": "https://auth.europe-west1.gcp.commercetools.com/"
},
"AllowedHosts": "*"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="5.0.1" />
<PackageReference Include="Polly.Extensions.Http" Version="3.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\commercetools.Sdk.All\commercetools.Sdk.All.csproj" />
</ItemGroup>

<ItemGroup>
<None Remove="Views\" />
<None Remove="Views\Categories\" />
</ItemGroup>
<ItemGroup>
<Folder Include="Views\" />
<Folder Include="Views\Categories\" />
</ItemGroup>
</Project>
7 changes: 7 additions & 0 deletions commercetools.Sdk/commercetools.Sdk.sln
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "commercetools.Sdk.ManualTes
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ManualTests", "ManualTests", "{73E27F17-DEB9-488B-8137-A57D4129E0E6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "commercetools.Sdk.PollyExample", "Examples\commercetools.Sdk.PollyExample\commercetools.Sdk.PollyExample.csproj", "{0FB0CEBF-A0E5-483C-92A2-916DB63ED77C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -155,6 +157,10 @@ Global
{A618E44D-3C9C-4343-A7AE-595A6FADD51A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A618E44D-3C9C-4343-A7AE-595A6FADD51A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A618E44D-3C9C-4343-A7AE-595A6FADD51A}.Release|Any CPU.Build.0 = Release|Any CPU
{0FB0CEBF-A0E5-483C-92A2-916DB63ED77C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0FB0CEBF-A0E5-483C-92A2-916DB63ED77C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0FB0CEBF-A0E5-483C-92A2-916DB63ED77C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0FB0CEBF-A0E5-483C-92A2-916DB63ED77C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -171,6 +177,7 @@ Global
{1ED86710-A7A6-4E63-AAC6-A98A1EEB46D2} = {246B3DBC-CE94-4B32-AEFB-8C42A0D8F502}
{2ADE2630-89A4-4F15-A855-7FA421D589FE} = {199CAB4C-C38A-47B7-AB72-CCFCCA06C31D}
{A618E44D-3C9C-4343-A7AE-595A6FADD51A} = {73E27F17-DEB9-488B-8137-A57D4129E0E6}
{0FB0CEBF-A0E5-483C-92A2-916DB63ED77C} = {246B3DBC-CE94-4B32-AEFB-8C42A0D8F502}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {38B2497B-A494-43A7-A44D-88131CE16D12}
Expand Down