diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml new file mode 100644 index 000000000..f27e1f774 --- /dev/null +++ b/.github/workflows/build-and-test.yml @@ -0,0 +1,108 @@ +name: Basic Build and Test + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + build-and-test: + name: Build, Test and Analyze + runs-on: ubuntu-latest + env: + ASSISTANT_ID: ${{ secrets.ASSISTANT_ID }} + + steps: + # 1. Checkout source code + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 # Shallow clones should be disabled for a better relevance of analysis + + # 2. Install required dependencies (Setup environment) + # Uses global.json to pick the correct .NET SDK version + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + global-json-file: global.json + + # JDK 17 is required for SonarScanner + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: 17 + distribution: 'zulu' + + # Install the SonarScanner tool globally + - name: Install SonarCloud scanner + run: | + dotnet tool install --global dotnet-sonarscanner + + # 3. SonarCloud Begin (Quality Check Setup) + - name: Begin Sonar scan + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Necesario para comentar en el PR + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + run: | + dotnet sonarscanner begin /k:"epam-ai_eShop" /o:"epam-ai" /d:sonar.token="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="https://sonarcloud.io" /d:sonar.cs.vstest.reportsPaths="**/*.trx" /d:sonar.cs.vscoveragexml.reportsPaths="**/coverage.cobertura.xml" + + # 4. Install dependencies (Restore) + - name: Restore dependencies + run: dotnet restore eShop.slnx + + # 5. Build the application + - name: Build + run: dotnet build eShop.slnx --no-restore --configuration Debug + + # 6. Run automated tests + # Fails pipeline if tests fail. Generates coverage for SonarQube. + - name: Test + run: dotnet test --solution eShop.Web.slnf --no-build --no-progress --output detailed + + # 7. Execute SonarCloud Analysis (End) + # This pushes the analysis to the server and performs the quality gate check + - name: End Sonar scan + env: + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + run: dotnet sonarscanner end /d:sonar.token="${{ secrets.SONAR_TOKEN }}" + + - name: Get Access Token + id: auth + env: + CODEMIE_CLIENT_ID: ${{ secrets.CODEMIE_CLIENT_ID }} + CODEMIE_CLIENT_SECRET: ${{ secrets.CODEMIE_CLIENT_SECRET }} + run: | + set -euo pipefail + + ACCESS_TOKEN=$(curl -s -X POST 'https://keycloak.eks-core.aws.main.edp.projects.epam.com/auth/realms/codemie-prod/protocol/openid-connect/token' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d 'grant_type=password' \ + -d 'client_id=codemie-sdk' \ + -d "username=${CODEMIE_CLIENT_ID}" \ + -d "password=${CODEMIE_CLIENT_SECRET}" | jq -r '.access_token') + + if [[ -z "${ACCESS_TOKEN}" || "${ACCESS_TOKEN}" == "null" ]]; then + echo "Failed to obtain access token" >&2 + exit 1 + fi + + echo "access_token=${ACCESS_TOKEN}" >> $GITHUB_OUTPUT + echo "Access token obtained successfully" + + - name: Call CodeMie Agent + env: + ACCESS_TOKEN: ${{ steps.auth.outputs.access_token }} + run: | + set -euo pipefail + + RESPONSE=$(curl -s -X POST "https://codemie.lab.epam.com/code-assistant-api/v1/assistants/${ASSISTANT_ID}/model" \ + -H "Content-Type: application/json" \ + -H "Accept: application/json" \ + -H "Authorization: Bearer $ACCESS_TOKEN" \ + -d "{\"text\": \"Hi\"}") + echo "$RESPONSE" + GENERATED=$(echo "$RESPONSE" | jq -r '.generated') + + echo "CodeMie Agent Response:" + echo "$GENERATED" \ No newline at end of file diff --git a/.github/workflows/codemieAgent.yml b/.github/workflows/codemieAgent.yml new file mode 100644 index 000000000..09886f8eb --- /dev/null +++ b/.github/workflows/codemieAgent.yml @@ -0,0 +1,69 @@ +name: Call CodeMie Agent + +on: + workflow_dispatch: + inputs: + prompt: + description: Prompt to send to CodeMie Agent + required: true + type: string + +jobs: + call: + runs-on: ubuntu-latest + env: + ASSISTANT_ID: ${{ secrets.ASSISTANT_ID }} + PROMPT: ${{ inputs.prompt }} + steps: + - name: Get Access Token + id: auth + env: + CODEMIE_CLIENT_ID: ${{ secrets.CODEMIE_CLIENT_ID }} + CODEMIE_CLIENT_SECRET: ${{ secrets.CODEMIE_CLIENT_SECRET }} + run: | + set -euo pipefail + + ACCESS_TOKEN=$(curl -s -X POST 'https://keycloak.eks-core.aws.main.edp.projects.epam.com/auth/realms/codemie-prod/protocol/openid-connect/token' \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d 'grant_type=password' \ + -d 'client_id=codemie-sdk' \ + -d "username=${CODEMIE_CLIENT_ID}" \ + -d "password=${CODEMIE_CLIENT_SECRET}" | jq -r '.access_token') + + if [[ -z "${ACCESS_TOKEN}" || "${ACCESS_TOKEN}" == "null" ]]; then + echo "Failed to obtain access token" >&2 + exit 1 + fi + + echo "access_token=${ACCESS_TOKEN}" >> $GITHUB_OUTPUT + echo "Access token obtained successfully" + + - name: Call CodeMie Agent + env: + ACCESS_TOKEN: ${{ steps.auth.outputs.access_token }} + run: | + set -euo pipefail + + RESPONSE=$(curl -s -X POST "https://codemie.lab.epam.com/code-assistant-api/v1/assistants/${ASSISTANT_ID}/model" \ + -H "Content-Type: application/json" \ + -H "Accept: application/json" \ + -H "Authorization: Bearer $ACCESS_TOKEN" \ + -d "{\"text\": \"${PROMPT}\"}") + echo "$RESPONSE" + GENERATED=$(echo "$RESPONSE" | jq -r '.generated') + RESULT=$(echo "$GENERATED" | grep -oP 'result: \K\w+' | head -1) + DETAIL=$(echo "$GENERATED" | sed -n '/detail:/,$p' | sed '1d') + + echo "CodeMie Agent Response:" + echo "$DETAIL" + + if [[ "$RESULT" != "true" ]]; then + echo "Pipeline failed: result is false" >&2 + exit 1 + fi + + - name: Validate Workflow + run: | + RANDOM_ID=$(uuidgen) + echo "Workflow validation ID: $RANDOM_ID" + diff --git a/.github/workflows/markdownlint-problem-matcher.json b/.github/workflows/markdownlint-problem-matcher.json deleted file mode 100644 index f0741f6b9..000000000 --- a/.github/workflows/markdownlint-problem-matcher.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "problemMatcher": [ - { - "owner": "markdownlint", - "pattern": [ - { - "regexp": "^([^:]*):(\\d+):?(\\d+)?\\s([\\w-\\/]*)\\s(.*)$", - "file": 1, - "line": 2, - "column": 3, - "code": 4, - "message": 5 - } - ] - } - ] -} diff --git a/.github/workflows/markdownlint.yml b/.github/workflows/markdownlint.yml deleted file mode 100644 index 9cb00dc5a..000000000 --- a/.github/workflows/markdownlint.yml +++ /dev/null @@ -1,26 +0,0 @@ -name: Markdownlint - -permissions: - contents: read - -# run even on changes without markdown changes, so that we can -# make it in GitHub a required check for PR's -on: - pull_request: - -jobs: - lint: - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - - name: Use Node.js - uses: actions/setup-node@v4 - with: - node-version: 16.x - - name: Run Markdownlint - run: | - echo "::add-matcher::.github/workflows/markdownlint-problem-matcher.json" - npm i -g markdownlint-cli - markdownlint --ignore '.dotnet/' '**/*.md' diff --git a/.github/workflows/playwright.yml b/.github/workflows/playwright.yml index 7aa5749ed..d3ba936c6 100644 --- a/.github/workflows/playwright.yml +++ b/.github/workflows/playwright.yml @@ -28,12 +28,7 @@ jobs: with: node-version: lts/* - name: Install dependencies - run: npm ci - - name: Install .NET HTTPS Development Certificate - # if: matrix.os == 'ubuntu-latest' - run: | - dotnet dev-certs https --clean - dotnet dev-certs https --trust + run: npm install - name: Install Playwright Browsers run: npx playwright install chromium - name: Run Playwright tests @@ -42,6 +37,10 @@ jobs: ESHOP_USE_HTTP_ENDPOINTS: 1 USERNAME1: bob PASSWORD: Pass123$ + RP_API_KEY: ${{ secrets.REPORTPORTAL_API_KEY }} + RP_ENDPOINT: "https://reportportal.epam.com/api/v1" + RP_PROJECT: ${{ secrets.REPORTPORTAL_PROJECT }} + RP_LAUNCH: "Playwright E2E | ${{ github.repository }} | ${{ github.ref_name }} | #${{ github.run_number }}" - uses: actions/upload-artifact@v4 if: always() with: diff --git a/.github/workflows/pr-validation-maui.yml b/.github/workflows/pr-validation-maui.yml deleted file mode 100644 index 2f63a0943..000000000 --- a/.github/workflows/pr-validation-maui.yml +++ /dev/null @@ -1,42 +0,0 @@ -name: eShop Pull Request Validation - .NET MAUI - -on: - pull_request: - branches: - - '**' - paths: - - 'src/ClientApp/**' - - 'tests/ClientApp.UnitTests/**' - - '.github/workflows/pr-validation-maui.yml' - push: - branches: - - main - paths: - - 'src/ClientApp/**' - - 'tests/ClientApp.UnitTests/**' - - '.github/workflows/pr-validation-maui.yml' - -jobs: - test: - runs-on: windows-latest - steps: - - uses: actions/checkout@v4 - - name: Setup .NET (global.json) - uses: actions/setup-dotnet@v3 - - - name: Update Workloads - run: dotnet workload update - - - name: Install Workloads - shell: pwsh - run: | - dotnet workload install android - dotnet workload install ios - dotnet workload install maccatalyst - dotnet workload install maui - - - name: Build - run: dotnet build src/ClientApp/ClientApp.csproj - - - name: Test - run: dotnet test --project tests/ClientApp.UnitTests/ClientApp.UnitTests.csproj --no-progress --output detailed \ No newline at end of file diff --git a/.github/workflows/pr-validation.yml b/.github/workflows/pr-validation.yml deleted file mode 100644 index 77431a0ca..000000000 --- a/.github/workflows/pr-validation.yml +++ /dev/null @@ -1,29 +0,0 @@ -name: eShop Pull Request Validation - -on: - pull_request: - paths-ignore: - - '**.md' - - 'src/ClientApp/**' - - 'tests/ClientApp.UnitTests/**' - - '.github/workflows/pr-validation-maui.yml' - push: - branches: - - main - paths-ignore: - - '**.md' - - 'src/ClientApp/**' - - 'tests/ClientApp.UnitTests/**' - - '.github/workflows/pr-validation-maui.yml' - -jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - name: Setup .NET (global.json) - uses: actions/setup-dotnet@v3 - - name: Build - run: dotnet build eShop.Web.slnf - - name: Test - run: dotnet test --solution eShop.Web.slnf --no-build --no-progress --output detailed \ No newline at end of file diff --git a/README.md b/README.md index a56eecbf9..db0fb2281 100644 --- a/README.md +++ b/README.md @@ -8,10 +8,8 @@ A reference .NET application implementing an e-commerce website using a services ## Getting Started -This version of eShop is based on .NET 9. - -Previous eShop versions: -* [.NET 8](https://github.com/dotnet/eShop/tree/release/8.0) +This version of eShop is based on [.NET 10](https://dotnet.microsoft.com/en-us/download/dotnet/10.0). +You need to have this version of the SDK installed in your laptop to run the app. ### Prerequisites @@ -79,8 +77,10 @@ then look for lines like this in the console output in order to find the URL to Login to the dashboard at: http://localhost:19888/login?t=uniquelogincodeforyou ``` -> You may need to install ASP.NET Core HTTPS development certificates first, and then close all browser tabs. Learn more at https://aka.ms/aspnet/https-trust-dev-cert - +> You may need to install ASP.NET Core HTTPS development certificates first, and then close all browser tabs running the below command. Learn more at https://aka.ms/aspnet/https-trust-dev-cert +```sh +dotnet dev-certs https --trust +``` ### Azure Open AI When using Azure OpenAI, inside *eShop.AppHost/appsettings.json*, add the following section: diff --git a/eShop.slnx b/eShop.slnx index 42061bab1..5d1c13a6f 100644 --- a/eShop.slnx +++ b/eShop.slnx @@ -1,36 +1,33 @@  + + + + + + - + - + + - - - - - - - - - - \ No newline at end of file diff --git a/package.json b/package.json index 5d5626b97..9023f857b 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "devDependencies": { "@playwright/test": "^1.42.1", "@types/node": "^20.11.25", - "dotenv": "^16.4.5" + "dotenv": "^16.4.5", + "@reportportal/agent-js-playwright": "^5.3.2" } } diff --git a/playwright.config.ts b/playwright.config.ts index 9728afbcd..70aa43aec 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -17,8 +17,33 @@ export default defineConfig({ retries: process.env.CI ? 2 : 0, /* Opt out of parallel tests on CI. */ workers: process.env.CI ? 1 : undefined, - /* Reporter to use. See https://playwright.dev/docs/test-reporters */ - reporter: 'html', + /* Reporter to use. See https://playwright.dev/docs/test-reporters */ + reporter: process.env.CI + ? (process.env.RP_API_KEY && process.env.RP_ENDPOINT && process.env.RP_PROJECT + ? [ + ['html'], + ['@reportportal/agent-js-playwright', { + apiKey: process.env.RP_API_KEY, + endpoint: process.env.RP_ENDPOINT, + project: process.env.RP_PROJECT, + launch: process.env.RP_LAUNCH || 'Playwright E2E Tests', + description: 'eShop Playwright E2E Tests', + mode: 'DEFAULT', + debug: false, + attributes: [ + { + key: 'environment', + value: 'CI' + } + ], + restClientConfig: { + timeout: 30000 + } + }] + ] + : [['html']] + ) + : 'html', /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ use: { /* Base URL to use in actions like `await page.goto('/')`. */ diff --git a/src/ClientApp/Animations/Base/AnimationBase.cs b/src/ClientApp/Animations/Base/AnimationBase.cs deleted file mode 100644 index 2e90c3f61..000000000 --- a/src/ClientApp/Animations/Base/AnimationBase.cs +++ /dev/null @@ -1,111 +0,0 @@ -using System.Diagnostics; - -namespace eShop.ClientApp.Animations.Base; - -public abstract class AnimationBase : BindableObject -{ - public static readonly BindableProperty TargetProperty = BindableProperty.Create(nameof(Target), - typeof(VisualElement), typeof(AnimationBase), - propertyChanged: (bindable, oldValue, newValue) => ((AnimationBase)bindable).Target = (VisualElement)newValue); - - public static readonly BindableProperty DurationProperty = BindableProperty.Create(nameof(Duration), typeof(string), - typeof(AnimationBase), "1000", - propertyChanged: (bindable, oldValue, newValue) => ((AnimationBase)bindable).Duration = (string)newValue); - - public static readonly BindableProperty EasingProperty = BindableProperty.Create(nameof(Easing), typeof(EasingType), - typeof(AnimationBase), EasingType.Linear, - propertyChanged: (bindable, oldValue, newValue) => ((AnimationBase)bindable).Easing = (EasingType)newValue); - - public static readonly BindableProperty RepeatForeverProperty = BindableProperty.Create(nameof(RepeatForever), - typeof(bool), typeof(AnimationBase), false, - propertyChanged: (bindable, oldValue, newValue) => ((AnimationBase)bindable).RepeatForever = (bool)newValue); - - public static readonly BindableProperty DelayProperty = BindableProperty.Create(nameof(Delay), typeof(int), - typeof(AnimationBase), 0, - propertyChanged: (bindable, oldValue, newValue) => ((AnimationBase)bindable).Delay = (int)newValue); - - private bool _isRunning; - - public VisualElement Target - { - get => (VisualElement)GetValue(TargetProperty); - set => SetValue(TargetProperty, value); - } - - public string Duration - { - get => (string)GetValue(DurationProperty); - set => SetValue(DurationProperty, value); - } - - public EasingType Easing - { - get => (EasingType)GetValue(EasingProperty); - set => SetValue(EasingProperty, value); - } - - public bool RepeatForever - { - get => (bool)GetValue(RepeatForeverProperty); - set => SetValue(RepeatForeverProperty, value); - } - - public int Delay - { - get => (int)GetValue(DelayProperty); - set => SetValue(DelayProperty, value); - } - - protected abstract Task BeginAnimation(); - - public async Task Begin() - { - try - { - if (!_isRunning) - { - _isRunning = true; - - await InternalBegin() - .ContinueWith(t => t.Exception, TaskContinuationOptions.OnlyOnFaulted) - .ConfigureAwait(false); - } - } - catch (TaskCanceledException) - { - } - catch (Exception ex) - { - Debug.WriteLine($"Exception in animation {ex}"); - } - } - - protected abstract Task ResetAnimation(); - - public async Task Reset() - { - _isRunning = false; - await ResetAnimation(); - } - - private async Task InternalBegin() - { - if (Delay > 0) - { - await Task.Delay(Delay); - } - - if (!RepeatForever) - { - await BeginAnimation(); - } - else - { - do - { - await BeginAnimation(); - await ResetAnimation(); - } while (RepeatForever); - } - } -} diff --git a/src/ClientApp/Animations/Base/EasingType.cs b/src/ClientApp/Animations/Base/EasingType.cs deleted file mode 100644 index a04627d37..000000000 --- a/src/ClientApp/Animations/Base/EasingType.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace eShop.ClientApp.Animations.Base; - -public enum EasingType -{ - BounceIn, - BounceOut, - CubicIn, - CubicInOut, - CubicOut, - Linear, - SinIn, - SinInOut, - SinOut, - SpringIn, - SpringOut -} diff --git a/src/ClientApp/Animations/FadeToAnimation.cs b/src/ClientApp/Animations/FadeToAnimation.cs deleted file mode 100644 index 5d2998a46..000000000 --- a/src/ClientApp/Animations/FadeToAnimation.cs +++ /dev/null @@ -1,155 +0,0 @@ -using eShop.ClientApp.Animations.Base; -using eShop.ClientApp.Helpers; - -namespace eShop.ClientApp.Animations; - -public class FadeToAnimation : AnimationBase -{ - public static readonly BindableProperty OpacityProperty = - BindableProperty.Create(nameof(Opacity), typeof(double), typeof(FadeToAnimation), 0.0d, - propertyChanged: (bindable, oldValue, newValue) => - ((FadeToAnimation)bindable).Opacity = (double)newValue); - - public double Opacity - { - get => (double)GetValue(OpacityProperty); - set => SetValue(OpacityProperty, value); - } - - protected override Task BeginAnimation() - { - if (Target == null) - { - throw new NullReferenceException("Null Target property."); - } - - return Target.FadeTo(Opacity, Convert.ToUInt32(Duration), EasingHelper.GetEasing(Easing)); - } - - protected override Task ResetAnimation() - { - if (Target == null) - { - throw new NullReferenceException("Null Target property."); - } - - return Target.FadeTo(0, 0); - } -} - -public class FadeInAnimation : AnimationBase -{ - public enum FadeDirection - { - Up, - Down - } - - public static readonly BindableProperty DirectionProperty = - BindableProperty.Create(nameof(Direction), typeof(FadeDirection), typeof(FadeInAnimation), FadeDirection.Up, - propertyChanged: (bindable, oldValue, newValue) => - ((FadeInAnimation)bindable).Direction = (FadeDirection)newValue); - - public FadeDirection Direction - { - get => (FadeDirection)GetValue(DirectionProperty); - set => SetValue(DirectionProperty, value); - } - - protected override Task BeginAnimation() - { - if (Target == null) - { - throw new NullReferenceException("Null Target property."); - } - - Target.Dispatcher.Dispatch(() => Target.Animate("FadeIn", FadeIn(), 16, Convert.ToUInt32(Duration))); - - return Task.CompletedTask; - } - - protected override Task ResetAnimation() - { - if (Target == null) - { - throw new NullReferenceException("Null Target property."); - } - - Target.Dispatcher.Dispatch(() => Target.FadeTo(0, 0)); - - return Task.CompletedTask; - } - - internal Animation FadeIn() - { - var animation = new Animation(); - - animation.WithConcurrent(f => Target.Opacity = f, 0, 1, Microsoft.Maui.Easing.CubicOut); - - animation.WithConcurrent( - f => Target.TranslationY = f, - Target.TranslationY + (Direction == FadeDirection.Up ? 50 : -50), Target.TranslationY, - Microsoft.Maui.Easing.CubicOut); - - return animation; - } -} - -public class FadeOutAnimation : AnimationBase -{ - public enum FadeDirection - { - Up, - Down - } - - public static readonly BindableProperty DirectionProperty = - BindableProperty.Create(nameof(Direction), typeof(FadeDirection), typeof(FadeOutAnimation), FadeDirection.Up, - propertyChanged: (bindable, oldValue, newValue) => - ((FadeOutAnimation)bindable).Direction = (FadeDirection)newValue); - - public FadeDirection Direction - { - get => (FadeDirection)GetValue(DirectionProperty); - set => SetValue(DirectionProperty, value); - } - - protected override Task BeginAnimation() - { - if (Target == null) - { - throw new NullReferenceException("Null Target property."); - } - - Target.Dispatcher.Dispatch(() => Target.Animate("FadeOut", FadeOut(), 16, Convert.ToUInt32(Duration))); - - return Task.CompletedTask; - } - - protected override Task ResetAnimation() - { - if (Target == null) - { - throw new NullReferenceException("Null Target property."); - } - - Target.Dispatcher.Dispatch(() => Target.FadeTo(0, 0)); - - return Task.CompletedTask; - } - - internal Animation FadeOut() - { - Animation animation = new(); - - animation.WithConcurrent( - f => Target.Opacity = f, - 1, 0); - - animation.WithConcurrent( - f => Target.TranslationY = f, - Target.TranslationY, Target.TranslationY + (Direction == FadeDirection.Up ? 50 : -50)); - - return animation; - } -} diff --git a/src/ClientApp/Animations/StoryBoard.cs b/src/ClientApp/Animations/StoryBoard.cs deleted file mode 100644 index df8d745a5..000000000 --- a/src/ClientApp/Animations/StoryBoard.cs +++ /dev/null @@ -1,45 +0,0 @@ -using eShop.ClientApp.Animations.Base; - -namespace eShop.ClientApp.Animations; - -[ContentProperty("Animations")] -public class StoryBoard : AnimationBase -{ - public StoryBoard() - { - Animations = new List(); - } - - public StoryBoard(List animations) - { - Animations = animations; - } - - public List Animations { get; } - - protected override async Task BeginAnimation() - { - foreach (var animation in Animations) - { - if (animation.Target == null) - { - animation.Target = Target; - } - - await animation.Begin(); - } - } - - protected override async Task ResetAnimation() - { - foreach (var animation in Animations) - { - if (animation.Target == null) - { - animation.Target = Target; - } - - await animation.Reset(); - } - } -} diff --git a/src/ClientApp/App.xaml b/src/ClientApp/App.xaml deleted file mode 100644 index bd3a678bf..000000000 --- a/src/ClientApp/App.xaml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/src/ClientApp/App.xaml.cs b/src/ClientApp/App.xaml.cs deleted file mode 100644 index a5ae3a114..000000000 --- a/src/ClientApp/App.xaml.cs +++ /dev/null @@ -1,167 +0,0 @@ -using System.Diagnostics; -using System.Globalization; -using eShop.ClientApp.Services; -using eShop.ClientApp.Services.AppEnvironment; -using eShop.ClientApp.Services.Location; -using eShop.ClientApp.Services.Settings; -using eShop.ClientApp.Services.Theme; -using Location = eShop.ClientApp.Models.Location.Location; - -namespace eShop.ClientApp; - -public partial class App : Application -{ - private readonly IAppEnvironmentService _appEnvironmentService; - private readonly ILocationService _locationService; - private readonly INavigationService _navigationService; - private readonly ISettingsService _settingsService; - private readonly ITheme _theme; - - public App( - ISettingsService settingsService, IAppEnvironmentService appEnvironmentService, - INavigationService navigationService, ILocationService locationService, - ITheme theme) - { - _settingsService = settingsService; - _appEnvironmentService = appEnvironmentService; - _navigationService = navigationService; - _locationService = locationService; - _theme = theme; - - InitializeComponent(); - - InitApp(); - - - Current.UserAppTheme = AppTheme.Light; - } - - protected override Window CreateWindow(IActivationState activationState) - { - return new Window(new AppShell(_navigationService)); - } - - private void InitApp() - { - if (VersionTracking.IsFirstLaunchEver) - { - _settingsService.UseMocks = true; - } - - if (!_settingsService.UseMocks) - { - _appEnvironmentService.UpdateDependencies(_settingsService.UseMocks); - } - } - - protected override async void OnStart() - { - base.OnStart(); - - if (_settingsService.AllowGpsLocation && !_settingsService.UseFakeLocation) - { - await GetGpsLocation(); - } - - if (!_settingsService.UseMocks) - { - await SendCurrentLocation(); - } - - OnResume(); - } - - protected override void OnSleep() - { - SetStatusBar(); - RequestedThemeChanged -= App_RequestedThemeChanged; - } - - protected override void OnResume() - { - SetStatusBar(); - RequestedThemeChanged += App_RequestedThemeChanged; - } - - private void App_RequestedThemeChanged(object sender, AppThemeChangedEventArgs e) - { - Dispatcher.Dispatch(() => SetStatusBar()); - } - - private void SetStatusBar() - { - var nav = Windows[0].Page as NavigationPage; - - if (Current.RequestedTheme == AppTheme.Dark) - { - _theme?.SetStatusBarColor(Colors.Black, false); - if (nav != null) - { - nav.BarBackgroundColor = Colors.Black; - nav.BarTextColor = Colors.White; - } - } - else - { - _theme?.SetStatusBarColor(Colors.White, true); - if (nav != null) - { - nav.BarBackgroundColor = Colors.White; - nav.BarTextColor = Colors.Black; - } - } - } - - private async Task GetGpsLocation() - { - try - { - var request = new GeolocationRequest(GeolocationAccuracy.High); - var location = await Geolocation.GetLocationAsync(request, CancellationToken.None).ConfigureAwait(false); - - if (location != null) - { - _settingsService.Latitude = location.Latitude.ToString(); - _settingsService.Longitude = location.Longitude.ToString(); - } - } - catch (Exception ex) - { - if (ex is FeatureNotEnabledException || ex is FeatureNotEnabledException || ex is PermissionException) - { - _settingsService.AllowGpsLocation = false; - } - - // Unable to get location - Debug.WriteLine(ex); - } - } - - private async Task SendCurrentLocation() - { - var location = new Location - { - Latitude = double.Parse(_settingsService.Latitude, CultureInfo.InvariantCulture), - Longitude = double.Parse(_settingsService.Longitude, CultureInfo.InvariantCulture) - }; - - await _locationService.UpdateUserLocation(location); - } - - public static void HandleAppActions(AppAction appAction) - { - if (Current is not App app) - { - return; - } - - app.Dispatcher.Dispatch( - async () => - { - if (appAction.Id.Equals(AppActions.ViewProfileAction.Id)) - { - await app._navigationService.NavigateToAsync("//Main/Profile"); - } - }); - } -} diff --git a/src/ClientApp/AppActions.cs b/src/ClientApp/AppActions.cs deleted file mode 100644 index b6f5468e4..000000000 --- a/src/ClientApp/AppActions.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace eShop.ClientApp; - -public static class AppActions -{ - public static readonly AppAction - ViewProfileAction = new("view_profile", "View Profile", "View your user profile"); -} diff --git a/src/ClientApp/AppShell.xaml b/src/ClientApp/AppShell.xaml deleted file mode 100644 index f24f5c0a9..000000000 --- a/src/ClientApp/AppShell.xaml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/ClientApp/Services/AppEnvironment/AppEnvironmentService.cs b/src/ClientApp/Services/AppEnvironment/AppEnvironmentService.cs deleted file mode 100644 index c2a1db1b5..000000000 --- a/src/ClientApp/Services/AppEnvironment/AppEnvironmentService.cs +++ /dev/null @@ -1,66 +0,0 @@ -using eShop.ClientApp.Services.Basket; -using eShop.ClientApp.Services.Catalog; -using eShop.ClientApp.Services.Identity; -using eShop.ClientApp.Services.Order; - -namespace eShop.ClientApp.Services.AppEnvironment; - -public class AppEnvironmentService : IAppEnvironmentService -{ - private readonly IBasketService _basketService; - private readonly ICatalogService _catalogService; - private readonly IIdentityService _identityService; - private readonly IBasketService _mockBasketService; - - private readonly ICatalogService _mockCatalogService; - - private readonly IIdentityService _mockIdentityService; - - private readonly IOrderService _mockOrderService; - private readonly IOrderService _orderService; - - public AppEnvironmentService( - IBasketService mockBasketService, IBasketService basketService, - ICatalogService mockCatalogService, ICatalogService catalogService, - IOrderService mockOrderService, IOrderService orderService, - IIdentityService mockIdentityService, IIdentityService identityService) - { - _mockBasketService = mockBasketService; - _basketService = basketService; - - _mockCatalogService = mockCatalogService; - _catalogService = catalogService; - - _mockOrderService = mockOrderService; - _orderService = orderService; - - _mockIdentityService = mockIdentityService; - _identityService = identityService; - } - - public IBasketService BasketService { get; private set; } - - public ICatalogService CatalogService { get; private set; } - - public IOrderService OrderService { get; private set; } - - public IIdentityService IdentityService { get; private set; } - - public void UpdateDependencies(bool useMockServices) - { - if (useMockServices) - { - BasketService = _mockBasketService; - CatalogService = _mockCatalogService; - OrderService = _mockOrderService; - IdentityService = _mockIdentityService; - } - else - { - BasketService = _basketService; - CatalogService = _catalogService; - OrderService = _orderService; - IdentityService = _identityService; - } - } -} diff --git a/src/ClientApp/Services/AppEnvironment/IAppEnvironmentService.cs b/src/ClientApp/Services/AppEnvironment/IAppEnvironmentService.cs deleted file mode 100644 index 909767c6b..000000000 --- a/src/ClientApp/Services/AppEnvironment/IAppEnvironmentService.cs +++ /dev/null @@ -1,19 +0,0 @@ -using eShop.ClientApp.Services.Basket; -using eShop.ClientApp.Services.Catalog; -using eShop.ClientApp.Services.Identity; -using eShop.ClientApp.Services.Order; - -namespace eShop.ClientApp.Services.AppEnvironment; - -public interface IAppEnvironmentService -{ - IBasketService BasketService { get; } - - ICatalogService CatalogService { get; } - - IOrderService OrderService { get; } - - IIdentityService IdentityService { get; } - - void UpdateDependencies(bool useMockServices); -} diff --git a/src/ClientApp/Services/Basket/BasketMockService.cs b/src/ClientApp/Services/Basket/BasketMockService.cs deleted file mode 100644 index e954381db..000000000 --- a/src/ClientApp/Services/Basket/BasketMockService.cs +++ /dev/null @@ -1,59 +0,0 @@ -using eShop.ClientApp.Models.Basket; - -namespace eShop.ClientApp.Services.Basket; - -public class BasketMockService : IBasketService -{ - private CustomerBasket _mockCustomBasket; - - public BasketMockService() - { - _mockCustomBasket = new CustomerBasket {BuyerId = "9245fe4a-d402-451c-b9ed-9c1a04247482"}; - _mockCustomBasket.AddItemToBasket(new BasketItem - { - Id = "1", - PictureUrl = "fake_product_01.png", - ProductId = Common.Common.MockCatalogItemId01, - ProductName = ".NET Bot Blue Sweatshirt (M)", - Quantity = 1, - UnitPrice = 19.50M - }); - - _mockCustomBasket.AddItemToBasket(new BasketItem - { - Id = "2", - PictureUrl = "fake_product_04.png", - ProductId = Common.Common.MockCatalogItemId04, - ProductName = ".NET Black Cup", - Quantity = 1, - UnitPrice = 17.00M - }); - } - - public IEnumerable LocalBasketItems { get; set; } - - public async Task GetBasketAsync() - { - await Task.Delay(10); - - return _mockCustomBasket; - } - - public async Task UpdateBasketAsync(CustomerBasket customerBasket) - { - await Task.Delay(10); - - _mockCustomBasket = customerBasket; - - return _mockCustomBasket; - } - - public async Task ClearBasketAsync() - { - await Task.Delay(10); - - _mockCustomBasket.ClearBasket(); - - LocalBasketItems = null; - } -} diff --git a/src/ClientApp/Services/Basket/BasketService.cs b/src/ClientApp/Services/Basket/BasketService.cs deleted file mode 100644 index 6772b649a..000000000 --- a/src/ClientApp/Services/Basket/BasketService.cs +++ /dev/null @@ -1,151 +0,0 @@ -using eShop.ClientApp.BasketGrpcClient; -using eShop.ClientApp.Models.Basket; -using eShop.ClientApp.Services.FixUri; -using eShop.ClientApp.Services.Identity; -using eShop.ClientApp.Services.Settings; -using Google.Protobuf; -using Grpc.Core; -using Grpc.Net.Client; -using BasketItem = eShop.ClientApp.Models.Basket.BasketItem; - -namespace eShop.ClientApp.Services.Basket; - -public class BasketService : IBasketService, IDisposable -{ - private readonly IFixUriService _fixUriService; - private readonly IIdentityService _identityService; - private readonly ISettingsService _settingsService; - private BasketGrpcClient.Basket.BasketClient _basketClient; - - private GrpcChannel _channel; - - public BasketService(IIdentityService identityService, ISettingsService settingsService, - IFixUriService fixUriService) - { - _identityService = identityService; - _settingsService = settingsService; - _fixUriService = fixUriService; - } - - public IEnumerable LocalBasketItems { get; set; } - - public async Task GetBasketAsync() - { - CustomerBasket basket = new(); - - var authToken = await _identityService.GetAuthTokenAsync().ConfigureAwait(false); - - if (string.IsNullOrEmpty(authToken)) - { - return basket; - } - - try - { - var basketResponse = await GetBasketClient() - .GetBasketAsync(new GetBasketRequest(), CreateAuthenticationHeaders(authToken)); - - if (basketResponse.IsInitialized() && basketResponse.Items.Any()) - { - foreach (var item in basketResponse.Items) - { - basket.AddItemToBasket(new BasketItem {ProductId = item.ProductId, Quantity = item.Quantity}); - } - } - } - catch (Exception exception) - { - Console.WriteLine(exception); - basket = null; - } - - _fixUriService.FixBasketItemPictureUri(basket?.Items); - return basket; - } - - public async Task UpdateBasketAsync(CustomerBasket customerBasket) - { - var authToken = await _identityService.GetAuthTokenAsync().ConfigureAwait(false); - - if (string.IsNullOrEmpty(authToken)) - { - return customerBasket; - } - - var updateBasketRequest = new UpdateBasketRequest(); - - updateBasketRequest.Items.Add( - customerBasket.Items - .Select( - x => - new BasketGrpcClient.BasketItem {ProductId = x.ProductId, Quantity = x.Quantity})); - - var result = await GetBasketClient() - .UpdateBasketAsync(updateBasketRequest, CreateAuthenticationHeaders(authToken)).ConfigureAwait(false); - - if (result.Items.Count > 0) - { - customerBasket.ClearBasket(); - } - - foreach (var item in result.Items) - { - customerBasket.AddItemToBasket(new BasketItem {ProductId = item.ProductId, Quantity = item.Quantity}); - } - - return customerBasket; - } - - public async Task ClearBasketAsync() - { - var authToken = await _identityService.GetAuthTokenAsync().ConfigureAwait(false); - - if (string.IsNullOrEmpty(authToken)) - { - return; - } - - await GetBasketClient().DeleteBasketAsync(new DeleteBasketRequest(), CreateAuthenticationHeaders(authToken)) - .ConfigureAwait(false); - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - private BasketGrpcClient.Basket.BasketClient GetBasketClient() - { - if (_basketClient is not null) - { - return _basketClient; - } - - _channel = GrpcChannel.ForAddress(_settingsService.GatewayBasketEndpointBase); - - _basketClient = new BasketGrpcClient.Basket.BasketClient(_channel); - - return _basketClient; - } - - private Metadata CreateAuthenticationHeaders(string token) - { - var headers = new Metadata(); - headers.Add("authorization", $"Bearer {token}"); - return headers; - } - - protected virtual void Dispose(bool disposing) - { - if (disposing) - { - _channel?.Dispose(); - } - } - - ~BasketService() - { - Dispose(false); - } -} diff --git a/src/ClientApp/Services/Basket/IBasketService.cs b/src/ClientApp/Services/Basket/IBasketService.cs deleted file mode 100644 index 615ea8aed..000000000 --- a/src/ClientApp/Services/Basket/IBasketService.cs +++ /dev/null @@ -1,11 +0,0 @@ -using eShop.ClientApp.Models.Basket; - -namespace eShop.ClientApp.Services.Basket; - -public interface IBasketService -{ - IEnumerable LocalBasketItems { get; set; } - Task GetBasketAsync(); - Task UpdateBasketAsync(CustomerBasket customerBasket); - Task ClearBasketAsync(); -} diff --git a/src/ClientApp/Services/Basket/Protos/Basket.cs b/src/ClientApp/Services/Basket/Protos/Basket.cs deleted file mode 100644 index d725f4527..000000000 --- a/src/ClientApp/Services/Basket/Protos/Basket.cs +++ /dev/null @@ -1,1152 +0,0 @@ -// -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: Services/Basket/Protos/basket.proto -// -#pragma warning disable 1591, 0612, 3021, 8981 -#region Designer generated code - -using pb = global::Google.Protobuf; -using pbc = global::Google.Protobuf.Collections; -using pbr = global::Google.Protobuf.Reflection; -using scg = global::System.Collections.Generic; -namespace eShop.ClientApp.BasketGrpcClient { - - /// Holder for reflection information generated from Services/Basket/Protos/basket.proto - public static partial class BasketReflection { - - #region Descriptor - /// File descriptor for Services/Basket/Protos/basket.proto - public static pbr::FileDescriptor Descriptor { - get { return descriptor; } - } - private static pbr::FileDescriptor descriptor; - - static BasketReflection() { - byte[] descriptorData = global::System.Convert.FromBase64String( - string.Concat( - "CiNTZXJ2aWNlcy9CYXNrZXQvUHJvdG9zL2Jhc2tldC5wcm90bxIJQmFza2V0", - "QXBpIhIKEEdldEJhc2tldFJlcXVlc3QiPgoWQ3VzdG9tZXJCYXNrZXRSZXNw", - "b25zZRIkCgVpdGVtcxgBIAMoCzIVLkJhc2tldEFwaS5CYXNrZXRJdGVtIjIK", - "CkJhc2tldEl0ZW0SEgoKcHJvZHVjdF9pZBgCIAEoBRIQCghxdWFudGl0eRgG", - "IAEoBSI7ChNVcGRhdGVCYXNrZXRSZXF1ZXN0EiQKBWl0ZW1zGAIgAygLMhUu", - "QmFza2V0QXBpLkJhc2tldEl0ZW0iFQoTRGVsZXRlQmFza2V0UmVxdWVzdCIW", - "ChREZWxldGVCYXNrZXRSZXNwb25zZTL/AQoGQmFza2V0Ek0KCUdldEJhc2tl", - "dBIbLkJhc2tldEFwaS5HZXRCYXNrZXRSZXF1ZXN0GiEuQmFza2V0QXBpLkN1", - "c3RvbWVyQmFza2V0UmVzcG9uc2UiABJTCgxVcGRhdGVCYXNrZXQSHi5CYXNr", - "ZXRBcGkuVXBkYXRlQmFza2V0UmVxdWVzdBohLkJhc2tldEFwaS5DdXN0b21l", - "ckJhc2tldFJlc3BvbnNlIgASUQoMRGVsZXRlQmFza2V0Eh4uQmFza2V0QXBp", - "LkRlbGV0ZUJhc2tldFJlcXVlc3QaHy5CYXNrZXRBcGkuRGVsZXRlQmFza2V0", - "UmVzcG9uc2UiAEIjqgIgZVNob3AuQ2xpZW50QXBwLkJhc2tldEdycGNDbGll", - "bnRiBnByb3RvMw==")); - descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, - new pbr::FileDescriptor[] { }, - new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { - new pbr::GeneratedClrTypeInfo(typeof(global::eShop.ClientApp.BasketGrpcClient.GetBasketRequest), global::eShop.ClientApp.BasketGrpcClient.GetBasketRequest.Parser, null, null, null, null, null), - new pbr::GeneratedClrTypeInfo(typeof(global::eShop.ClientApp.BasketGrpcClient.CustomerBasketResponse), global::eShop.ClientApp.BasketGrpcClient.CustomerBasketResponse.Parser, new[]{ "Items" }, null, null, null, null), - new pbr::GeneratedClrTypeInfo(typeof(global::eShop.ClientApp.BasketGrpcClient.BasketItem), global::eShop.ClientApp.BasketGrpcClient.BasketItem.Parser, new[]{ "ProductId", "Quantity" }, null, null, null, null), - new pbr::GeneratedClrTypeInfo(typeof(global::eShop.ClientApp.BasketGrpcClient.UpdateBasketRequest), global::eShop.ClientApp.BasketGrpcClient.UpdateBasketRequest.Parser, new[]{ "Items" }, null, null, null, null), - new pbr::GeneratedClrTypeInfo(typeof(global::eShop.ClientApp.BasketGrpcClient.DeleteBasketRequest), global::eShop.ClientApp.BasketGrpcClient.DeleteBasketRequest.Parser, null, null, null, null, null), - new pbr::GeneratedClrTypeInfo(typeof(global::eShop.ClientApp.BasketGrpcClient.DeleteBasketResponse), global::eShop.ClientApp.BasketGrpcClient.DeleteBasketResponse.Parser, null, null, null, null, null) - })); - } - #endregion - - } - #region Messages - [global::System.Diagnostics.DebuggerDisplayAttribute("{ToString(),nq}")] - public sealed partial class GetBasketRequest : pb::IMessage - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - , pb::IBufferMessage - #endif - { - private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new GetBasketRequest()); - private pb::UnknownFieldSet _unknownFields; - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public static pb::MessageParser Parser { get { return _parser; } } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public static pbr::MessageDescriptor Descriptor { - get { return global::eShop.ClientApp.BasketGrpcClient.BasketReflection.Descriptor.MessageTypes[0]; } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - pbr::MessageDescriptor pb::IMessage.Descriptor { - get { return Descriptor; } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public GetBasketRequest() { - OnConstruction(); - } - - partial void OnConstruction(); - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public GetBasketRequest(GetBasketRequest other) : this() { - _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public GetBasketRequest Clone() { - return new GetBasketRequest(this); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override bool Equals(object other) { - return Equals(other as GetBasketRequest); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public bool Equals(GetBasketRequest other) { - if (ReferenceEquals(other, null)) { - return false; - } - if (ReferenceEquals(other, this)) { - return true; - } - return Equals(_unknownFields, other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override int GetHashCode() { - int hash = 1; - if (_unknownFields != null) { - hash ^= _unknownFields.GetHashCode(); - } - return hash; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override string ToString() { - return pb::JsonFormatter.ToDiagnosticString(this); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void WriteTo(pb::CodedOutputStream output) { - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - output.WriteRawMessage(this); - #else - if (_unknownFields != null) { - _unknownFields.WriteTo(output); - } - #endif - } - - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { - if (_unknownFields != null) { - _unknownFields.WriteTo(ref output); - } - } - #endif - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public int CalculateSize() { - int size = 0; - if (_unknownFields != null) { - size += _unknownFields.CalculateSize(); - } - return size; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void MergeFrom(GetBasketRequest other) { - if (other == null) { - return; - } - _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void MergeFrom(pb::CodedInputStream input) { - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - input.ReadRawMessage(this); - #else - uint tag; - while ((tag = input.ReadTag()) != 0) { - if ((tag & 7) == 4) { - // Abort on any end group tag. - return; - } - switch(tag) { - default: - _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); - break; - } - } - #endif - } - - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { - uint tag; - while ((tag = input.ReadTag()) != 0) { - if ((tag & 7) == 4) { - // Abort on any end group tag. - return; - } - switch(tag) { - default: - _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); - break; - } - } - } - #endif - - } - - [global::System.Diagnostics.DebuggerDisplayAttribute("{ToString(),nq}")] - public sealed partial class CustomerBasketResponse : pb::IMessage - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - , pb::IBufferMessage - #endif - { - private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new CustomerBasketResponse()); - private pb::UnknownFieldSet _unknownFields; - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public static pb::MessageParser Parser { get { return _parser; } } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public static pbr::MessageDescriptor Descriptor { - get { return global::eShop.ClientApp.BasketGrpcClient.BasketReflection.Descriptor.MessageTypes[1]; } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - pbr::MessageDescriptor pb::IMessage.Descriptor { - get { return Descriptor; } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public CustomerBasketResponse() { - OnConstruction(); - } - - partial void OnConstruction(); - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public CustomerBasketResponse(CustomerBasketResponse other) : this() { - items_ = other.items_.Clone(); - _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public CustomerBasketResponse Clone() { - return new CustomerBasketResponse(this); - } - - /// Field number for the "items" field. - public const int ItemsFieldNumber = 1; - private static readonly pb::FieldCodec _repeated_items_codec - = pb::FieldCodec.ForMessage(10, global::eShop.ClientApp.BasketGrpcClient.BasketItem.Parser); - private readonly pbc::RepeatedField items_ = new pbc::RepeatedField(); - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public pbc::RepeatedField Items { - get { return items_; } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override bool Equals(object other) { - return Equals(other as CustomerBasketResponse); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public bool Equals(CustomerBasketResponse other) { - if (ReferenceEquals(other, null)) { - return false; - } - if (ReferenceEquals(other, this)) { - return true; - } - if(!items_.Equals(other.items_)) return false; - return Equals(_unknownFields, other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override int GetHashCode() { - int hash = 1; - hash ^= items_.GetHashCode(); - if (_unknownFields != null) { - hash ^= _unknownFields.GetHashCode(); - } - return hash; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override string ToString() { - return pb::JsonFormatter.ToDiagnosticString(this); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void WriteTo(pb::CodedOutputStream output) { - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - output.WriteRawMessage(this); - #else - items_.WriteTo(output, _repeated_items_codec); - if (_unknownFields != null) { - _unknownFields.WriteTo(output); - } - #endif - } - - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { - items_.WriteTo(ref output, _repeated_items_codec); - if (_unknownFields != null) { - _unknownFields.WriteTo(ref output); - } - } - #endif - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public int CalculateSize() { - int size = 0; - size += items_.CalculateSize(_repeated_items_codec); - if (_unknownFields != null) { - size += _unknownFields.CalculateSize(); - } - return size; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void MergeFrom(CustomerBasketResponse other) { - if (other == null) { - return; - } - items_.Add(other.items_); - _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void MergeFrom(pb::CodedInputStream input) { - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - input.ReadRawMessage(this); - #else - uint tag; - while ((tag = input.ReadTag()) != 0) { - if ((tag & 7) == 4) { - // Abort on any end group tag. - return; - } - switch(tag) { - default: - _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); - break; - case 10: { - items_.AddEntriesFrom(input, _repeated_items_codec); - break; - } - } - } - #endif - } - - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { - uint tag; - while ((tag = input.ReadTag()) != 0) { - if ((tag & 7) == 4) { - // Abort on any end group tag. - return; - } - switch(tag) { - default: - _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); - break; - case 10: { - items_.AddEntriesFrom(ref input, _repeated_items_codec); - break; - } - } - } - } - #endif - - } - - [global::System.Diagnostics.DebuggerDisplayAttribute("{ToString(),nq}")] - public sealed partial class BasketItem : pb::IMessage - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - , pb::IBufferMessage - #endif - { - private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new BasketItem()); - private pb::UnknownFieldSet _unknownFields; - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public static pb::MessageParser Parser { get { return _parser; } } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public static pbr::MessageDescriptor Descriptor { - get { return global::eShop.ClientApp.BasketGrpcClient.BasketReflection.Descriptor.MessageTypes[2]; } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - pbr::MessageDescriptor pb::IMessage.Descriptor { - get { return Descriptor; } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public BasketItem() { - OnConstruction(); - } - - partial void OnConstruction(); - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public BasketItem(BasketItem other) : this() { - productId_ = other.productId_; - quantity_ = other.quantity_; - _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public BasketItem Clone() { - return new BasketItem(this); - } - - /// Field number for the "product_id" field. - public const int ProductIdFieldNumber = 2; - private int productId_; - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public int ProductId { - get { return productId_; } - set { - productId_ = value; - } - } - - /// Field number for the "quantity" field. - public const int QuantityFieldNumber = 6; - private int quantity_; - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public int Quantity { - get { return quantity_; } - set { - quantity_ = value; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override bool Equals(object other) { - return Equals(other as BasketItem); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public bool Equals(BasketItem other) { - if (ReferenceEquals(other, null)) { - return false; - } - if (ReferenceEquals(other, this)) { - return true; - } - if (ProductId != other.ProductId) return false; - if (Quantity != other.Quantity) return false; - return Equals(_unknownFields, other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override int GetHashCode() { - int hash = 1; - if (ProductId != 0) hash ^= ProductId.GetHashCode(); - if (Quantity != 0) hash ^= Quantity.GetHashCode(); - if (_unknownFields != null) { - hash ^= _unknownFields.GetHashCode(); - } - return hash; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override string ToString() { - return pb::JsonFormatter.ToDiagnosticString(this); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void WriteTo(pb::CodedOutputStream output) { - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - output.WriteRawMessage(this); - #else - if (ProductId != 0) { - output.WriteRawTag(16); - output.WriteInt32(ProductId); - } - if (Quantity != 0) { - output.WriteRawTag(48); - output.WriteInt32(Quantity); - } - if (_unknownFields != null) { - _unknownFields.WriteTo(output); - } - #endif - } - - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { - if (ProductId != 0) { - output.WriteRawTag(16); - output.WriteInt32(ProductId); - } - if (Quantity != 0) { - output.WriteRawTag(48); - output.WriteInt32(Quantity); - } - if (_unknownFields != null) { - _unknownFields.WriteTo(ref output); - } - } - #endif - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public int CalculateSize() { - int size = 0; - if (ProductId != 0) { - size += 1 + pb::CodedOutputStream.ComputeInt32Size(ProductId); - } - if (Quantity != 0) { - size += 1 + pb::CodedOutputStream.ComputeInt32Size(Quantity); - } - if (_unknownFields != null) { - size += _unknownFields.CalculateSize(); - } - return size; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void MergeFrom(BasketItem other) { - if (other == null) { - return; - } - if (other.ProductId != 0) { - ProductId = other.ProductId; - } - if (other.Quantity != 0) { - Quantity = other.Quantity; - } - _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void MergeFrom(pb::CodedInputStream input) { - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - input.ReadRawMessage(this); - #else - uint tag; - while ((tag = input.ReadTag()) != 0) { - if ((tag & 7) == 4) { - // Abort on any end group tag. - return; - } - switch(tag) { - default: - _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); - break; - case 16: { - ProductId = input.ReadInt32(); - break; - } - case 48: { - Quantity = input.ReadInt32(); - break; - } - } - } - #endif - } - - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { - uint tag; - while ((tag = input.ReadTag()) != 0) { - if ((tag & 7) == 4) { - // Abort on any end group tag. - return; - } - switch(tag) { - default: - _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); - break; - case 16: { - ProductId = input.ReadInt32(); - break; - } - case 48: { - Quantity = input.ReadInt32(); - break; - } - } - } - } - #endif - - } - - [global::System.Diagnostics.DebuggerDisplayAttribute("{ToString(),nq}")] - public sealed partial class UpdateBasketRequest : pb::IMessage - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - , pb::IBufferMessage - #endif - { - private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new UpdateBasketRequest()); - private pb::UnknownFieldSet _unknownFields; - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public static pb::MessageParser Parser { get { return _parser; } } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public static pbr::MessageDescriptor Descriptor { - get { return global::eShop.ClientApp.BasketGrpcClient.BasketReflection.Descriptor.MessageTypes[3]; } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - pbr::MessageDescriptor pb::IMessage.Descriptor { - get { return Descriptor; } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public UpdateBasketRequest() { - OnConstruction(); - } - - partial void OnConstruction(); - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public UpdateBasketRequest(UpdateBasketRequest other) : this() { - items_ = other.items_.Clone(); - _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public UpdateBasketRequest Clone() { - return new UpdateBasketRequest(this); - } - - /// Field number for the "items" field. - public const int ItemsFieldNumber = 2; - private static readonly pb::FieldCodec _repeated_items_codec - = pb::FieldCodec.ForMessage(18, global::eShop.ClientApp.BasketGrpcClient.BasketItem.Parser); - private readonly pbc::RepeatedField items_ = new pbc::RepeatedField(); - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public pbc::RepeatedField Items { - get { return items_; } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override bool Equals(object other) { - return Equals(other as UpdateBasketRequest); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public bool Equals(UpdateBasketRequest other) { - if (ReferenceEquals(other, null)) { - return false; - } - if (ReferenceEquals(other, this)) { - return true; - } - if(!items_.Equals(other.items_)) return false; - return Equals(_unknownFields, other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override int GetHashCode() { - int hash = 1; - hash ^= items_.GetHashCode(); - if (_unknownFields != null) { - hash ^= _unknownFields.GetHashCode(); - } - return hash; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override string ToString() { - return pb::JsonFormatter.ToDiagnosticString(this); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void WriteTo(pb::CodedOutputStream output) { - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - output.WriteRawMessage(this); - #else - items_.WriteTo(output, _repeated_items_codec); - if (_unknownFields != null) { - _unknownFields.WriteTo(output); - } - #endif - } - - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { - items_.WriteTo(ref output, _repeated_items_codec); - if (_unknownFields != null) { - _unknownFields.WriteTo(ref output); - } - } - #endif - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public int CalculateSize() { - int size = 0; - size += items_.CalculateSize(_repeated_items_codec); - if (_unknownFields != null) { - size += _unknownFields.CalculateSize(); - } - return size; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void MergeFrom(UpdateBasketRequest other) { - if (other == null) { - return; - } - items_.Add(other.items_); - _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void MergeFrom(pb::CodedInputStream input) { - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - input.ReadRawMessage(this); - #else - uint tag; - while ((tag = input.ReadTag()) != 0) { - if ((tag & 7) == 4) { - // Abort on any end group tag. - return; - } - switch(tag) { - default: - _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); - break; - case 18: { - items_.AddEntriesFrom(input, _repeated_items_codec); - break; - } - } - } - #endif - } - - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { - uint tag; - while ((tag = input.ReadTag()) != 0) { - if ((tag & 7) == 4) { - // Abort on any end group tag. - return; - } - switch(tag) { - default: - _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); - break; - case 18: { - items_.AddEntriesFrom(ref input, _repeated_items_codec); - break; - } - } - } - } - #endif - - } - - [global::System.Diagnostics.DebuggerDisplayAttribute("{ToString(),nq}")] - public sealed partial class DeleteBasketRequest : pb::IMessage - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - , pb::IBufferMessage - #endif - { - private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new DeleteBasketRequest()); - private pb::UnknownFieldSet _unknownFields; - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public static pb::MessageParser Parser { get { return _parser; } } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public static pbr::MessageDescriptor Descriptor { - get { return global::eShop.ClientApp.BasketGrpcClient.BasketReflection.Descriptor.MessageTypes[4]; } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - pbr::MessageDescriptor pb::IMessage.Descriptor { - get { return Descriptor; } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public DeleteBasketRequest() { - OnConstruction(); - } - - partial void OnConstruction(); - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public DeleteBasketRequest(DeleteBasketRequest other) : this() { - _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public DeleteBasketRequest Clone() { - return new DeleteBasketRequest(this); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override bool Equals(object other) { - return Equals(other as DeleteBasketRequest); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public bool Equals(DeleteBasketRequest other) { - if (ReferenceEquals(other, null)) { - return false; - } - if (ReferenceEquals(other, this)) { - return true; - } - return Equals(_unknownFields, other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override int GetHashCode() { - int hash = 1; - if (_unknownFields != null) { - hash ^= _unknownFields.GetHashCode(); - } - return hash; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override string ToString() { - return pb::JsonFormatter.ToDiagnosticString(this); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void WriteTo(pb::CodedOutputStream output) { - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - output.WriteRawMessage(this); - #else - if (_unknownFields != null) { - _unknownFields.WriteTo(output); - } - #endif - } - - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { - if (_unknownFields != null) { - _unknownFields.WriteTo(ref output); - } - } - #endif - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public int CalculateSize() { - int size = 0; - if (_unknownFields != null) { - size += _unknownFields.CalculateSize(); - } - return size; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void MergeFrom(DeleteBasketRequest other) { - if (other == null) { - return; - } - _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void MergeFrom(pb::CodedInputStream input) { - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - input.ReadRawMessage(this); - #else - uint tag; - while ((tag = input.ReadTag()) != 0) { - if ((tag & 7) == 4) { - // Abort on any end group tag. - return; - } - switch(tag) { - default: - _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); - break; - } - } - #endif - } - - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { - uint tag; - while ((tag = input.ReadTag()) != 0) { - if ((tag & 7) == 4) { - // Abort on any end group tag. - return; - } - switch(tag) { - default: - _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); - break; - } - } - } - #endif - - } - - [global::System.Diagnostics.DebuggerDisplayAttribute("{ToString(),nq}")] - public sealed partial class DeleteBasketResponse : pb::IMessage - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - , pb::IBufferMessage - #endif - { - private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new DeleteBasketResponse()); - private pb::UnknownFieldSet _unknownFields; - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public static pb::MessageParser Parser { get { return _parser; } } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public static pbr::MessageDescriptor Descriptor { - get { return global::eShop.ClientApp.BasketGrpcClient.BasketReflection.Descriptor.MessageTypes[5]; } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - pbr::MessageDescriptor pb::IMessage.Descriptor { - get { return Descriptor; } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public DeleteBasketResponse() { - OnConstruction(); - } - - partial void OnConstruction(); - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public DeleteBasketResponse(DeleteBasketResponse other) : this() { - _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public DeleteBasketResponse Clone() { - return new DeleteBasketResponse(this); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override bool Equals(object other) { - return Equals(other as DeleteBasketResponse); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public bool Equals(DeleteBasketResponse other) { - if (ReferenceEquals(other, null)) { - return false; - } - if (ReferenceEquals(other, this)) { - return true; - } - return Equals(_unknownFields, other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override int GetHashCode() { - int hash = 1; - if (_unknownFields != null) { - hash ^= _unknownFields.GetHashCode(); - } - return hash; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public override string ToString() { - return pb::JsonFormatter.ToDiagnosticString(this); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void WriteTo(pb::CodedOutputStream output) { - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - output.WriteRawMessage(this); - #else - if (_unknownFields != null) { - _unknownFields.WriteTo(output); - } - #endif - } - - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { - if (_unknownFields != null) { - _unknownFields.WriteTo(ref output); - } - } - #endif - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public int CalculateSize() { - int size = 0; - if (_unknownFields != null) { - size += _unknownFields.CalculateSize(); - } - return size; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void MergeFrom(DeleteBasketResponse other) { - if (other == null) { - return; - } - _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - public void MergeFrom(pb::CodedInputStream input) { - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - input.ReadRawMessage(this); - #else - uint tag; - while ((tag = input.ReadTag()) != 0) { - if ((tag & 7) == 4) { - // Abort on any end group tag. - return; - } - switch(tag) { - default: - _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); - break; - } - } - #endif - } - - #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE - [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] - void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { - uint tag; - while ((tag = input.ReadTag()) != 0) { - if ((tag & 7) == 4) { - // Abort on any end group tag. - return; - } - switch(tag) { - default: - _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); - break; - } - } - } - #endif - - } - - #endregion - -} - -#endregion Designer generated code diff --git a/src/ClientApp/Services/Basket/Protos/BasketGrpc.cs b/src/ClientApp/Services/Basket/Protos/BasketGrpc.cs deleted file mode 100644 index 2d3bbf456..000000000 --- a/src/ClientApp/Services/Basket/Protos/BasketGrpc.cs +++ /dev/null @@ -1,186 +0,0 @@ -// -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: Services/Basket/Protos/basket.proto -// -#pragma warning disable 0414, 1591, 8981, 0612 -#region Designer generated code - -using grpc = global::Grpc.Core; - -namespace eShop.ClientApp.BasketGrpcClient { - public static partial class Basket - { - static readonly string __ServiceName = "BasketApi.Basket"; - - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - static void __Helper_SerializeMessage(global::Google.Protobuf.IMessage message, grpc::SerializationContext context) - { - #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION - if (message is global::Google.Protobuf.IBufferMessage) - { - context.SetPayloadLength(message.CalculateSize()); - global::Google.Protobuf.MessageExtensions.WriteTo(message, context.GetBufferWriter()); - context.Complete(); - return; - } - #endif - context.Complete(global::Google.Protobuf.MessageExtensions.ToByteArray(message)); - } - - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - static class __Helper_MessageCache - { - public static readonly bool IsBufferMessage = global::System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(global::Google.Protobuf.IBufferMessage)).IsAssignableFrom(typeof(T)); - } - - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - static T __Helper_DeserializeMessage(grpc::DeserializationContext context, global::Google.Protobuf.MessageParser parser) where T : global::Google.Protobuf.IMessage - { - #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION - if (__Helper_MessageCache.IsBufferMessage) - { - return parser.ParseFrom(context.PayloadAsReadOnlySequence()); - } - #endif - return parser.ParseFrom(context.PayloadAsNewBuffer()); - } - - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - static readonly grpc::Marshaller __Marshaller_BasketApi_GetBasketRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::eShop.ClientApp.BasketGrpcClient.GetBasketRequest.Parser)); - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - static readonly grpc::Marshaller __Marshaller_BasketApi_CustomerBasketResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::eShop.ClientApp.BasketGrpcClient.CustomerBasketResponse.Parser)); - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - static readonly grpc::Marshaller __Marshaller_BasketApi_UpdateBasketRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::eShop.ClientApp.BasketGrpcClient.UpdateBasketRequest.Parser)); - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - static readonly grpc::Marshaller __Marshaller_BasketApi_DeleteBasketRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::eShop.ClientApp.BasketGrpcClient.DeleteBasketRequest.Parser)); - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - static readonly grpc::Marshaller __Marshaller_BasketApi_DeleteBasketResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::eShop.ClientApp.BasketGrpcClient.DeleteBasketResponse.Parser)); - - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - static readonly grpc::Method __Method_GetBasket = new grpc::Method( - grpc::MethodType.Unary, - __ServiceName, - "GetBasket", - __Marshaller_BasketApi_GetBasketRequest, - __Marshaller_BasketApi_CustomerBasketResponse); - - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - static readonly grpc::Method __Method_UpdateBasket = new grpc::Method( - grpc::MethodType.Unary, - __ServiceName, - "UpdateBasket", - __Marshaller_BasketApi_UpdateBasketRequest, - __Marshaller_BasketApi_CustomerBasketResponse); - - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - static readonly grpc::Method __Method_DeleteBasket = new grpc::Method( - grpc::MethodType.Unary, - __ServiceName, - "DeleteBasket", - __Marshaller_BasketApi_DeleteBasketRequest, - __Marshaller_BasketApi_DeleteBasketResponse); - - /// Service descriptor - public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor - { - get { return global::eShop.ClientApp.BasketGrpcClient.BasketReflection.Descriptor.Services[0]; } - } - - /// Client for Basket - public partial class BasketClient : grpc::ClientBase - { - /// Creates a new client for Basket - /// The channel to use to make remote calls. - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - public BasketClient(grpc::ChannelBase channel) : base(channel) - { - } - /// Creates a new client for Basket that uses a custom CallInvoker. - /// The callInvoker to use to make remote calls. - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - public BasketClient(grpc::CallInvoker callInvoker) : base(callInvoker) - { - } - /// Protected parameterless constructor to allow creation of test doubles. - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - protected BasketClient() : base() - { - } - /// Protected constructor to allow creation of configured clients. - /// The client configuration. - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - protected BasketClient(ClientBaseConfiguration configuration) : base(configuration) - { - } - - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - public virtual global::eShop.ClientApp.BasketGrpcClient.CustomerBasketResponse GetBasket(global::eShop.ClientApp.BasketGrpcClient.GetBasketRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) - { - return GetBasket(request, new grpc::CallOptions(headers, deadline, cancellationToken)); - } - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - public virtual global::eShop.ClientApp.BasketGrpcClient.CustomerBasketResponse GetBasket(global::eShop.ClientApp.BasketGrpcClient.GetBasketRequest request, grpc::CallOptions options) - { - return CallInvoker.BlockingUnaryCall(__Method_GetBasket, null, options, request); - } - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - public virtual grpc::AsyncUnaryCall GetBasketAsync(global::eShop.ClientApp.BasketGrpcClient.GetBasketRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) - { - return GetBasketAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); - } - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - public virtual grpc::AsyncUnaryCall GetBasketAsync(global::eShop.ClientApp.BasketGrpcClient.GetBasketRequest request, grpc::CallOptions options) - { - return CallInvoker.AsyncUnaryCall(__Method_GetBasket, null, options, request); - } - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - public virtual global::eShop.ClientApp.BasketGrpcClient.CustomerBasketResponse UpdateBasket(global::eShop.ClientApp.BasketGrpcClient.UpdateBasketRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) - { - return UpdateBasket(request, new grpc::CallOptions(headers, deadline, cancellationToken)); - } - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - public virtual global::eShop.ClientApp.BasketGrpcClient.CustomerBasketResponse UpdateBasket(global::eShop.ClientApp.BasketGrpcClient.UpdateBasketRequest request, grpc::CallOptions options) - { - return CallInvoker.BlockingUnaryCall(__Method_UpdateBasket, null, options, request); - } - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - public virtual grpc::AsyncUnaryCall UpdateBasketAsync(global::eShop.ClientApp.BasketGrpcClient.UpdateBasketRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) - { - return UpdateBasketAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); - } - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - public virtual grpc::AsyncUnaryCall UpdateBasketAsync(global::eShop.ClientApp.BasketGrpcClient.UpdateBasketRequest request, grpc::CallOptions options) - { - return CallInvoker.AsyncUnaryCall(__Method_UpdateBasket, null, options, request); - } - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - public virtual global::eShop.ClientApp.BasketGrpcClient.DeleteBasketResponse DeleteBasket(global::eShop.ClientApp.BasketGrpcClient.DeleteBasketRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) - { - return DeleteBasket(request, new grpc::CallOptions(headers, deadline, cancellationToken)); - } - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - public virtual global::eShop.ClientApp.BasketGrpcClient.DeleteBasketResponse DeleteBasket(global::eShop.ClientApp.BasketGrpcClient.DeleteBasketRequest request, grpc::CallOptions options) - { - return CallInvoker.BlockingUnaryCall(__Method_DeleteBasket, null, options, request); - } - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - public virtual grpc::AsyncUnaryCall DeleteBasketAsync(global::eShop.ClientApp.BasketGrpcClient.DeleteBasketRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) - { - return DeleteBasketAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); - } - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - public virtual grpc::AsyncUnaryCall DeleteBasketAsync(global::eShop.ClientApp.BasketGrpcClient.DeleteBasketRequest request, grpc::CallOptions options) - { - return CallInvoker.AsyncUnaryCall(__Method_DeleteBasket, null, options, request); - } - /// Creates a new instance of client from given ClientBaseConfiguration. - [global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)] - protected override BasketClient NewInstance(ClientBaseConfiguration configuration) - { - return new BasketClient(configuration); - } - } - - } -} -#endregion diff --git a/src/ClientApp/Services/Basket/Protos/basket.proto b/src/ClientApp/Services/Basket/Protos/basket.proto deleted file mode 100644 index 962c56ff1..000000000 --- a/src/ClientApp/Services/Basket/Protos/basket.proto +++ /dev/null @@ -1,33 +0,0 @@ -syntax = "proto3"; - -option csharp_namespace = "eShop.ClientApp.BasketGrpcClient"; - -package BasketApi; - -service Basket { - rpc GetBasket(GetBasketRequest) returns (CustomerBasketResponse) {} - rpc UpdateBasket(UpdateBasketRequest) returns (CustomerBasketResponse) {} - rpc DeleteBasket(DeleteBasketRequest) returns (DeleteBasketResponse) {} -} - -message GetBasketRequest { -} - -message CustomerBasketResponse { - repeated BasketItem items = 1; -} - -message BasketItem { - int32 product_id = 2; - int32 quantity = 6; -} - -message UpdateBasketRequest { - repeated BasketItem items = 2; -} - -message DeleteBasketRequest { -} - -message DeleteBasketResponse { -} \ No newline at end of file diff --git a/src/ClientApp/Services/Catalog/CatalogMockService.cs b/src/ClientApp/Services/Catalog/CatalogMockService.cs deleted file mode 100644 index 0f19e10c0..000000000 --- a/src/ClientApp/Services/Catalog/CatalogMockService.cs +++ /dev/null @@ -1,116 +0,0 @@ -using eShop.ClientApp.Models.Catalog; - -namespace eShop.ClientApp.Services.Catalog; - -public class CatalogMockService : ICatalogService -{ - private static readonly List MockCatalogBrands = - new() {new CatalogBrand {Id = 1, Brand = "Azure"}, new CatalogBrand {Id = 2, Brand = "Visual Studio"}}; - - private static readonly List MockCatalogTypes = - new() {new CatalogType {Id = 1, Type = "Mug"}, new CatalogType {Id = 2, Type = "T-Shirt"}}; - - private static readonly List MockCatalog = - new() - { - new CatalogItem - { - Id = Common.Common.MockCatalogItemId01, - PictureUri = "fake_product_01.png", - Name = "Adventurer GPS Watch", - Price = 199.99M, - CatalogBrandId = 2, - CatalogBrand = MockCatalogBrands[1], - CatalogTypeId = 2, - CatalogType = MockCatalogTypes[1], - Description = "Navigate with confidence using the Adventurer GPS Watch by Adventurer. This rugged and durable watch features a built-in GPS, altimeter, and compass, allowing you to track your progress and find your way in any terrain. With its sleek black design and easy-to-read display, this watch is both stylish and practical. The Adventurer GPS Watch is a must-have for every adventurer." - }, - new CatalogItem - { - Id = Common.Common.MockCatalogItemId02, - PictureUri = "fake_product_02.png", - Name = "AeroLite Cycling Helmet", - Price = 129.99M, - CatalogBrandId = 2, - CatalogBrand = MockCatalogBrands[1], - CatalogTypeId = 2, - CatalogType = MockCatalogTypes[1], - Description = "Stay safe on your cycling adventures with the Trailblazer Bike Helmet by Green Equipment. This lightweight and durable helmet features an adjustable fit system and ventilation for added comfort. With its vibrant green color and sleek design, you'll stand out on the road. The Trailblazer Bike Helmet is perfect for all types of cycling, from mountain biking to road cycling." - }, - new CatalogItem - { - Id = Common.Common.MockCatalogItemId03, - PictureUri = "fake_product_03.png", - Name = "Alpine AlpinePack Backpack", - Price = 129.00M, - CatalogBrandId = 2, - CatalogBrand = MockCatalogBrands[1], - CatalogTypeId = 2, - CatalogType = MockCatalogTypes[1], - Description = "The AlpinePack backpack by Green Equipment is your ultimate companion for outdoor adventures. This versatile and durable backpack features a sleek navy design with reinforced straps. With a capacity of 45 liters, multiple compartments, and a hydration pack sleeve, it offers ample storage and organization. The ergonomic back panel ensures maximum comfort, even on the most challenging treks." - }, - new CatalogItem - { - Id = Common.Common.MockCatalogItemId04, - PictureUri = "fake_product_04.png", - Name = "Alpine Fusion Goggles", - Price = 79.99M, - CatalogBrandId = 2, - CatalogBrand = MockCatalogBrands[1], - CatalogTypeId = 1, - CatalogType = MockCatalogTypes[0], - Description = "Enhance your skiing experience with the Alpine Fusion Goggles from WildRunner. These goggles offer full UV protection and anti-fog lenses to keep your vision clear on the slopes. With their stylish silver frame and orange lenses, you'll stand out from the crowd. Adjustable straps ensure a secure fit, while the soft foam padding provides comfort all day long." - }, - new CatalogItem - { - Id = Common.Common.MockCatalogItemId05, - PictureUri = "fake_product_05.png", - Name = "Alpine PeakDown Jacket", - Price = 249.99M, - CatalogBrandId = 1, - CatalogBrand = MockCatalogBrands[0], - CatalogTypeId = 2, - CatalogType = MockCatalogTypes[1], - Description = "The Solstix Alpine Peak Down Jacket is crafted for extreme cold conditions. With its bold red color and sleek design, this jacket combines style with functionality. Made with high-quality goose down insulation, the Alpine Peak Jacket provides exceptional warmth and comfort. The jacket features a removable hood, adjustable cuffs, and multiple zippered pockets for storage. Conquer the harshest weather with the Solstix Alpine Peak Down Jacket." - } - }; - - public async Task> GetCatalogAsync() - { - await Task.Delay(10); - - return MockCatalog; - } - - public async Task GetCatalogItemAsync(int catalogItemId) - { - await Task.Delay(10); - - return MockCatalog.FirstOrDefault(x => x.Id == catalogItemId); - } - - public async Task> FilterAsync(int catalogBrandId, int catalogTypeId) - { - await Task.Delay(10); - - return MockCatalog - .Where( - c => c.CatalogBrandId == catalogBrandId && - c.CatalogTypeId == catalogTypeId) - .ToArray(); - } - - public async Task> GetCatalogBrandAsync() - { - await Task.Delay(10); - - return MockCatalogBrands; - } - - public async Task> GetCatalogTypeAsync() - { - await Task.Delay(10); - - return MockCatalogTypes; - } -} diff --git a/src/ClientApp/Services/Catalog/CatalogService.cs b/src/ClientApp/Services/Catalog/CatalogService.cs deleted file mode 100644 index 174690457..000000000 --- a/src/ClientApp/Services/Catalog/CatalogService.cs +++ /dev/null @@ -1,84 +0,0 @@ -using eShop.ClientApp.Helpers; -using eShop.ClientApp.Models.Catalog; -using eShop.ClientApp.Services.FixUri; -using eShop.ClientApp.Services.RequestProvider; -using eShop.ClientApp.Services.Settings; - -namespace eShop.ClientApp.Services.Catalog; - -public class CatalogService : ICatalogService -{ - private const string ApiUrlBase = "api/catalog"; - private const string ApiVersion = "api-version=2.0"; - - private readonly IFixUriService _fixUriService; - private readonly IRequestProvider _requestProvider; - private readonly ISettingsService _settingsService; - - public CatalogService(ISettingsService settingsService, IRequestProvider requestProvider, - IFixUriService fixUriService) - { - _settingsService = settingsService; - _requestProvider = requestProvider; - _fixUriService = fixUriService; - } - - public async Task> FilterAsync(int catalogBrandId, int catalogTypeId) - { - var uri = UriHelper.CombineUri(_settingsService.GatewayCatalogEndpointBase, - $"{ApiUrlBase}//items?type={catalogTypeId}&brand={catalogBrandId}&PageSize=100&PageIndex=0&{ApiVersion}"); - - var catalog = await _requestProvider.GetAsync(uri).ConfigureAwait(false); - - return catalog?.Data ?? Enumerable.Empty(); - } - - public async Task> GetCatalogAsync() - { - var uri = UriHelper.CombineUri(_settingsService.GatewayCatalogEndpointBase, $"{ApiUrlBase}/items?PageSize=100&{ApiVersion}"); - - var catalog = await _requestProvider.GetAsync(uri).ConfigureAwait(false); - - if (catalog?.Data != null) - { - _fixUriService.FixCatalogItemPictureUri(catalog.Data); - return catalog.Data; - } - - return Enumerable.Empty(); - } - - public async Task GetCatalogItemAsync(int catalogItemId) - { - var uri = UriHelper.CombineUri(_settingsService.GatewayCatalogEndpointBase, - $"{ApiUrlBase}/items/{catalogItemId}?{ApiVersion}"); - - var catalogItem = await _requestProvider.GetAsync(uri).ConfigureAwait(false); - - if (catalogItem != null) - { - _fixUriService.FixCatalogItemPictureUri(new[] {catalogItem}); - return catalogItem; - } - - return default; - } - - public async Task> GetCatalogBrandAsync() - { - var uri = UriHelper.CombineUri(_settingsService.GatewayCatalogEndpointBase, $"{ApiUrlBase}/catalogbrands?{ApiVersion}"); - - var brands = await _requestProvider.GetAsync>(uri).ConfigureAwait(false); - - return brands?.ToArray() ?? Enumerable.Empty(); - } - - public async Task> GetCatalogTypeAsync() - { - var uri = UriHelper.CombineUri(_settingsService.GatewayCatalogEndpointBase, $"{ApiUrlBase}/catalogtypes?{ApiVersion}"); - - var types = await _requestProvider.GetAsync>(uri).ConfigureAwait(false); - - return types?.ToArray() ?? Enumerable.Empty(); - } -} diff --git a/src/ClientApp/Services/Catalog/ICatalogService.cs b/src/ClientApp/Services/Catalog/ICatalogService.cs deleted file mode 100644 index 1d8c7b326..000000000 --- a/src/ClientApp/Services/Catalog/ICatalogService.cs +++ /dev/null @@ -1,13 +0,0 @@ -using eShop.ClientApp.Models.Catalog; - -namespace eShop.ClientApp.Services.Catalog; - -public interface ICatalogService -{ - Task> GetCatalogBrandAsync(); - Task> FilterAsync(int catalogBrandId, int catalogTypeId); - Task> GetCatalogTypeAsync(); - Task> GetCatalogAsync(); - - Task GetCatalogItemAsync(int catalogItemId); -} diff --git a/src/ClientApp/Services/Common/Common.cs b/src/ClientApp/Services/Common/Common.cs deleted file mode 100644 index b51fa3139..000000000 --- a/src/ClientApp/Services/Common/Common.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace eShop.ClientApp.Services.Common; - -public static class Common -{ - public static int MockCatalogItemId01 = 1; - public static int MockCatalogItemId02 = 2; - public static int MockCatalogItemId03 = 3; - public static int MockCatalogItemId04 = 4; - public static int MockCatalogItemId05 = 5; - - public static int MockCampaignId01 = 1; - public static int MockCampaignId02 = 2; -} diff --git a/src/ClientApp/Services/Dialog/DialogService.cs b/src/ClientApp/Services/Dialog/DialogService.cs deleted file mode 100644 index 6db4706d9..000000000 --- a/src/ClientApp/Services/Dialog/DialogService.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace eShop.ClientApp.Services; - -public class DialogService : IDialogService -{ - public Task ShowAlertAsync(string message, string title, string buttonLabel) - { - return AppShell.Current.DisplayAlert(title, message, buttonLabel); - } -} diff --git a/src/ClientApp/Services/Dialog/IDialogService.cs b/src/ClientApp/Services/Dialog/IDialogService.cs deleted file mode 100644 index a5f3a23e2..000000000 --- a/src/ClientApp/Services/Dialog/IDialogService.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace eShop.ClientApp.Services; - -public interface IDialogService -{ - Task ShowAlertAsync(string message, string title, string buttonLabel); -} diff --git a/src/ClientApp/Services/EShopJsonSerializerContext.cs b/src/ClientApp/Services/EShopJsonSerializerContext.cs deleted file mode 100644 index a8a2b97e6..000000000 --- a/src/ClientApp/Services/EShopJsonSerializerContext.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Text.Json.Serialization; -using eShop.ClientApp.Models.Catalog; -using eShop.ClientApp.Models.Orders; -using eShop.ClientApp.Models.Token; - -namespace eShop.ClientApp.Services; - -[JsonSourceGenerationOptions( - PropertyNameCaseInsensitive = true, - NumberHandling = JsonNumberHandling.AllowReadingFromString)] -[JsonSerializable(typeof(CancelOrderCommand))] -[JsonSerializable(typeof(CatalogBrand))] -[JsonSerializable(typeof(CatalogItem))] -[JsonSerializable(typeof(CatalogRoot))] -[JsonSerializable(typeof(CatalogType))] -[JsonSerializable(typeof(Models.Orders.Order))] -[JsonSerializable(typeof(Models.Location.Location))] -[JsonSerializable(typeof(UserToken))] -internal partial class EShopJsonSerializerContext : JsonSerializerContext -{ -} diff --git a/src/ClientApp/Services/FixUri/FixUriService.cs b/src/ClientApp/Services/FixUri/FixUriService.cs deleted file mode 100644 index d518b7688..000000000 --- a/src/ClientApp/Services/FixUri/FixUriService.cs +++ /dev/null @@ -1,108 +0,0 @@ -using System.Diagnostics; -using System.Text.RegularExpressions; -using eShop.ClientApp.Models.Basket; -using eShop.ClientApp.Models.Catalog; -using eShop.ClientApp.Models.Marketing; -using eShop.ClientApp.Services.Settings; - -namespace eShop.ClientApp.Services.FixUri; - -public class FixUriService : IFixUriService -{ - private const string ApiVersion = "api-version=2.0"; - - private readonly ISettingsService _settingsService; - - private readonly Regex IpRegex = new(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"); - - public FixUriService(ISettingsService settingsService) - { - _settingsService = settingsService; - } - - public void FixCatalogItemPictureUri(IEnumerable catalogItems) - { - if (catalogItems is null) - { - return; - } - - try - { - if (!_settingsService.UseMocks && _settingsService.GatewayCatalogEndpointBase != _settingsService.DefaultEndpoint) - { - foreach (var catalogItem in catalogItems) - { - catalogItem.PictureUri = Path.Combine(_settingsService.GatewayCatalogEndpointBase, $"api/catalog/items/{catalogItem.Id}/pic?{ApiVersion}"); - } - } - } - catch (Exception ex) - { - Debug.WriteLine(ex.Message); - } - } - - public void FixBasketItemPictureUri(IEnumerable basketItems) - { - if (basketItems is null) - { - return; - } - - try - { - if (!_settingsService.UseMocks && _settingsService.IdentityEndpointBase != _settingsService.DefaultEndpoint) - { - foreach (var basketItem in basketItems) - { - var serverResult = IpRegex.Matches(basketItem.PictureUrl); - var localResult = IpRegex.Matches(_settingsService.IdentityEndpointBase); - - if (serverResult.Count != -1 && localResult.Count != -1) - { - var serviceIp = serverResult[0].Value; - var localIp = localResult[0].Value; - basketItem.PictureUrl = basketItem.PictureUrl.Replace(serviceIp, localIp); - } - } - } - } - catch (Exception ex) - { - Debug.WriteLine(ex.Message); - } - } - - public void FixCampaignItemPictureUri(IEnumerable campaignItems) - { - if (campaignItems is null) - { - return; - } - - try - { - if (!_settingsService.UseMocks && _settingsService.IdentityEndpointBase != _settingsService.DefaultEndpoint) - { - foreach (var campaignItem in campaignItems) - { - var serverResult = IpRegex.Matches(campaignItem.PictureUri); - var localResult = IpRegex.Matches(_settingsService.IdentityEndpointBase); - - if (serverResult.Count != -1 && localResult.Count != -1) - { - var serviceIp = serverResult[0].Value; - var localIp = localResult[0].Value; - - campaignItem.PictureUri = campaignItem.PictureUri.Replace(serviceIp, localIp); - } - } - } - } - catch (Exception ex) - { - Debug.WriteLine(ex.Message); - } - } -} diff --git a/src/ClientApp/Services/FixUri/IFixUriService.cs b/src/ClientApp/Services/FixUri/IFixUriService.cs deleted file mode 100644 index 6420adbd7..000000000 --- a/src/ClientApp/Services/FixUri/IFixUriService.cs +++ /dev/null @@ -1,12 +0,0 @@ -using eShop.ClientApp.Models.Basket; -using eShop.ClientApp.Models.Catalog; -using eShop.ClientApp.Models.Marketing; - -namespace eShop.ClientApp.Services.FixUri; - -public interface IFixUriService -{ - void FixCatalogItemPictureUri(IEnumerable catalogItems); - void FixBasketItemPictureUri(IEnumerable basketItems); - void FixCampaignItemPictureUri(IEnumerable campaignItems); -} diff --git a/src/ClientApp/Services/Identity/AuthorizeRequest.cs b/src/ClientApp/Services/Identity/AuthorizeRequest.cs deleted file mode 100644 index bf87761b5..000000000 --- a/src/ClientApp/Services/Identity/AuthorizeRequest.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Net; - -namespace eShop.ClientApp.Services.Identity; - -public class AuthorizeRequest -{ - private readonly Uri _authorizeEndpoint; - - public AuthorizeRequest(string authorizeEndpoint) - { - _authorizeEndpoint = new Uri(authorizeEndpoint); - } - - public string Create(IDictionary values) - { - var queryString = string.Join("&", - values.Select(kvp => - string.Format("{0}={1}", WebUtility.UrlEncode(kvp.Key), WebUtility.UrlEncode(kvp.Value))).ToArray()); - return string.Format("{0}?{1}", _authorizeEndpoint.AbsoluteUri, queryString); - } -} diff --git a/src/ClientApp/Services/Identity/IIdentityService.cs b/src/ClientApp/Services/Identity/IIdentityService.cs deleted file mode 100644 index 485981675..000000000 --- a/src/ClientApp/Services/Identity/IIdentityService.cs +++ /dev/null @@ -1,14 +0,0 @@ -using eShop.ClientApp.Models.User; - -namespace eShop.ClientApp.Services.Identity; - -public interface IIdentityService -{ - Task SignInAsync(); - - Task SignOutAsync(); - - Task GetUserInfoAsync(); - - Task GetAuthTokenAsync(); -} diff --git a/src/ClientApp/Services/Identity/IdentityMockService.cs b/src/ClientApp/Services/Identity/IdentityMockService.cs deleted file mode 100644 index 4e06f6f79..000000000 --- a/src/ClientApp/Services/Identity/IdentityMockService.cs +++ /dev/null @@ -1,58 +0,0 @@ -using eShop.ClientApp.Models.User; - -namespace eShop.ClientApp.Services.Identity; - -public class IdentityMockService : IIdentityService -{ - private bool _signedIn; - - public Task SignInAsync() - { - _signedIn = true; - return Task.FromResult(_signedIn); - } - - public Task SignOutAsync() - { - _signedIn = false; - return Task.FromResult(_signedIn); - } - - public Task GetUserInfoAsync() - { - if (!_signedIn) - { - return Task.FromResult(UserInfo.Default); - } - - return Task.FromResult(new UserInfo - { - UserId = Guid.NewGuid().ToString(), - PreferredUsername = "sampleUser", - Name = "Sample", - LastName = "User", - CardNumber = "XXXXXXXXXXXX3456", - CardHolder = "Sample User", - CardSecurityNumber = "123", - Address = "123 Sample Street", - Country = "USA", - State = "Washington", - Street = "123 Sample Street", - ZipCode = "12345", - Email = "sample.user@example.com", - EmailVerified = true, - PhoneNumber = "1234567890", - PhoneNumberVerified = true - }); - } - - public Task GetAuthTokenAsync() - { - if (!_signedIn) - { - return Task.FromResult(string.Empty); - } - - return Task.FromResult(Guid.NewGuid().ToString()); - } -} diff --git a/src/ClientApp/Services/Identity/IdentityService.cs b/src/ClientApp/Services/Identity/IdentityService.cs deleted file mode 100644 index 086759e26..000000000 --- a/src/ClientApp/Services/Identity/IdentityService.cs +++ /dev/null @@ -1,153 +0,0 @@ -using eShop.ClientApp.Models.Token; -using eShop.ClientApp.Models.User; -using eShop.ClientApp.Services.Settings; -using IdentityModel.OidcClient; -using IBrowser = IdentityModel.OidcClient.Browser.IBrowser; - -namespace eShop.ClientApp.Services.Identity; - -public class IdentityService : IIdentityService -{ - private readonly IBrowser _browser; - private readonly ISettingsService _settingsService; - private readonly HttpMessageHandler _httpMessageHandler; - - public IdentityService(IBrowser browser, ISettingsService settingsService, HttpMessageHandler httpMessageHandler) - { - _browser = browser; - _settingsService = settingsService; - _httpMessageHandler = httpMessageHandler; - } - - public async Task SignInAsync() - { - var response = await GetClient().LoginAsync(new LoginRequest()).ConfigureAwait(false); - - if (response.IsError) - { - return false; - } - - await _settingsService - .SetUserTokenAsync( - new UserToken - { - AccessToken = response.AccessToken, - IdToken = response.IdentityToken, - RefreshToken = response.RefreshToken, - ExpiresAt = response.AccessTokenExpiration - }) - .ConfigureAwait(false); - - return !response.IsError; - } - - public async Task SignOutAsync() - { - var response = await GetClient().LogoutAsync(new LogoutRequest()).ConfigureAwait(false); - - if (response.IsError) - { - return false; - } - - await _settingsService.SetUserTokenAsync(default); - - return !response.IsError; - } - - public async Task GetUserInfoAsync() - { - var authToken = await GetAuthTokenAsync().ConfigureAwait(false); - - if (string.IsNullOrEmpty(authToken)) - { - return UserInfo.Default; - } - - var userInfoWithClaims = await GetClient().GetUserInfoAsync(authToken).ConfigureAwait(false); - - return - new UserInfo - { - UserId = userInfoWithClaims.Claims.FirstOrDefault(c => c.Type == "sub")?.Value, - Email = userInfoWithClaims.Claims.FirstOrDefault(c => c.Type == "email")?.Value, - PhoneNumber = userInfoWithClaims.Claims.FirstOrDefault(c => c.Type == "phone_number")?.Value, - Street = userInfoWithClaims.Claims.FirstOrDefault(c => c.Type == "address_street")?.Value, - Address = userInfoWithClaims.Claims.FirstOrDefault(c => c.Type == "address_city")?.Value, - State = userInfoWithClaims.Claims.FirstOrDefault(c => c.Type == "address_state")?.Value, - ZipCode = userInfoWithClaims.Claims.FirstOrDefault(c => c.Type == "address_zip_code")?.Value, - Country = userInfoWithClaims.Claims.FirstOrDefault(c => c.Type == "address_country")?.Value, - PreferredUsername = - userInfoWithClaims.Claims.FirstOrDefault(c => c.Type == "preferred_username")?.Value, - Name = userInfoWithClaims.Claims.FirstOrDefault(c => c.Type == "name")?.Value, - LastName = userInfoWithClaims.Claims.FirstOrDefault(c => c.Type == "last_name")?.Value, - CardNumber = userInfoWithClaims.Claims.FirstOrDefault(c => c.Type == "card_number")?.Value, - CardHolder = userInfoWithClaims.Claims.FirstOrDefault(c => c.Type == "card_holder")?.Value, - CardSecurityNumber = - userInfoWithClaims.Claims.FirstOrDefault(c => c.Type == "card_security_number")?.Value, - PhoneNumberVerified = - bool.Parse(userInfoWithClaims.Claims.FirstOrDefault(c => c.Type == "phone_number_verified") - ?.Value ?? "false"), - EmailVerified = - bool.Parse(userInfoWithClaims.Claims.FirstOrDefault(c => c.Type == "email_verified")?.Value ?? - "false") - }; - } - - public async Task GetAuthTokenAsync() - { - var userToken = await _settingsService.GetUserTokenAsync().ConfigureAwait(false); - - if (userToken is null) - { - return string.Empty; - } - - if (userToken.ExpiresAt.Subtract(DateTimeOffset.Now).TotalMinutes > 5) - { - return userToken.AccessToken; - } - - var response = await GetClient().RefreshTokenAsync(userToken.RefreshToken).ConfigureAwait(false); - - if (response.IsError) - { - return string.Empty; - } - - await _settingsService - .SetUserTokenAsync( - new UserToken - { - AccessToken = response.AccessToken, - IdToken = response.IdentityToken, - RefreshToken = response.RefreshToken, - ExpiresAt = response.AccessTokenExpiration - }) - .ConfigureAwait(false); - - return response.AccessToken; - } - - private OidcClient GetClient() - { - var options = new OidcClientOptions - { - Authority = _settingsService.IdentityEndpointBase, - ClientId = _settingsService.ClientId, - ClientSecret = _settingsService.ClientSecret, - Scope = "openid profile basket orders offline_access", - RedirectUri = _settingsService.CallbackUri, - PostLogoutRedirectUri = _settingsService.CallbackUri, - Browser = _browser, - }; - - if (_httpMessageHandler is not null) - { - options.BackchannelHandler = _httpMessageHandler; - } - - return new OidcClient(options); - } -} diff --git a/src/ClientApp/Services/Location/ILocationService.cs b/src/ClientApp/Services/Location/ILocationService.cs deleted file mode 100644 index 9a6b9284c..000000000 --- a/src/ClientApp/Services/Location/ILocationService.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace eShop.ClientApp.Services.Location; - -public interface ILocationService -{ - Task UpdateUserLocation(Models.Location.Location newLocReq); -} diff --git a/src/ClientApp/Services/Location/LocationService.cs b/src/ClientApp/Services/Location/LocationService.cs deleted file mode 100644 index 9e21f6564..000000000 --- a/src/ClientApp/Services/Location/LocationService.cs +++ /dev/null @@ -1,30 +0,0 @@ -using eShop.ClientApp.Services.Identity; -using eShop.ClientApp.Services.RequestProvider; -using eShop.ClientApp.Services.Settings; - -namespace eShop.ClientApp.Services.Location; - -public class LocationService : ILocationService -{ - private const string ApiUrlBase = "l/api/v1/locations"; - private readonly IIdentityService _identityService; - - public LocationService(IIdentityService identityService) - { - _identityService = identityService; - } - - public async Task UpdateUserLocation(Models.Location.Location newLocReq) - { - var accessToken = await _identityService.GetAuthTokenAsync().ConfigureAwait(false); - - if (string.IsNullOrEmpty(accessToken)) - { - return; - } - - //TODO: Determine mapped location - await Task.Delay(10).ConfigureAwait(false); - //await _requestProvider.PostAsync(uri, newLocReq, token).ConfigureAwait(false); - } -} diff --git a/src/ClientApp/Services/Navigation/INavigationService.cs b/src/ClientApp/Services/Navigation/INavigationService.cs deleted file mode 100644 index 5aac92b71..000000000 --- a/src/ClientApp/Services/Navigation/INavigationService.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace eShop.ClientApp.Services; - -public interface INavigationService -{ - Task InitializeAsync(); - - Task NavigateToAsync(string route, IDictionary routeParameters = null); - - Task PopAsync(); -} diff --git a/src/ClientApp/Services/Navigation/MauiNavigationService.cs b/src/ClientApp/Services/Navigation/MauiNavigationService.cs deleted file mode 100644 index 393c7ba80..000000000 --- a/src/ClientApp/Services/Navigation/MauiNavigationService.cs +++ /dev/null @@ -1,35 +0,0 @@ -using eShop.ClientApp.Models.User; -using eShop.ClientApp.Services.AppEnvironment; - -namespace eShop.ClientApp.Services; - -public class MauiNavigationService : INavigationService -{ - private readonly IAppEnvironmentService _appEnvironmentService; - - public MauiNavigationService(IAppEnvironmentService appEnvironmentService) - { - _appEnvironmentService = appEnvironmentService; - } - - public async Task InitializeAsync() - { - var user = await _appEnvironmentService.IdentityService.GetUserInfoAsync(); - - await NavigateToAsync(user == UserInfo.Default ? "//Login" : "//Main/Catalog"); - } - - public Task NavigateToAsync(string route, IDictionary routeParameters = null) - { - var shellNavigation = new ShellNavigationState(route); - - return routeParameters != null - ? Shell.Current.GoToAsync(shellNavigation, routeParameters) - : Shell.Current.GoToAsync(shellNavigation); - } - - public Task PopAsync() - { - return Shell.Current.GoToAsync(".."); - } -} diff --git a/src/ClientApp/Services/OpenUrl/IOpenUrlService.cs b/src/ClientApp/Services/OpenUrl/IOpenUrlService.cs deleted file mode 100644 index fffd2d1bd..000000000 --- a/src/ClientApp/Services/OpenUrl/IOpenUrlService.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace eShop.ClientApp.Services.OpenUrl; - -public interface IOpenUrlService -{ - Task OpenUrl(string url); -} diff --git a/src/ClientApp/Services/OpenUrl/OpenUrlService.cs b/src/ClientApp/Services/OpenUrl/OpenUrlService.cs deleted file mode 100644 index 53ee914f3..000000000 --- a/src/ClientApp/Services/OpenUrl/OpenUrlService.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace eShop.ClientApp.Services.OpenUrl; - -public class OpenUrlService : IOpenUrlService -{ - public async Task OpenUrl(string url) - { - if (await Launcher.CanOpenAsync(url)) - { - await Launcher.OpenAsync(url); - } - } -} diff --git a/src/ClientApp/Services/Order/IOrderService.cs b/src/ClientApp/Services/Order/IOrderService.cs deleted file mode 100644 index 36608a1fd..000000000 --- a/src/ClientApp/Services/Order/IOrderService.cs +++ /dev/null @@ -1,16 +0,0 @@ -using eShop.ClientApp.Models.Basket; - -namespace eShop.ClientApp.Services.Order; - -public interface IOrderService -{ - Task CreateOrderAsync(Models.Orders.Order newOrder); - - Task> GetOrdersAsync(); - - Task GetOrderAsync(int orderId); - - Task CancelOrderAsync(int orderId); - - OrderCheckout MapOrderToBasket(Models.Orders.Order order); -} diff --git a/src/ClientApp/Services/Order/OrderMockService.cs b/src/ClientApp/Services/Order/OrderMockService.cs deleted file mode 100644 index f18219415..000000000 --- a/src/ClientApp/Services/Order/OrderMockService.cs +++ /dev/null @@ -1,187 +0,0 @@ -using eShop.ClientApp.Models.Basket; -using eShop.ClientApp.Models.Orders; -using eShop.ClientApp.Models.User; - -namespace eShop.ClientApp.Services.Order; - -public class OrderMockService : IOrderService -{ - private static readonly DateTime MockExpirationDate = DateTime.Now.AddYears(5); - - private static readonly Address MockAdress = new() - { - Id = Guid.NewGuid(), - City = "Seattle, WA", - Street = "120 E 87th Street", - CountryCode = "98122", - Country = "United States", - Latitude = 40.785091, - Longitude = -73.968285, - State = "Seattle", - StateCode = "WA", - ZipCode = "98101" - }; - - private static readonly PaymentInfo MockPaymentInfo = new() - { - Id = Guid.NewGuid(), - CardHolderName = "American Express", - CardNumber = "XXXXXXXXXXXX0005", - CardType = new CardType - { - Id = 3, - Name = "MasterCard" - }, - Expiration = MockExpirationDate.ToString(), - ExpirationMonth = MockExpirationDate.Month, - ExpirationYear = MockExpirationDate.Year, - SecurityNumber = "123" - }; - - private static readonly List MockOrderItems = new() - { - new OrderItem - { - OrderId = Guid.NewGuid(), - ProductId = Common.Common.MockCatalogItemId01, - Discount = 15, - ProductName = ".NET Bot Blue Sweatshirt (M)", - Quantity = 1, - UnitPrice = 16.50M, - PictureUrl = "fake_product_01.png" - }, - new OrderItem - { - OrderId = Guid.NewGuid(), - ProductId = Common.Common.MockCatalogItemId03, - Discount = 0, - ProductName = ".NET Bot Black Sweatshirt (M)", - Quantity = 2, - UnitPrice = 19.95M, - PictureUrl = "fake_product_03.png" - } - }; - - private static readonly OrderCheckout MockOrderCheckout = new() - { - CardExpiration = DateTime.UtcNow, - CardHolderName = "FakeCardHolderName", - CardNumber = "XXXXXXXXXXXX3224", - CardSecurityNumber = "1234", - CardTypeId = 1, - City = "FakeCity", - Country = "FakeCountry", - ZipCode = "FakeZipCode", - Street = "FakeStreet" - }; - - private readonly List MockOrders = new() - { - new Models.Orders.Order - { - OrderNumber = 1, - SequenceNumber = 123, - OrderDate = DateTime.Now, - OrderStatus = "Submitted", - OrderItems = MockOrderItems, - CardTypeId = MockPaymentInfo.CardType.Id, - CardHolderName = MockPaymentInfo.CardHolderName, - CardNumber = MockPaymentInfo.CardNumber, - CardSecurityNumber = MockPaymentInfo.SecurityNumber, - CardExpiration = new DateTime(MockPaymentInfo.ExpirationYear, MockPaymentInfo.ExpirationMonth, 1), - ShippingCity = MockAdress.City, - ShippingState = MockAdress.State, - ShippingCountry = MockAdress.Country, - ShippingStreet = MockAdress.Street, - Total = 36.46M - }, - new Models.Orders.Order - { - OrderNumber = 2, - SequenceNumber = 132, - OrderDate = DateTime.Now, - OrderStatus = "Paid", - OrderItems = MockOrderItems, - CardTypeId = MockPaymentInfo.CardType.Id, - CardHolderName = MockPaymentInfo.CardHolderName, - CardNumber = MockPaymentInfo.CardNumber, - CardSecurityNumber = MockPaymentInfo.SecurityNumber, - CardExpiration = new DateTime(MockPaymentInfo.ExpirationYear, MockPaymentInfo.ExpirationMonth, 1), - ShippingCity = MockAdress.City, - ShippingState = MockAdress.State, - ShippingCountry = MockAdress.Country, - ShippingStreet = MockAdress.Street, - Total = 36.46M - }, - new Models.Orders.Order - { - OrderNumber = 3, - SequenceNumber = 231, - OrderDate = DateTime.Now, - OrderStatus = "Cancelled", - OrderItems = MockOrderItems, - CardTypeId = MockPaymentInfo.CardType.Id, - CardHolderName = MockPaymentInfo.CardHolderName, - CardNumber = MockPaymentInfo.CardNumber, - CardSecurityNumber = MockPaymentInfo.SecurityNumber, - CardExpiration = new DateTime(MockPaymentInfo.ExpirationYear, MockPaymentInfo.ExpirationMonth, 1), - ShippingCity = MockAdress.City, - ShippingState = MockAdress.State, - ShippingCountry = MockAdress.Country, - ShippingStreet = MockAdress.Street, - Total = 36.46M - }, - new Models.Orders.Order - { - OrderNumber = 4, - SequenceNumber = 131, - OrderDate = DateTime.Now, - OrderStatus = "Shipped", - OrderItems = MockOrderItems, - CardTypeId = MockPaymentInfo.CardType.Id, - CardHolderName = MockPaymentInfo.CardHolderName, - CardNumber = MockPaymentInfo.CardNumber, - CardSecurityNumber = MockPaymentInfo.SecurityNumber, - CardExpiration = new DateTime(MockPaymentInfo.ExpirationYear, MockPaymentInfo.ExpirationMonth, 1), - ShippingCity = MockAdress.City, - ShippingState = MockAdress.State, - ShippingCountry = MockAdress.Country, - ShippingStreet = MockAdress.Street, - Total = 36.46M - } - }; - - public async Task> GetOrdersAsync() - { - await Task.Delay(10); - - return MockOrders - .OrderByDescending(o => o.OrderNumber) - .ToArray(); - } - - public async Task GetOrderAsync(int orderId) - { - await Task.Delay(10); - - return MockOrders - .FirstOrDefault(o => o.OrderNumber.Equals(orderId)); - } - - public async Task CreateOrderAsync(Models.Orders.Order newOrder) - { - await Task.Delay(10); - - MockOrders.Add(newOrder); - } - - public OrderCheckout MapOrderToBasket(Models.Orders.Order order) - { - return MockOrderCheckout; - } - - public Task CancelOrderAsync(int orderId) - { - return Task.FromResult(true); - } -} diff --git a/src/ClientApp/Services/Order/OrderService.cs b/src/ClientApp/Services/Order/OrderService.cs deleted file mode 100644 index d7f6a9887..000000000 --- a/src/ClientApp/Services/Order/OrderService.cs +++ /dev/null @@ -1,128 +0,0 @@ -using System.Net; -using eShop.ClientApp.Helpers; -using eShop.ClientApp.Models.Basket; -using eShop.ClientApp.Models.Orders; -using eShop.ClientApp.Services.Identity; -using eShop.ClientApp.Services.RequestProvider; -using eShop.ClientApp.Services.Settings; - -namespace eShop.ClientApp.Services.Order; - -public class OrderService : IOrderService -{ - private const string ApiUrlBase = "api/orders"; - private const string ApiVersion = "api-version=1.0"; - - private readonly IIdentityService _identityService; - private readonly IRequestProvider _requestProvider; - private readonly ISettingsService _settingsService; - - public OrderService(IIdentityService identityService, ISettingsService settingsService, - IRequestProvider requestProvider) - { - _identityService = identityService; - _settingsService = settingsService; - _requestProvider = requestProvider; - } - - public async Task CreateOrderAsync(Models.Orders.Order newOrder) - { - var authToken = await _identityService.GetAuthTokenAsync().ConfigureAwait(false); - - if (string.IsNullOrEmpty(authToken)) - { - return; - } - - var uri = $"{UriHelper.CombineUri(_settingsService.GatewayOrdersEndpointBase, ApiUrlBase)}?{ApiVersion}"; - - var success = await _requestProvider.PostAsync(uri, newOrder, authToken, "x-requestid").ConfigureAwait(false); - } - - public async Task> GetOrdersAsync() - { - var authToken = await _identityService.GetAuthTokenAsync().ConfigureAwait(false); - - if (string.IsNullOrEmpty(authToken)) - { - return Enumerable.Empty(); - } - - var uri = $"{UriHelper.CombineUri(_settingsService.GatewayOrdersEndpointBase, ApiUrlBase)}?{ApiVersion}"; - - var orders = - await _requestProvider.GetAsync>(uri, authToken).ConfigureAwait(false); - - return orders ?? Enumerable.Empty(); - } - - public async Task GetOrderAsync(int orderId) - { - var authToken = await _identityService.GetAuthTokenAsync().ConfigureAwait(false); - - if (string.IsNullOrEmpty(authToken)) - { - return new Models.Orders.Order(); - } - - try - { - var uri = $"{UriHelper.CombineUri(_settingsService.GatewayOrdersEndpointBase, $"{ApiUrlBase}/{orderId}")}?{ApiVersion}"; - - var order = - await _requestProvider.GetAsync(uri, authToken).ConfigureAwait(false); - - return order; - } - catch - { - return new Models.Orders.Order(); - } - } - - public async Task CancelOrderAsync(int orderId) - { - var authToken = await _identityService.GetAuthTokenAsync().ConfigureAwait(false); - - if (string.IsNullOrEmpty(authToken)) - { - return false; - } - - var uri = $"{UriHelper.CombineUri(_settingsService.GatewayOrdersEndpointBase, $"{ApiUrlBase}/cancel")}?{ApiVersion}"; - - var cancelOrderCommand = new CancelOrderCommand(orderId); - - var header = "x-requestid"; - - try - { - await _requestProvider.PutAsync(uri, cancelOrderCommand, authToken, header).ConfigureAwait(false); - } - //If the status of the order has changed before to click cancel button, we will get - //a BadRequest HttpStatus - catch (HttpRequestExceptionEx ex) when (ex.HttpCode == HttpStatusCode.BadRequest) - { - return false; - } - - return true; - } - - public OrderCheckout MapOrderToBasket(Models.Orders.Order order) - { - return new OrderCheckout - { - CardExpiration = order.CardExpiration, - CardHolderName = order.CardHolderName, - CardNumber = order.CardNumber, - CardSecurityNumber = order.CardSecurityNumber, - CardTypeId = order.CardTypeId, - City = order.ShippingCity, - State = order.ShippingState, - Country = order.ShippingCountry, - ZipCode = order.ShippingZipCode, - Street = order.ShippingStreet - }; - } -} diff --git a/src/ClientApp/Services/RequestProvider/HttpRequestExceptionEx.cs b/src/ClientApp/Services/RequestProvider/HttpRequestExceptionEx.cs deleted file mode 100644 index 6eeecf0d9..000000000 --- a/src/ClientApp/Services/RequestProvider/HttpRequestExceptionEx.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Net; - -namespace eShop.ClientApp.Services.RequestProvider; - -public class HttpRequestExceptionEx : HttpRequestException -{ - public HttpRequestExceptionEx(HttpStatusCode code) : this(code, null, null) - { - } - - public HttpRequestExceptionEx(HttpStatusCode code, string message) : this(code, message, null) - { - } - - public HttpRequestExceptionEx(HttpStatusCode code, string message, Exception inner) : base(message, inner) - { - HttpCode = code; - } - - public HttpStatusCode HttpCode { get; } -} diff --git a/src/ClientApp/Services/RequestProvider/IRequestProvider.cs b/src/ClientApp/Services/RequestProvider/IRequestProvider.cs deleted file mode 100644 index 919205b26..000000000 --- a/src/ClientApp/Services/RequestProvider/IRequestProvider.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace eShop.ClientApp.Services.RequestProvider; - -public interface IRequestProvider -{ - Task GetAsync(string uri, string token = ""); - - Task PostAsync(string uri, TRequest data, string token = "", string header = ""); - - Task PostAsync(string uri, TRequest data, string token = "", string header = ""); - - Task PostAsync(string uri, string data, string clientId, string clientSecret); - - Task PutAsync(string uri, TResult data, string token = "", string header = ""); - - Task DeleteAsync(string uri, string token = ""); -} diff --git a/src/ClientApp/Services/RequestProvider/RequestProvider.cs b/src/ClientApp/Services/RequestProvider/RequestProvider.cs deleted file mode 100644 index 2f5f7f3df..000000000 --- a/src/ClientApp/Services/RequestProvider/RequestProvider.cs +++ /dev/null @@ -1,181 +0,0 @@ -#nullable enable -using System.Net; -using System.Net.Http.Headers; -using System.Net.Http.Json; -using System.Text.Json; -using eShop.ClientApp.Exceptions; - -namespace eShop.ClientApp.Services.RequestProvider; - -public class RequestProvider(HttpMessageHandler _messageHandler) : IRequestProvider -{ - private readonly Lazy _httpClient = - new(() => - { - var httpClient = _messageHandler is not null ? new HttpClient(_messageHandler) : new HttpClient(); - httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - return httpClient; - }, - LazyThreadSafetyMode.ExecutionAndPublication); - - public async Task GetAsync(string uri, string token = "") - { - var httpClient = GetOrCreateHttpClient(token); - using var response = await httpClient.GetAsync(uri).ConfigureAwait(false); - - await HandleResponse(response).ConfigureAwait(false); - - var result = await ReadFromJsonAsync(response.Content).ConfigureAwait(false); - - return result; - } - - public async Task PostAsync(string uri, TRequest data, string token = "", string header = "") - { - var httpClient = GetOrCreateHttpClient(token); - - if (!string.IsNullOrEmpty(header)) - { - AddHeaderParameter(httpClient, header); - } - - var requestContent = SerializeToJson(data); - using HttpResponseMessage response = await httpClient.PostAsync(uri, requestContent).ConfigureAwait(false); - - await HandleResponse(response).ConfigureAwait(false); - var result = await ReadFromJsonAsync(response.Content).ConfigureAwait(false); - - return result; - } - - public async Task PostAsync(string uri, TRequest data, string token = "", string header = "") - { - var httpClient = GetOrCreateHttpClient(token); - - if (!string.IsNullOrEmpty(header)) - { - AddHeaderParameter(httpClient, header); - } - - var requestContent = SerializeToJson(data); - using var response = await httpClient.PostAsync(uri, requestContent).ConfigureAwait(false); - - await HandleResponse(response).ConfigureAwait(false); - - return response.IsSuccessStatusCode; - } - - public async Task PostAsync(string uri, string data, string clientId, string clientSecret) - - { - var httpClient = GetOrCreateHttpClient(string.Empty); - - if (!string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(clientSecret)) - { - AddBasicAuthenticationHeader(httpClient, clientId, clientSecret); - } - - using var content = new StringContent(data); - content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); - using var response = await httpClient.PostAsync(uri, content).ConfigureAwait(false); - - await HandleResponse(response).ConfigureAwait(false); - var result = await ReadFromJsonAsync(response.Content).ConfigureAwait(false); - - return result; - } - - public async Task PutAsync(string uri, TResult data, string token = "", string header = "") - { - var httpClient = GetOrCreateHttpClient(token); - - if (!string.IsNullOrEmpty(header)) - { - AddHeaderParameter(httpClient, header); - } - - var requestContent = SerializeToJson(data); - using HttpResponseMessage response = await httpClient.PutAsync(uri, requestContent).ConfigureAwait(false); - - await HandleResponse(response).ConfigureAwait(false); - var result = await ReadFromJsonAsync(response.Content).ConfigureAwait(false); - - return result; - } - - public async Task DeleteAsync(string uri, string token = "") - { - var httpClient = GetOrCreateHttpClient(token); - await httpClient.DeleteAsync(uri).ConfigureAwait(false); - } - - private HttpClient GetOrCreateHttpClient(string token = "") - { - var httpClient = _httpClient.Value; - - httpClient.DefaultRequestHeaders.Authorization = - !string.IsNullOrEmpty(token) - ? new AuthenticationHeaderValue("Bearer", token) - : null; - - return httpClient; - } - - private static void AddHeaderParameter(HttpClient httpClient, string parameter) - { - if (httpClient == null) - { - return; - } - - if (string.IsNullOrEmpty(parameter)) - { - return; - } - - httpClient.DefaultRequestHeaders.Add(parameter, Guid.NewGuid().ToString()); - } - - private static void AddBasicAuthenticationHeader(HttpClient httpClient, string clientId, string clientSecret) - { - if (httpClient == null) - { - return; - } - - if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(clientSecret)) - { - return; - } - - httpClient.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(clientId, clientSecret); - } - - private static async Task HandleResponse(HttpResponseMessage response) - { - if (!response.IsSuccessStatusCode) - { - var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - - if (response.StatusCode == HttpStatusCode.Forbidden || response.StatusCode == HttpStatusCode.Unauthorized) - { - throw new ServiceAuthenticationException(content); - } - - throw new HttpRequestExceptionEx(response.StatusCode, content); - } - } - - private static async Task ReadFromJsonAsync(HttpContent content) - { - using var contentStream = await content.ReadAsStreamAsync().ConfigureAwait(false); - var data = await JsonSerializer.DeserializeAsync(contentStream, typeof(T), EShopJsonSerializerContext.Default).ConfigureAwait(false); - return (T?)data; - } - - private static JsonContent SerializeToJson(T data) - { - var typeInfo = EShopJsonSerializerContext.Default.GetTypeInfo(typeof(T)) ?? throw new InvalidOperationException($"Missing type info for {typeof(T)}"); - return JsonContent.Create(data, typeInfo); - } -} diff --git a/src/ClientApp/Services/Settings/ISettingsService.cs b/src/ClientApp/Services/Settings/ISettingsService.cs deleted file mode 100644 index 43f8edbcc..000000000 --- a/src/ClientApp/Services/Settings/ISettingsService.cs +++ /dev/null @@ -1,38 +0,0 @@ -#nullable enable -using eShop.ClientApp.Models.Token; - -namespace eShop.ClientApp.Services.Settings; - -public interface ISettingsService -{ - bool UseMocks { get; set; } - - string DefaultEndpoint { get; set; } - - string RegistrationEndpoint { get; set; } - - string ClientId { get; set; } - - string ClientSecret { get; set; } - - string CallbackUri { get; set; } - - string IdentityEndpointBase { get; set; } - - string GatewayCatalogEndpointBase { get; set; } - - string GatewayOrdersEndpointBase { get; set; } - - string GatewayBasketEndpointBase { get; set; } - - bool UseFakeLocation { get; set; } - - string Latitude { get; set; } - - string Longitude { get; set; } - - bool AllowGpsLocation { get; set; } - Task GetUserTokenAsync(); - - Task SetUserTokenAsync(UserToken? userToken); -} diff --git a/src/ClientApp/Services/Settings/SettingsService.cs b/src/ClientApp/Services/Settings/SettingsService.cs deleted file mode 100644 index 72bb081a5..000000000 --- a/src/ClientApp/Services/Settings/SettingsService.cs +++ /dev/null @@ -1,152 +0,0 @@ -using System.Globalization; -using System.Text.Json; -using eShop.ClientApp.Models.Token; - -namespace eShop.ClientApp.Services.Settings; - -public class SettingsService : ISettingsService -{ - #region Setting Constants - - private const string UserAccessToken = "user_token"; - private const string IdUseMocks = "use_mocks"; - private const string IdIdentityBase = "url_base"; - private const string DefaultClientId = "maui"; - private const string DefaultClientSecret = "secret"; - private const string DefaultCallbackUri = "maui://authcallback"; - private const string IdGatewayMarketingBase = "url_marketing"; - private const string IdGatewayShoppingBase = "url_shopping"; - private const string IdGatewayOrdersBase = "url_orders"; - private const string IdGatewayBasketBase = "url_basket"; - private const string IdUseFakeLocation = "use_fake_location"; - private const string IdLatitude = "latitude"; - private const string IdLongitude = "longitude"; - private const string IdAllowGpsLocation = "allow_gps_location"; - private readonly bool UseMocksDefault = true; - private readonly bool UseFakeLocationDefault = false; - private readonly bool AllowGpsLocationDefault = false; - private readonly double FakeLatitudeDefault = 47.604610d; - private readonly double FakeLongitudeDefault = -122.315752d; - - #endregion - - #region Settings Properties - - public async Task SetUserTokenAsync(UserToken userToken) - { - await SecureStorage - .SetAsync(UserAccessToken, userToken is not null ? JsonSerializer.Serialize(userToken, EShopJsonSerializerContext.Default.UserToken) : string.Empty) - .ConfigureAwait(false); - } - - public async Task GetUserTokenAsync() - { - var userToken = await SecureStorage.GetAsync(UserAccessToken).ConfigureAwait(false); - - return string.IsNullOrEmpty(userToken) ? default : JsonSerializer.Deserialize(userToken, EShopJsonSerializerContext.Default.UserToken); - } - - public bool UseMocks - { - get => Preferences.Get(IdUseMocks, UseMocksDefault); - set => Preferences.Set(IdUseMocks, value); - } - - public string DefaultEndpoint - { - get => Preferences.Get(nameof(DefaultEndpoint), string.Empty); - set => Preferences.Set(nameof(DefaultEndpoint), value); - } - - public string RegistrationEndpoint - { - get => Preferences.Get(nameof(RegistrationEndpoint), string.Empty); - set => Preferences.Set(nameof(RegistrationEndpoint), value); - } - - public string AuthorizeEndpoint - { - get => Preferences.Get(nameof(AuthorizeEndpoint), string.Empty); - set => Preferences.Set(nameof(AuthorizeEndpoint), value); - } - - public string UserInfoEndpoint - { - get => Preferences.Get(nameof(UserInfoEndpoint), string.Empty); - set => Preferences.Set(nameof(UserInfoEndpoint), value); - } - - public string ClientId - { - get => Preferences.Get(nameof(ClientId), DefaultClientId); - set => Preferences.Set(nameof(ClientId), value); - } - - public string ClientSecret - { - get => Preferences.Get(nameof(ClientSecret), DefaultClientSecret); - set => Preferences.Set(nameof(ClientSecret), value); - } - - public string CallbackUri - { - get => Preferences.Get(nameof(CallbackUri), DefaultCallbackUri); - set => Preferences.Set(nameof(CallbackUri), value); - } - - public string IdentityEndpointBase - { - get => Preferences.Get(IdIdentityBase, string.Empty); - set => Preferences.Set(IdIdentityBase, value); - } - - public string GatewayCatalogEndpointBase - { - get => Preferences.Get(IdGatewayShoppingBase, string.Empty); - set => Preferences.Set(IdGatewayShoppingBase, value); - } - - public string GatewayMarketingEndpointBase - { - get => Preferences.Get(IdGatewayMarketingBase, string.Empty); - set => Preferences.Set(IdGatewayMarketingBase, value); - } - - public string GatewayOrdersEndpointBase - { - get => Preferences.Get(IdGatewayOrdersBase, string.Empty); - set => Preferences.Set(IdGatewayOrdersBase, value); - } - - public string GatewayBasketEndpointBase - { - get => Preferences.Get(IdGatewayBasketBase, string.Empty); - set => Preferences.Set(IdGatewayBasketBase, value); - } - - public bool UseFakeLocation - { - get => Preferences.Get(IdUseFakeLocation, UseFakeLocationDefault); - set => Preferences.Set(IdUseFakeLocation, value); - } - - public string Latitude - { - get => Preferences.Get(IdLatitude, FakeLatitudeDefault.ToString(CultureInfo.InvariantCulture)); - set => Preferences.Set(IdLatitude, value); - } - - public string Longitude - { - get => Preferences.Get(IdLongitude, FakeLongitudeDefault.ToString(CultureInfo.InvariantCulture)); - set => Preferences.Set(IdLongitude, value); - } - - public bool AllowGpsLocation - { - get => Preferences.Get(IdAllowGpsLocation, AllowGpsLocationDefault); - set => Preferences.Set(IdAllowGpsLocation, value); - } - - #endregion -} diff --git a/src/ClientApp/Services/Theme/ITheme.cs b/src/ClientApp/Services/Theme/ITheme.cs deleted file mode 100644 index b864ac626..000000000 --- a/src/ClientApp/Services/Theme/ITheme.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace eShop.ClientApp.Services.Theme; - -public interface ITheme -{ - void SetStatusBarColor(Color color, bool darkStatusBarTint); -} diff --git a/src/ClientApp/Services/Theme/Theme.shared.cs b/src/ClientApp/Services/Theme/Theme.shared.cs deleted file mode 100644 index 25f09be58..000000000 --- a/src/ClientApp/Services/Theme/Theme.shared.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace eShop.ClientApp.Services.Theme; - -public class Theme : ITheme -{ - public void SetStatusBarColor(Color color, bool darkStatusBarTint) - { - } -} diff --git a/src/ClientApp/Triggers/BeginAnimation.cs b/src/ClientApp/Triggers/BeginAnimation.cs deleted file mode 100644 index 0baef8b0b..000000000 --- a/src/ClientApp/Triggers/BeginAnimation.cs +++ /dev/null @@ -1,16 +0,0 @@ -using eShop.ClientApp.Animations.Base; - -namespace eShop.ClientApp.Triggers; - -public class BeginAnimation : TriggerAction -{ - public AnimationBase Animation { get; set; } - - protected override async void Invoke(VisualElement sender) - { - if (Animation != null) - { - await Animation.Begin(); - } - } -} diff --git a/src/ClientApp/Validations/IValidationRule.cs b/src/ClientApp/Validations/IValidationRule.cs deleted file mode 100644 index f86875fa1..000000000 --- a/src/ClientApp/Validations/IValidationRule.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace eShop.ClientApp.Validations; - -public interface IValidationRule -{ - string ValidationMessage { get; set; } - - bool Check(T value); -} diff --git a/src/ClientApp/Validations/IValidity.cs b/src/ClientApp/Validations/IValidity.cs deleted file mode 100644 index 95b8b827d..000000000 --- a/src/ClientApp/Validations/IValidity.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace eShop.ClientApp.Validations; - -public interface IValidity -{ - bool IsValid { get; } -} diff --git a/src/ClientApp/Validations/IsNotNullOrEmptyRule.cs b/src/ClientApp/Validations/IsNotNullOrEmptyRule.cs deleted file mode 100644 index 4779c71b5..000000000 --- a/src/ClientApp/Validations/IsNotNullOrEmptyRule.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace eShop.ClientApp.Validations; - -public class IsNotNullOrEmptyRule : IValidationRule -{ - public string ValidationMessage { get; set; } - - public bool Check(T value) - { - return value is string str && - !string.IsNullOrWhiteSpace(str); - } -} diff --git a/src/ClientApp/Validations/ValidatableObject.cs b/src/ClientApp/Validations/ValidatableObject.cs deleted file mode 100644 index 53fc5cb6b..000000000 --- a/src/ClientApp/Validations/ValidatableObject.cs +++ /dev/null @@ -1,47 +0,0 @@ -namespace eShop.ClientApp.Validations; - -public class ValidatableObject : ObservableObject, IValidity -{ - private IEnumerable _errors; - private bool _isValid; - private T _value; - - public ValidatableObject() - { - _isValid = true; - _errors = Enumerable.Empty(); - } - - public List> Validations { get; } = new(); - - public IEnumerable Errors - { - get => _errors; - private set => SetProperty(ref _errors, value); - } - - public T Value - { - get => _value; - set => SetProperty(ref _value, value); - } - - public bool IsValid - { - get => _isValid; - private set => SetProperty(ref _isValid, value); - } - - public bool Validate() - { - Errors = Validations - ?.Where(v => !v.Check(Value)) - ?.Select(v => v.ValidationMessage) - ?.ToArray() - ?? Enumerable.Empty(); - - IsValid = !Errors.Any(); - - return IsValid; - } -} diff --git a/src/ClientApp/ViewModels/Base/IViewModelBase.cs b/src/ClientApp/ViewModels/Base/IViewModelBase.cs deleted file mode 100644 index 36a731d3e..000000000 --- a/src/ClientApp/ViewModels/Base/IViewModelBase.cs +++ /dev/null @@ -1,16 +0,0 @@ -using eShop.ClientApp.Services; - -namespace eShop.ClientApp.ViewModels.Base; - -public interface IViewModelBase : IQueryAttributable -{ - public INavigationService NavigationService { get; } - - public IAsyncRelayCommand InitializeAsyncCommand { get; } - - public bool IsBusy { get; } - - public bool IsInitialized { get; } - - Task InitializeAsync(); -} diff --git a/src/ClientApp/ViewModels/Base/ViewModelBase.cs b/src/ClientApp/ViewModels/Base/ViewModelBase.cs deleted file mode 100644 index fcc921add..000000000 --- a/src/ClientApp/ViewModels/Base/ViewModelBase.cs +++ /dev/null @@ -1,55 +0,0 @@ -using eShop.ClientApp.Services; - -namespace eShop.ClientApp.ViewModels.Base; - -public abstract partial class ViewModelBase : ObservableObject, IViewModelBase -{ - private long _isBusy; - - [ObservableProperty] private bool _isInitialized; - - public ViewModelBase(INavigationService navigationService) - { - NavigationService = navigationService; - - InitializeAsyncCommand = - new AsyncRelayCommand( - async () => - { - await IsBusyFor(InitializeAsync); - IsInitialized = true; - }, - AsyncRelayCommandOptions.FlowExceptionsToTaskScheduler); - } - - public bool IsBusy => Interlocked.Read(ref _isBusy) > 0; - - public INavigationService NavigationService { get; } - - public IAsyncRelayCommand InitializeAsyncCommand { get; } - - public virtual void ApplyQueryAttributes(IDictionary query) - { - } - - public virtual Task InitializeAsync() - { - return Task.CompletedTask; - } - - protected async Task IsBusyFor(Func unitOfWork) - { - Interlocked.Increment(ref _isBusy); - OnPropertyChanged(nameof(IsBusy)); - - try - { - await unitOfWork(); - } - finally - { - Interlocked.Decrement(ref _isBusy); - OnPropertyChanged(nameof(IsBusy)); - } - } -} diff --git a/src/ClientApp/ViewModels/BasketViewModel.cs b/src/ClientApp/ViewModels/BasketViewModel.cs deleted file mode 100644 index 67eb60ba4..000000000 --- a/src/ClientApp/ViewModels/BasketViewModel.cs +++ /dev/null @@ -1,113 +0,0 @@ -using eShop.ClientApp.Models.Basket; -using eShop.ClientApp.Services; -using eShop.ClientApp.Services.AppEnvironment; -using eShop.ClientApp.Services.Settings; -using eShop.ClientApp.ViewModels.Base; - -namespace eShop.ClientApp.ViewModels; - -public partial class BasketViewModel : ViewModelBase -{ - private readonly IAppEnvironmentService _appEnvironmentService; - private readonly ObservableCollectionEx _basketItems = new(); - private readonly ISettingsService _settingsService; - - public BasketViewModel( - IAppEnvironmentService appEnvironmentService, - INavigationService navigationService, ISettingsService settingsService) - : base(navigationService) - { - _appEnvironmentService = appEnvironmentService; - _settingsService = settingsService; - } - - public int BadgeCount => _basketItems?.Sum(basketItem => basketItem.Quantity) ?? 0; - - public decimal Total => _basketItems?.Sum(basketItem => basketItem.Quantity * basketItem.UnitPrice) ?? 0m; - - public IReadOnlyList BasketItems => _basketItems; - - public override async Task InitializeAsync() - { - // Update Basket - var basket = await _appEnvironmentService.BasketService.GetBasketAsync(); - - if ((basket?.Items?.Count ?? 0) > 0) - { - await _basketItems.ReloadDataAsync( - async innerList => - { - foreach (var basketItem in basket.Items.ToArray()) - { - var catalogItem = - await _appEnvironmentService.CatalogService.GetCatalogItemAsync(basketItem.ProductId); - basketItem.PictureUrl = catalogItem.PictureUri; - basketItem.ProductName = catalogItem.Name; - basketItem.UnitPrice = catalogItem.Price; - await AddBasketItemAsync(basketItem, innerList); - } - }); - } - } - - [RelayCommand] - private Task AddAsync(BasketItem item) - { - return AddBasketItemAsync(item, _basketItems); - } - - private async Task AddBasketItemAsync(BasketItem item, IList basketItems) - { - basketItems.Add(item); - - var basket = await _appEnvironmentService.BasketService.GetBasketAsync(); - - if (basket != null) - { - basket.AddItemToBasket(item); - await _appEnvironmentService.BasketService.UpdateBasketAsync(basket); - } - - ReCalculateTotal(); - } - - [RelayCommand] - private async Task DeleteAsync(BasketItem item) - { - _basketItems.Remove(item); - - var basket = await _appEnvironmentService.BasketService.GetBasketAsync(); - if (basket != null) - { - basket.RemoveItemFromBasket(item); - await _appEnvironmentService.BasketService.UpdateBasketAsync(basket); - } - - ReCalculateTotal(); - } - - public async Task ClearBasketItems() - { - _basketItems.Clear(); - - await _appEnvironmentService.BasketService.ClearBasketAsync(); - - ReCalculateTotal(); - } - - private void ReCalculateTotal() - { - OnPropertyChanged(nameof(BadgeCount)); - OnPropertyChanged(nameof(Total)); - } - - [RelayCommand] - private async Task CheckoutAsync() - { - if (_basketItems?.Any() ?? false) - { - _appEnvironmentService.BasketService.LocalBasketItems = _basketItems; - await NavigationService.NavigateToAsync("Checkout"); - } - } -} diff --git a/src/ClientApp/ViewModels/CatalogItemViewModel.cs b/src/ClientApp/ViewModels/CatalogItemViewModel.cs deleted file mode 100644 index 02170e226..000000000 --- a/src/ClientApp/ViewModels/CatalogItemViewModel.cs +++ /dev/null @@ -1,65 +0,0 @@ -using CommunityToolkit.Mvvm.Messaging; -using eShop.ClientApp.Messages; -using eShop.ClientApp.Models.Basket; -using eShop.ClientApp.Models.Catalog; -using eShop.ClientApp.Services; -using eShop.ClientApp.Services.AppEnvironment; -using eShop.ClientApp.ViewModels.Base; - -namespace eShop.ClientApp.ViewModels; - -public partial class CatalogItemViewModel : ViewModelBase -{ - private readonly IAppEnvironmentService _appEnvironmentService; - - [ObservableProperty] private CatalogItem _catalogItem; - - public CatalogItemViewModel(IAppEnvironmentService appEnvironmentService, INavigationService navigationService) : - base(navigationService) - { - _appEnvironmentService = appEnvironmentService; - } - - public override void ApplyQueryAttributes(IDictionary query) - { - base.ApplyQueryAttributes(query); - - CatalogItem = query.ValueAs("CatalogItem"); - } - - [RelayCommand] - private async Task AddCatalogItemAsync() - { - if (CatalogItem is null) - { - return; - } - - var basket = await _appEnvironmentService.BasketService.GetBasketAsync(); - if (basket is not null) - { - basket.AddItemToBasket( - new BasketItem - { - ProductId = CatalogItem.Id, - ProductName = CatalogItem.Name, - PictureUrl = CatalogItem.PictureUri, - UnitPrice = CatalogItem.Price, - Quantity = 1 - }); - - var basketUpdate = await _appEnvironmentService.BasketService.UpdateBasketAsync(basket); - - WeakReferenceMessenger.Default - .Send(new ProductCountChangedMessage(basketUpdate.ItemCount)); - - await NavigationService.PopAsync(); - } - } - - [RelayCommand] - private async Task DismissAsync() - { - await NavigationService.PopAsync(); - } -} diff --git a/src/ClientApp/ViewModels/CatalogViewModel.cs b/src/ClientApp/ViewModels/CatalogViewModel.cs deleted file mode 100644 index a90d1601d..000000000 --- a/src/ClientApp/ViewModels/CatalogViewModel.cs +++ /dev/null @@ -1,205 +0,0 @@ -#nullable enable -using CommunityToolkit.Mvvm.Messaging; -using eShop.ClientApp.Messages; -using eShop.ClientApp.Models.Catalog; -using eShop.ClientApp.Services; -using eShop.ClientApp.Services.AppEnvironment; -using eShop.ClientApp.ViewModels.Base; - -namespace eShop.ClientApp.ViewModels; - -public partial class CatalogViewModel : ViewModelBase -{ - private readonly IAppEnvironmentService _appEnvironmentService; - private readonly ObservableCollectionEx _brands = new(); - - private readonly ObservableCollectionEx _products = new(); - private readonly ObservableCollectionEx _types = new(); - - [ObservableProperty] private int _badgeCount; - - private bool _initialized; - - [ObservableProperty] private bool _isFiltering; - - [ObservableProperty] - [NotifyPropertyChangedFor(nameof(CanFilter))] - [NotifyCanExecuteChangedFor(nameof(ApplyFilterCommand))] - private CatalogBrand? _selectedBrand; - - [ObservableProperty] private CatalogItem? _selectedProduct; - - [ObservableProperty] - [NotifyPropertyChangedFor(nameof(CanFilter))] - [NotifyCanExecuteChangedFor(nameof(ApplyFilterCommand))] - private CatalogType? _selectedType; - - public CatalogViewModel( - IAppEnvironmentService appEnvironmentService, - INavigationService navigationService) - : base(navigationService) - { - _appEnvironmentService = appEnvironmentService; - - _products = new ObservableCollectionEx(); - _brands = new ObservableCollectionEx(); - _types = new ObservableCollectionEx(); - - WeakReferenceMessenger.Default - .Register( - this, - (_, message) => - { - BadgeCount = message.Value; - }); - } - - public bool CanFilter => SelectedBrand is not null && SelectedType is not null; - - public IReadOnlyList Products => _products; - - public IReadOnlyList Brands => _brands; - - public IReadOnlyList Types => _types; - - public override async Task InitializeAsync() - { - if (_initialized) - { - return; - } - - _initialized = true; - await IsBusyFor( - async () => - { - // Get Catalog, Brands and Types - var products = await _appEnvironmentService.CatalogService.GetCatalogAsync(); - var brands = await _appEnvironmentService.CatalogService.GetCatalogBrandAsync(); - var types = await _appEnvironmentService.CatalogService.GetCatalogTypeAsync(); - var basket = await _appEnvironmentService.BasketService.GetBasketAsync(); - - BadgeCount = basket.ItemCount; - - _products.ReloadData(products); - _brands.ReloadData(brands.Select(x => new CatalogBrandSelectionViewModel {Value = x})); - _types.ReloadData(types.Select(x => new CatalogTypeSelectionViewModel {Value = x})); - }); - } - - [RelayCommand] - private async Task ViewCatalogItemAsync(CatalogItem catalogItem) - { - SelectedProduct = null; - - if (catalogItem is null) - { - return; - } - - await NavigationService.NavigateToAsync( - "ViewCatalogItem", - new Dictionary {["CatalogItem"] = catalogItem}); - } - - [RelayCommand] - private void Filter() - { - IsFiltering = !IsFiltering; - } - - [RelayCommand] - public void SelectCatalogBrand(CatalogBrand? selectedItem) - { - foreach (var brand in Brands) - { - var isSelection = brand.Value == selectedItem; - - if (!isSelection) - { - brand.Selected = false; - continue; - } - - if (brand.Selected) - { - SelectedBrand = null; - brand.Selected = false; - continue; - } - - SelectedBrand = selectedItem; - brand.Selected = true; - } - } - - [RelayCommand] - public void SelectCatalogType(CatalogType? selectedItem) - { - foreach (var type in Types) - { - var isSelection = type.Value == selectedItem; - - if (!isSelection) - { - type.Selected = false; - continue; - } - - if (type.Selected) - { - SelectedType = null; - type.Selected = false; - continue; - } - - SelectedType = selectedItem; - type.Selected = true; - } - } - - [RelayCommand] - private async Task ApplyFilterAsync() - { - await IsBusyFor( - async () => - { - if (SelectedBrand is not null && SelectedType is not null) - { - var filteredProducts = - await _appEnvironmentService.CatalogService.FilterAsync(SelectedBrand.Id, SelectedType.Id); - _products.ReloadData(filteredProducts); - } - - IsFiltering = false; - }); - } - - [RelayCommand] - private async Task ClearFilterAsync() - { - await IsBusyFor( - async () => - { - SelectCatalogBrand(default); - SelectCatalogType(default); - var allProducts = await _appEnvironmentService.CatalogService.GetCatalogAsync(); - _products.ReloadData(allProducts); - IsFiltering = false; - }); - } - - [RelayCommand] - private async Task ViewBasket() - { - await NavigationService.NavigateToAsync("Basket"); - } -} - -public class CatalogBrandSelectionViewModel : SelectionViewModel -{ -} - -public class CatalogTypeSelectionViewModel : SelectionViewModel -{ -} diff --git a/src/ClientApp/ViewModels/CheckoutViewModel.cs b/src/ClientApp/ViewModels/CheckoutViewModel.cs deleted file mode 100644 index b4e251d6c..000000000 --- a/src/ClientApp/ViewModels/CheckoutViewModel.cs +++ /dev/null @@ -1,170 +0,0 @@ -using CommunityToolkit.Mvvm.Messaging; -using eShop.ClientApp.Messages; -using eShop.ClientApp.Models.Basket; -using eShop.ClientApp.Models.Orders; -using eShop.ClientApp.Models.User; -using eShop.ClientApp.Services; -using eShop.ClientApp.Services.AppEnvironment; -using eShop.ClientApp.Services.Settings; -using eShop.ClientApp.ViewModels.Base; - -namespace eShop.ClientApp.ViewModels; - -public partial class CheckoutViewModel : ViewModelBase -{ - private readonly IAppEnvironmentService _appEnvironmentService; - - private readonly BasketViewModel _basketViewModel; - private readonly IDialogService _dialogService; - private readonly ISettingsService _settingsService; - - [ObservableProperty] private Order _order; - - [ObservableProperty] private Address _shippingAddress; - - public CheckoutViewModel( - BasketViewModel basketViewModel, - IAppEnvironmentService appEnvironmentService, IDialogService dialogService, ISettingsService settingsService, - INavigationService navigationService) - : base(navigationService) - { - _dialogService = dialogService; - _appEnvironmentService = appEnvironmentService; - _settingsService = settingsService; - - _basketViewModel = basketViewModel; - } - - public override async Task InitializeAsync() - { - await IsBusyFor( - async () => - { - var basketItems = _appEnvironmentService.BasketService.LocalBasketItems; - - var userInfo = await _appEnvironmentService.IdentityService.GetUserInfoAsync(); - - // Create Shipping Address - ShippingAddress = new Address - { - Id = !string.IsNullOrEmpty(userInfo?.UserId) ? new Guid(userInfo.UserId) : Guid.NewGuid(), - Street = userInfo?.Street, - ZipCode = userInfo?.ZipCode, - State = userInfo?.State, - Country = userInfo?.Country, - City = userInfo?.Address - }; - - // Create Payment Info - var paymentInfo = new PaymentInfo - { - CardNumber = userInfo?.CardNumber, - CardHolderName = userInfo?.CardHolder, - CardType = new CardType {Id = 3, Name = "MasterCard"}, - SecurityNumber = userInfo?.CardSecurityNumber - }; - - var orderItems = CreateOrderItems(basketItems); - - // Create new Order - Order = new Order - { - //TODO: Get a better order number generator - OrderNumber = (int)DateTimeOffset.Now.TimeOfDay.TotalMilliseconds, - UserId = userInfo.UserId, - UserName = userInfo.PreferredUsername, - OrderItems = orderItems, - OrderStatus = "Submitted", - OrderDate = DateTime.Now, - CardHolderName = paymentInfo.CardHolderName, - CardNumber = paymentInfo.CardNumber, - CardSecurityNumber = paymentInfo.SecurityNumber, - CardExpiration = DateTime.UtcNow.AddYears(5), - CardTypeId = paymentInfo.CardType.Id, - ShippingState = ShippingAddress.State, - ShippingCountry = ShippingAddress.Country, - ShippingStreet = ShippingAddress.Street, - ShippingCity = ShippingAddress.City, - ShippingZipCode = ShippingAddress.ZipCode, - Total = CalculateTotal(orderItems) - }; - - if (_settingsService.UseMocks) - { - // Get number of orders - var orders = await _appEnvironmentService.OrderService.GetOrdersAsync(); - - // Create the OrderNumber - Order.OrderNumber = orders.Count() + 1; - OnPropertyChanged(nameof(Order)); - } - }); - } - - [RelayCommand] - private async Task CheckoutAsync() - { - try - { - var basket = _appEnvironmentService.OrderService.MapOrderToBasket(Order); - basket.RequestId = Guid.NewGuid(); - - await _appEnvironmentService.OrderService.CreateOrderAsync(Order); - - // Clean Basket - await _appEnvironmentService.BasketService.ClearBasketAsync(); - - // Reset Basket badge - await _basketViewModel.ClearBasketItems(); - - WeakReferenceMessenger.Default - .Send(new ProductCountChangedMessage(0)); - - // Navigate to Orders - await NavigationService.NavigateToAsync("//Main/Catalog"); - - // Show Dialog - await _dialogService.ShowAlertAsync("Order sent successfully!", "Checkout", "Ok"); - } - catch (Exception ex) - { - Console.WriteLine(ex); - await _dialogService.ShowAlertAsync("An error ocurred. Please, try again.", "Oops!", "Ok"); - } - } - - private static List CreateOrderItems(IEnumerable basketItems) - { - var orderItems = new List(); - - foreach (var basketItem in basketItems) - { - if (!string.IsNullOrEmpty(basketItem.ProductName)) - { - orderItems.Add(new OrderItem - { - OrderId = null, - ProductId = basketItem.ProductId, - ProductName = basketItem.ProductName, - PictureUrl = basketItem.PictureUrl, - Quantity = basketItem.Quantity, - UnitPrice = basketItem.UnitPrice - }); - } - } - - return orderItems; - } - - private static decimal CalculateTotal(List orderItems) - { - decimal total = 0; - - foreach (var orderItem in orderItems) - { - total += orderItem.Quantity * orderItem.UnitPrice; - } - - return total; - } -} diff --git a/src/ClientApp/ViewModels/LoginViewModel.cs b/src/ClientApp/ViewModels/LoginViewModel.cs deleted file mode 100644 index 07ee3e8f9..000000000 --- a/src/ClientApp/ViewModels/LoginViewModel.cs +++ /dev/null @@ -1,137 +0,0 @@ -using System.Diagnostics; -using eShop.ClientApp.Services; -using eShop.ClientApp.Services.AppEnvironment; -using eShop.ClientApp.Services.OpenUrl; -using eShop.ClientApp.Services.Settings; -using eShop.ClientApp.Validations; -using eShop.ClientApp.ViewModels.Base; - -namespace eShop.ClientApp.ViewModels; - -public partial class LoginViewModel : ViewModelBase -{ - private readonly IAppEnvironmentService _appEnvironmentService; - private readonly IOpenUrlService _openUrlService; - private readonly ISettingsService _settingsService; - - [ObservableProperty] private bool _isLogin; - - [ObservableProperty] private bool _isMock; - - [ObservableProperty] [NotifyCanExecuteChangedFor(nameof(MockSignInCommand))] - private bool _isValid; - - [ObservableProperty] private string _loginUrl; - - [ObservableProperty] private ValidatableObject _password = new(); - - [ObservableProperty] private ValidatableObject _userName = new(); - - public LoginViewModel( - IOpenUrlService openUrlService, IAppEnvironmentService appEnvironmentService, - INavigationService navigationService, ISettingsService settingsService) - : base(navigationService) - { - _settingsService = settingsService; - _openUrlService = openUrlService; - _appEnvironmentService = appEnvironmentService; - - InvalidateMock(); - } - - public override async void ApplyQueryAttributes(IDictionary query) - { - base.ApplyQueryAttributes(query); - - if (query.ValueAsBool("Logout")) - { - await PerformLogoutAsync(); - } - } - - public override Task InitializeAsync() - { - return Task.CompletedTask; - } - - [RelayCommand(CanExecute = nameof(IsValid))] - private async Task MockSignInAsync() - { - await IsBusyFor( - async () => - { - var isAuthenticated = false; - - try - { - await Task.Delay(1000); - - isAuthenticated = true; - } - catch (Exception ex) - { - Debug.WriteLine($"[SignIn] Error signing in: {ex}"); - } - - if (isAuthenticated) - { - await NavigationService.NavigateToAsync("//Main/Catalog"); - } - }); - } - - [RelayCommand] - private async Task SignInAsync() - { - await IsBusyFor( - async () => - { - var loginSuccess = await _appEnvironmentService.IdentityService.SignInAsync(); - - if (loginSuccess) - { - await NavigationService.NavigateToAsync("//Main/Catalog"); - } - }); - } - - [RelayCommand] - private Task RegisterAsync() - { - return _openUrlService.OpenUrl(_settingsService.RegistrationEndpoint); - } - - [RelayCommand] - private async Task PerformLogoutAsync() - { - await _appEnvironmentService.IdentityService.SignOutAsync(); - - _settingsService.UseFakeLocation = false; - - UserName.Value = string.Empty; - Password.Value = string.Empty; - } - - [RelayCommand] - private Task SettingsAsync() - { - return NavigationService.NavigateToAsync("Settings"); - } - - [RelayCommand] - private void Validate() - { - IsValid = UserName.Validate() && Password.Validate(); - } - - private void AddValidations() - { - UserName.Validations.Add(new IsNotNullOrEmptyRule {ValidationMessage = "A username is required."}); - Password.Validations.Add(new IsNotNullOrEmptyRule {ValidationMessage = "A password is required."}); - } - - public void InvalidateMock() - { - IsMock = false; //_settingsService.UseMocks; - } -} diff --git a/src/ClientApp/ViewModels/MainViewModel.cs b/src/ClientApp/ViewModels/MainViewModel.cs deleted file mode 100644 index 6ac7629b7..000000000 --- a/src/ClientApp/ViewModels/MainViewModel.cs +++ /dev/null @@ -1,18 +0,0 @@ -using eShop.ClientApp.Services; -using eShop.ClientApp.ViewModels.Base; - -namespace eShop.ClientApp.ViewModels; - -public partial class MainViewModel : ViewModelBase -{ - public MainViewModel(INavigationService navigationService) - : base(navigationService) - { - } - - [RelayCommand] - private async Task SettingsAsync() - { - await NavigationService.NavigateToAsync("Settings"); - } -} diff --git a/src/ClientApp/ViewModels/MapViewModel.cs b/src/ClientApp/ViewModels/MapViewModel.cs deleted file mode 100644 index 965cfce28..000000000 --- a/src/ClientApp/ViewModels/MapViewModel.cs +++ /dev/null @@ -1,37 +0,0 @@ -using eShop.ClientApp.Services; -using eShop.ClientApp.ViewModels.Base; - -namespace eShop.ClientApp.ViewModels; - -public partial class MapViewModel : ViewModelBase -{ - [ObservableProperty] private IEnumerable _stores; - - public MapViewModel(INavigationService navigationService) - : base(navigationService) - { - } - - public override Task InitializeAsync() - { - Stores = - new[] - { - new Store - { - Address = "Building 92, Redmond, WA", - Description = "Microsoft Visitor Center", - Location = new Location(47.6423109, -122.1368406) - } - }; - - return Task.CompletedTask; - } -} - -public record Store -{ - public Location Location { get; set; } - public string Address { get; set; } - public string Description { get; set; } -} diff --git a/src/ClientApp/ViewModels/ObservableCollectionEx.cs b/src/ClientApp/ViewModels/ObservableCollectionEx.cs deleted file mode 100644 index 2760d1865..000000000 --- a/src/ClientApp/ViewModels/ObservableCollectionEx.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; - -namespace eShop.ClientApp.ViewModels; - -public class ObservableCollectionEx : ObservableCollection -{ - public ObservableCollectionEx() - { - } - - public ObservableCollectionEx(IEnumerable collection) : base(collection) - { - } - - public ObservableCollectionEx(List list) : base(list) - { - } - - public void ReloadData(IEnumerable items) - { - ReloadData( - innerList => - { - foreach (var item in items) - { - innerList.Add(item); - } - }); - } - - public void ReloadData(Action> innerListAction) - { - Items.Clear(); - - innerListAction(Items); - - OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count))); - OnPropertyChanged(new PropertyChangedEventArgs("Items[]")); - OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); - } - - public async Task ReloadDataAsync(Func, Task> innerListAction) - { - Items.Clear(); - - await innerListAction(Items); - - OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count))); - OnPropertyChanged(new PropertyChangedEventArgs("Items[]")); - OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); - } -} diff --git a/src/ClientApp/ViewModels/OrderDetailViewModel.cs b/src/ClientApp/ViewModels/OrderDetailViewModel.cs deleted file mode 100644 index 47dd18532..000000000 --- a/src/ClientApp/ViewModels/OrderDetailViewModel.cs +++ /dev/null @@ -1,75 +0,0 @@ -using eShop.ClientApp.Models.Orders; -using eShop.ClientApp.Services; -using eShop.ClientApp.Services.AppEnvironment; -using eShop.ClientApp.Services.Settings; -using eShop.ClientApp.ViewModels.Base; - -namespace eShop.ClientApp.ViewModels; - -public partial class OrderDetailViewModel : ViewModelBase, IQueryAttributable -{ - private readonly IAppEnvironmentService _appEnvironmentService; - private readonly ISettingsService _settingsService; - - [ObservableProperty] private bool _isSubmittedOrder; - - [ObservableProperty] private Order _order; - - [ObservableProperty] private int _orderNumber; - - [ObservableProperty] private string _orderStatusText; - - public OrderDetailViewModel( - IAppEnvironmentService appEnvironmentService, - INavigationService navigationService, ISettingsService settingsService) - : base(navigationService) - { - _appEnvironmentService = appEnvironmentService; - _settingsService = settingsService; - } - - public override async Task InitializeAsync() - { - await IsBusyFor( - async () => - { - // Get order detail info - Order = await _appEnvironmentService.OrderService.GetOrderAsync(OrderNumber); - IsSubmittedOrder = Order.OrderStatus.Equals("Submitted", StringComparison.OrdinalIgnoreCase); - OrderStatusText = Order.OrderStatus; - }); - } - - [RelayCommand] - private async Task ToggleCancelOrderAsync() - { - var result = await _appEnvironmentService.OrderService.CancelOrderAsync(Order.OrderNumber); - - if (result) - { - OrderStatusText = "Cancelled"; - } - else - { - Order = await _appEnvironmentService.OrderService.GetOrderAsync(Order.OrderNumber); - OrderStatusText = Order.OrderStatus; - } - - IsSubmittedOrder = false; - } - - public override void ApplyQueryAttributes(IDictionary query) - { - if (query.TryGetValue("OrderNumber", out var orderNumber)) - { - if (orderNumber is string orderNumberString && int.TryParse(orderNumberString, out var parsedOrderNumber)) - { - OrderNumber = parsedOrderNumber; - } - else if (orderNumber is int intOrderNumber) - { - OrderNumber = intOrderNumber; - } - } - } -} diff --git a/src/ClientApp/ViewModels/ProfileViewModel.cs b/src/ClientApp/ViewModels/ProfileViewModel.cs deleted file mode 100644 index 0e38903a2..000000000 --- a/src/ClientApp/ViewModels/ProfileViewModel.cs +++ /dev/null @@ -1,78 +0,0 @@ -using eShop.ClientApp.Models.Orders; -using eShop.ClientApp.Services; -using eShop.ClientApp.Services.AppEnvironment; -using eShop.ClientApp.Services.Settings; -using eShop.ClientApp.ViewModels.Base; - -namespace eShop.ClientApp.ViewModels; - -public partial class ProfileViewModel : ViewModelBase -{ - private readonly IAppEnvironmentService _appEnvironmentService; - private readonly ObservableCollectionEx _orders; - private readonly ISettingsService _settingsService; - - [ObservableProperty] private Order _selectedOrder; - - public ProfileViewModel( - IAppEnvironmentService appEnvironmentService, ISettingsService settingsService, - INavigationService navigationService) - : base(navigationService) - { - _appEnvironmentService = appEnvironmentService; - _settingsService = settingsService; - - _orders = new ObservableCollectionEx(); - } - - public IList Orders => _orders; - - public override async Task InitializeAsync() - { - await RefreshAsync(); - } - - [RelayCommand] - private async Task LogoutAsync() - { - await IsBusyFor( - async () => - { - // Logout - await NavigationService.NavigateToAsync( - "//Login", - new Dictionary {{"Logout", true}}); - }); - } - - [RelayCommand] - private async Task RefreshAsync() - { - if (IsBusy) - { - return; - } - - await IsBusyFor( - async () => - { - // Get orders - var orders = await _appEnvironmentService.OrderService.GetOrdersAsync(); - - _orders.ReloadData(orders); - }); - } - - [RelayCommand] - private async Task OrderDetailAsync(Order order) - { - if (order is null || IsBusy) - { - return; - } - - await NavigationService.NavigateToAsync( - "OrderDetail", - new Dictionary {{nameof(Order.OrderNumber), order.OrderNumber}}); - } -} diff --git a/src/ClientApp/ViewModels/SelectionViewModel.cs b/src/ClientApp/ViewModels/SelectionViewModel.cs deleted file mode 100644 index 40a9fb67e..000000000 --- a/src/ClientApp/ViewModels/SelectionViewModel.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace eShop.ClientApp.ViewModels; - -public partial class SelectionViewModel : ObservableObject -{ - [ObservableProperty] private bool _selected; - [ObservableProperty] private T _value; -} diff --git a/src/ClientApp/ViewModels/SettingsViewModel.cs b/src/ClientApp/ViewModels/SettingsViewModel.cs deleted file mode 100644 index 99662a25f..000000000 --- a/src/ClientApp/ViewModels/SettingsViewModel.cs +++ /dev/null @@ -1,344 +0,0 @@ -using System.ComponentModel; -using System.Globalization; -using System.Windows.Input; -using eShop.ClientApp.Services; -using eShop.ClientApp.Services.AppEnvironment; -using eShop.ClientApp.Services.Location; -using eShop.ClientApp.Services.Settings; -using eShop.ClientApp.ViewModels.Base; -using Location = eShop.ClientApp.Models.Location.Location; - -namespace eShop.ClientApp.ViewModels; - -public class SettingsViewModel : ViewModelBase -{ - //Needed if using Android Emulator Locally. See https://learn.microsoft.com/en-us/dotnet/maui/data-cloud/local-web-services?view=net-maui-8.0#android - private static string _baseAddress = DeviceInfo.Platform == DevicePlatform.Android ? "10.0.2.2" : "localhost"; - - private readonly IAppEnvironmentService _appEnvironmentService; - private readonly ILocationService _locationService; - private readonly ISettingsService _settingsService; - private bool _allowGpsLocation; - private string _gatewayBasketEndpoint; - private string _gatewayCatalogEndpoint; - private string _gatewayOrdersEndpoint; - private string _gpsWarningMessage; - private string _identityEndpoint; - private double _latitude; - private double _longitude; - - private bool _useAzureServices; - private bool _useFakeLocation; - - public SettingsViewModel( - ILocationService locationService, IAppEnvironmentService appEnvironmentService, - INavigationService navigationService, ISettingsService settingsService) - : base(navigationService) - { - _settingsService = settingsService; - _locationService = locationService; - _appEnvironmentService = appEnvironmentService; - - _useAzureServices = !_settingsService.UseMocks; - _identityEndpoint = _settingsService.IdentityEndpointBase; - _latitude = double.Parse(_settingsService.Latitude, CultureInfo.CurrentCulture); - _longitude = double.Parse(_settingsService.Longitude, CultureInfo.CurrentCulture); - _useFakeLocation = _settingsService.UseFakeLocation; - _allowGpsLocation = _settingsService.AllowGpsLocation; - _gpsWarningMessage = string.Empty; - - IdentityEndpoint = - !string.IsNullOrEmpty(_settingsService.IdentityEndpointBase) - ? _settingsService.IdentityEndpointBase - : $"https://{_baseAddress}:5243"; - - GatewayCatalogEndpoint = - !string.IsNullOrEmpty(_settingsService.GatewayCatalogEndpointBase) - ? _settingsService.GatewayCatalogEndpointBase - : $"http://{_baseAddress}:11632"; - - GatewayBasketEndpoint = - !string.IsNullOrEmpty(_settingsService.GatewayBasketEndpointBase) - ? _settingsService.GatewayBasketEndpointBase - : $"http://{_baseAddress}:5221"; - - GatewayOrdersEndpoint = - !string.IsNullOrEmpty(_settingsService.GatewayOrdersEndpointBase) - ? _settingsService.GatewayOrdersEndpointBase - : $"http://{_baseAddress}:11632"; - - ToggleMockServicesCommand = new RelayCommand(ToggleMockServices); - - ToggleFakeLocationCommand = new RelayCommand(ToggleFakeLocation); - - ToggleSendLocationCommand = new AsyncRelayCommand(ToggleSendLocationAsync); - - ToggleAllowGpsLocationCommand = new RelayCommand(ToggleAllowGpsLocation); - - UseAzureServices = !_settingsService.UseMocks; - } - - public string TitleUseAzureServices => "Use Microservices/Containers from eShop"; - - public string DescriptionUseAzureServices => !UseAzureServices - ? "Currently using mock services that are simulated objects that mimic the behavior of real services using a controlled approach. Toggle on to configure the use of microserivces/containers." - : "When enabling the use of microservices/containers, the app will attempt to use real services deployed as Docker/Kubernetes containers at the specified base endpoint, which will must be reachable through the network."; - - public bool UseAzureServices - { - get => _useAzureServices; - set - { - SetProperty(ref _useAzureServices, value); - UpdateUseAzureServices(); - } - } - - public string TitleUseFakeLocation => !UseFakeLocation - ? "Use Real Location" - : "Use Fake Location"; - - public string DescriptionUseFakeLocation => !UseFakeLocation - ? "When enabling location, the app will attempt to use the location from the device." - : "Fake Location data is added for marketing campaign testing."; - - public bool UseFakeLocation - { - get => _useFakeLocation; - set - { - SetProperty(ref _useFakeLocation, value); - UpdateFakeLocation(); - } - } - - public string TitleAllowGpsLocation => !AllowGpsLocation - ? "GPS Location Disabled" - : "GPS Location Enabled"; - - public string DescriptionAllowGpsLocation => !AllowGpsLocation - ? "When disabling location, you won't receive location campaigns based upon your location." - : "When enabling location, you'll receive location campaigns based upon your location."; - - public string GpsWarningMessage - { - get => _gpsWarningMessage; - set => SetProperty(ref _gpsWarningMessage, value); - } - - public string IdentityEndpoint - { - get => _identityEndpoint; - set - { - SetProperty(ref _identityEndpoint, value); - if (!string.IsNullOrEmpty(value)) - { - UpdateIdentityEndpoint(); - } - } - } - - public string GatewayCatalogEndpoint - { - get => _gatewayCatalogEndpoint; - set - { - SetProperty(ref _gatewayCatalogEndpoint, value); - if (!string.IsNullOrEmpty(value)) - { - UpdateGatewayShoppingEndpoint(); - } - } - } - - public string GatewayOrdersEndpoint - { - get => _gatewayOrdersEndpoint; - set - { - SetProperty(ref _gatewayOrdersEndpoint, value); - if (!string.IsNullOrEmpty(value)) - { - UpdateGatewayOrdersEndpoint(); - } - } - } - - public string GatewayBasketEndpoint - { - get => _gatewayBasketEndpoint; - set - { - SetProperty(ref _gatewayBasketEndpoint, value); - if (!string.IsNullOrEmpty(value)) - { - UpdateGatewayBasketEndpoint(); - } - } - } - - public double Latitude - { - get => _latitude; - set - { - SetProperty(ref _latitude, value); - UpdateLatitude(); - } - } - - public double Longitude - { - get => _longitude; - set - { - SetProperty(ref _longitude, value); - UpdateLongitude(); - } - } - - public bool AllowGpsLocation - { - get => _allowGpsLocation; - set => SetProperty(ref _allowGpsLocation, value); - } - - public ICommand ToggleMockServicesCommand { get; } - - public ICommand ToggleFakeLocationCommand { get; } - - public ICommand ToggleSendLocationCommand { get; } - - public ICommand ToggleAllowGpsLocationCommand { get; } - - protected override async void OnPropertyChanged(PropertyChangedEventArgs e) - { - base.OnPropertyChanged(e); - - if (e.PropertyName == nameof(AllowGpsLocation)) - { - await UpdateAllowGpsLocation(); - } - } - - private void ToggleMockServices() - { - _appEnvironmentService.UpdateDependencies(!UseAzureServices); - - OnPropertyChanged(nameof(TitleUseAzureServices)); - OnPropertyChanged(nameof(DescriptionUseAzureServices)); - } - - private void ToggleFakeLocation() - { - _appEnvironmentService.UpdateDependencies(!UseAzureServices); - OnPropertyChanged(nameof(TitleUseFakeLocation)); - OnPropertyChanged(nameof(DescriptionUseFakeLocation)); - } - - private async Task ToggleSendLocationAsync() - { - if (!_settingsService.UseMocks) - { - var locationRequest = new Location {Latitude = _latitude, Longitude = _longitude}; - - await _locationService.UpdateUserLocation(locationRequest); - } - } - - private void ToggleAllowGpsLocation() - { - OnPropertyChanged(nameof(TitleAllowGpsLocation)); - OnPropertyChanged(nameof(DescriptionAllowGpsLocation)); - } - - private void UpdateUseAzureServices() - { - // Save use mocks services to local storage - _settingsService.UseMocks = !UseAzureServices; - } - - private void UpdateIdentityEndpoint() - { - // Update remote endpoint (save to local storage) - _settingsService.IdentityEndpointBase = _identityEndpoint; - } - - private void UpdateGatewayShoppingEndpoint() - { - _settingsService.GatewayCatalogEndpointBase = _gatewayCatalogEndpoint; - } - - private void UpdateGatewayOrdersEndpoint() - { - _settingsService.GatewayOrdersEndpointBase = _gatewayOrdersEndpoint; - } - - private void UpdateGatewayBasketEndpoint() - { - _settingsService.GatewayBasketEndpointBase = _gatewayBasketEndpoint; - } - - private void UpdateFakeLocation() - { - _settingsService.UseFakeLocation = _useFakeLocation; - } - - private void UpdateLatitude() - { - // Update fake latitude (save to local storage) - _settingsService.Latitude = _latitude.ToString(); - } - - private void UpdateLongitude() - { - // Update fake longitude (save to local storage) - _settingsService.Longitude = _longitude.ToString(); - } - - private async Task UpdateAllowGpsLocation() - { - if (_allowGpsLocation) - { - bool hasWhenInUseLocationPermissions; - bool hasBackgroundLocationPermissions; - - if (await Permissions.CheckStatusAsync() != PermissionStatus.Granted) - { - hasWhenInUseLocationPermissions = await Permissions.RequestAsync() == - PermissionStatus.Granted; - } - else - { - hasWhenInUseLocationPermissions = true; - } - - if (await Permissions.CheckStatusAsync() != PermissionStatus.Granted) - { - hasBackgroundLocationPermissions = await Permissions.RequestAsync() == - PermissionStatus.Granted; - } - else - { - hasBackgroundLocationPermissions = true; - } - - - if (!hasWhenInUseLocationPermissions || !hasBackgroundLocationPermissions) - { - _allowGpsLocation = false; - GpsWarningMessage = "Enable the GPS sensor on your device"; - } - else - { - _settingsService.AllowGpsLocation = _allowGpsLocation; - GpsWarningMessage = string.Empty; - } - } - else - { - _settingsService.AllowGpsLocation = _allowGpsLocation; - } - } -} diff --git a/src/ClientApp/Views/BadgeView.cs b/src/ClientApp/Views/BadgeView.cs deleted file mode 100644 index c25e97bd0..000000000 --- a/src/ClientApp/Views/BadgeView.cs +++ /dev/null @@ -1,140 +0,0 @@ -using Microsoft.Maui.Controls.Shapes; - -namespace eShop.ClientApp.Views; - -[ContentProperty(nameof(Content))] -public class BadgeView : Grid -{ - public static BindableProperty ContentProperty = - BindableProperty.Create(nameof(Content), typeof(View), typeof(BadgeView), - propertyChanged: OnLayoutPropertyChanged); - - public static BindableProperty TextProperty = - BindableProperty.Create(nameof(Text), typeof(string), typeof(BadgeView), - propertyChanged: OnLayoutPropertyChanged); - - public static BindableProperty TextColorProperty = - BindableProperty.Create(nameof(TextColor), typeof(Color), typeof(BadgeView), - propertyChanged: OnLayoutPropertyChanged); - - public static BindableProperty FontSizeProperty = - BindableProperty.Create(nameof(FontSize), typeof(double), typeof(BadgeView), 10.0d, - propertyChanged: OnLayoutPropertyChanged); - - public static BindableProperty BadgeColorProperty = - BindableProperty.Create(nameof(BadgeColor), typeof(Color), typeof(BadgeView), - propertyChanged: OnLayoutPropertyChanged); - - private readonly Label _badgeIndicator; - private readonly Border _border; - private readonly RoundRectangle _borderShape; - - public BadgeView() - { - _badgeIndicator = - new Label - { - Padding = 4, - HorizontalTextAlignment = TextAlignment.Center, - VerticalTextAlignment = TextAlignment.Center - }; - - _borderShape = new RoundRectangle(); - - _border = - new Border - { - StrokeShape = _borderShape, - Content = _badgeIndicator, - HorizontalOptions = LayoutOptions.End, - VerticalOptions = LayoutOptions.Start, - ZIndex = 10 - }; - - Children.Add(_border); - - UpdateLayout(); - } - - public View Content - { - get => (View)GetValue(ContentProperty); - set => SetValue(ContentProperty, value); - } - - public string Text - { - get => (string)GetValue(TextProperty); - set => SetValue(TextProperty, value); - } - - public Color TextColor - { - get => (Color)GetValue(TextColorProperty); - set => SetValue(TextColorProperty, value); - } - - public double FontSize - { - get => (double)GetValue(FontSizeProperty); - set => SetValue(FontSizeProperty, value); - } - - public Color BadgeColor - { - get => (Color)GetValue(BadgeColorProperty); - set => SetValue(BadgeColorProperty, value); - } - - private static void OnLayoutPropertyChanged(BindableObject bindable, object oldValue, object newValue) - { - (bindable as BadgeView)?.UpdateLayout(); - } - - protected override void OnHandlerChanging(HandlerChangingEventArgs args) - { - base.OnHandlerChanging(args); - - _border.SizeChanged -= BadgeIndicatorSizeChanged; - - if (args.NewHandler is not null) - { - _border.SizeChanged += BadgeIndicatorSizeChanged; - } - } - - private void BadgeIndicatorSizeChanged(object sender, EventArgs e) - { - var halfHeight = _border.Height * .5f; - _border.MinimumWidthRequest = _border.Height; - _borderShape.CornerRadius = halfHeight; - - if (Content is not null) - { - Content.Margin = halfHeight; - } - } - - private void UpdateLayout() - { - BatchBegin(); - _border.BatchBegin(); - _badgeIndicator.BatchBegin(); - - if (Content is not null && Content.Parent != this) - { - Content.ZIndex = 1; - Children.Add(Content); - } - - _border.BackgroundColor = BadgeColor; - - _badgeIndicator.Text = Text; - _badgeIndicator.TextColor = TextColor; - _badgeIndicator.FontSize = FontSize; - - _border.BatchCommit(); - _badgeIndicator.BatchCommit(); - BatchCommit(); - } -} diff --git a/src/ClientApp/Views/BasketView.xaml b/src/ClientApp/Views/BasketView.xaml deleted file mode 100644 index 5ff5007fa..000000000 --- a/src/ClientApp/Views/BasketView.xaml +++ /dev/null @@ -1,98 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/ClientApp/Views/FiltersView.xaml.cs b/src/ClientApp/Views/FiltersView.xaml.cs deleted file mode 100644 index 7d0f15cb3..000000000 --- a/src/ClientApp/Views/FiltersView.xaml.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace eShop.ClientApp.Views; - -public partial class FiltersView : ContentPage -{ - public FiltersView(CatalogViewModel viewModel) - { - BindingContext = viewModel; - - InitializeComponent(); - } -} diff --git a/src/ClientApp/Views/LoginView.xaml b/src/ClientApp/Views/LoginView.xaml deleted file mode 100644 index e6bc05455..000000000 --- a/src/ClientApp/Views/LoginView.xaml +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -