# Conflicts: # README.md # docs/Enterprise-Application-Patterns-using-XamarinForms.pdf # docs/architecting-and-developing-containerized-and-microservice-based-net-applications-ebook-early-draft.pdfpull/235/head
@ -0,0 +1,134 @@ | |||
# Kubernetes 101 | |||
## Docker vs. Kubernetes | |||
Docker helps you package applications into images, and execute them in containers. Kubernetes is a robust platform for containerized applications. It abstracts away the underlying network infrastructure and hardware required to run them, simplifying their deployment, scaling, and management. | |||
## Kubernetes from the container up | |||
### Pods | |||
The basic unit of a Kubernetes deployment is the **Pod**. A Pod encapsulates one or more containers. For example, the `basket` Pod specifies two containers: | |||
>`deployments.yaml` | |||
> | |||
>The first container runs the `eshop/basket.api` image: | |||
>```yaml | |||
>spec: | |||
> containers: | |||
> - name: basket | |||
> image: eshop/basket.api | |||
> env: | |||
> - name: ConnectionString | |||
> value: 127.0.0.1 | |||
>``` | |||
>Note the `ConnectionString` environment variable: containers within a Pod are networked via `localhost`. The second container runs the `redis` image: | |||
>```yaml | |||
>- name: basket-data | |||
> image: redis:3.2-alpine | |||
> ports: | |||
> - containerPort: 6379 | |||
>``` | |||
Placing `basket` and `basket-data` in the same Pod is reasonable here because the former requires the latter, and owns all its data. If we wanted to scale the service, however, it would be better to place the containers in separate Pods because the basket API and redis scale at different rates. | |||
If the containers were in separate Pods, they would no longer be able to communicate via `localhost`; a **Service** would be required. | |||
### Services | |||
Services expose Pods to external networks. For example, the `basket` Service exposes Pods with labels `app=eshop` and `component=basket` to the cluster at large: | |||
>`services.yaml` | |||
>```yaml | |||
>kind: Service | |||
>metadata: | |||
> ... | |||
> name: basket | |||
>spec: | |||
> ports: | |||
> - port: 80 | |||
> selector: | |||
> app: eshop | |||
> component: basket | |||
>``` | |||
Kubernetes's built-in DNS service resolves Service names to cluster-internal IP addresses. This allows the nginx frontend to proxy connections to the app's microservices by name: | |||
>`nginx.conf` | |||
>``` | |||
>location /basket-api { | |||
> proxy_pass http://basket; | |||
>``` | |||
The frontend Pod is different in that it needs to be exposed outside the cluster. This is accomplished with another Service: | |||
>`frontend.yaml` | |||
>```yaml | |||
>spec: | |||
> ports: | |||
> - port: 80 | |||
> targetPort: 8080 | |||
> selector: | |||
> app: eshop | |||
> component: frontend | |||
> type: LoadBalancer | |||
>``` | |||
`type: LoadBalancer` tells Kubernetes to expose the Service behind a load balancer appropriate for the cluster's platform. For Azure Container Service, this creates an Azure load balancer rule with a public IP. | |||
### Deployments | |||
Kubernetes uses Pods to organize containers, and Services to network them. It uses **Deployments** to organize creating, and modifying, Pods. A Deployment describes a state of one or more Pods. When a Deployment is created or modified, Kubernetes attempts to realize that state. | |||
The Deployments in this project are basic. Still, `deploy.ps1` shows some more advanced Deployment capabilities. For example, Deployments can be paused. Each Deployment of this app is paused at creation: | |||
>`deployments.yaml` | |||
>```yaml | |||
>kind: Deployment | |||
>spec: | |||
> paused: true | |||
>``` | |||
This allows the deployment script to change images before Kubernetes creates the Pods: | |||
>`deploy.ps1` | |||
>```powershell | |||
>kubectl set image -f deployments.yaml basket=$registry/basket.api ... | |||
>kubectl rollout resume -f deployments.yaml | |||
>``` | |||
### ConfigMaps | |||
A **ConfigMap** is a collection of key/value pairs commonly used to provide configuration information to Pods. The deployment script uses one to store the frontend's configuration: | |||
>`deploy.ps1` | |||
>``` | |||
>kubectl create configmap config-files from-file=nginx-conf=nginx.conf | |||
>``` | |||
This creates a ConfigMap named `config-files` with key `nginx-conf` whose value is the content of nginx.conf. The frontend Pod mounts that value as `/etc/nginx/nginx.conf`: | |||
>`frontend.yaml` | |||
>```yaml | |||
>spec: | |||
> containers: | |||
> - name: nginx | |||
> ... | |||
> volumeMounts: | |||
> - name: config | |||
> mountPath: /etc/nginx | |||
> volumes: | |||
> - name: config | |||
> configMap: | |||
> name: config-files | |||
> items: | |||
> - key: nginx-conf | |||
> path: nginx.conf | |||
>``` | |||
This facilitates rapid iteration better than other techniques, e.g. building an image to bake in configuration. | |||
The script also stores public URLs for the app's components in a ConfigMap: | |||
>`deploy.ps1` | |||
>```powershell | |||
>kubectl create configmap urls --from-literal=BasketUrl=http://$($frontendUrl)/basket-api ... | |||
>``` | |||
>Here's how the `webspa` Deployment uses it: | |||
> | |||
>`deployments.yaml` | |||
>```yaml | |||
>spec: | |||
> containers: | |||
> - name: webspa | |||
> ... | |||
> env: | |||
> ... | |||
> - name: BasketUrl | |||
> valueFrom: | |||
> configMapKeyRef: | |||
> name: urls | |||
> key: BasketUrl | |||
>``` | |||
### Further reading | |||
* [Kubernetes Concepts](https://kubernetes.io/docs/concepts/) | |||
* [kubectl for Docker Users](https://kubernetes.io/docs/user-guide/docker-cli-to-kubectl/) | |||
* [Kubernetes API reference](https://kubernetes.io/docs/api-reference/v1.5/) |
@ -0,0 +1,28 @@ | |||
# eShopOnContainers on Kubernetes | |||
The k8s directory contains Kubernetes configuration for the eShopOnContainers app and a PowerShell script to deploy it to a cluster. Each eShopOnContainers microservice has a deployment configuration in `deployments.yaml`, and is exposed to the cluster by a service in `services.yaml`. The microservices are exposed externally on individual routes (`/basket-api`, `/webmvc`, etc.) by an nginx reverse proxy specified in `frontend.yaml` and `nginx.conf`. | |||
## Prerequisites | |||
* A Kubernetes cluster. Follow Azure Container Service's [walkthrough](https://docs.microsoft.com/en-us/azure/container-service/container-service-kubernetes-walkthrough) to create one. | |||
* A private Docker registry. Follow Azure Container Registry's [guide](https://docs.microsoft.com/en-us/azure/container-registry/container-registry-get-started-portal) to create one. | |||
* Optionally, previous steps can be skipped if you run gen-k8s-env.ps1 script to automatically create the azure environment needed for kubernetes deployment. Azure cli 2.0 must be previously installed [installation guide](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli). For example: | |||
>``` | |||
>./gen-k8s-env -resourceGroupName k8sGroup -location westeurope -registryName k8sregistry -orchestratorName k8s-cluster -dnsName k8s-dns | |||
>``` | |||
* A Docker development environment with `docker` and `docker-compose`. | |||
* Visit [docker.com](https://docker.com) to download the tools and set up the environment. Docker's [installation guide](https://docs.docker.com/engine/getstarted/step_one/#step-3-verify-your-installation) covers verifying your Docker installation. | |||
* The Kubernetes command line client, `kubectl`. | |||
* This can be installed with the `az` tool as described in the Azure Container Service [walkthrough](https://docs.microsoft.com/en-us/azure/container-service/container-service-kubernetes-walkthrough). `az` is also helpful for getting the credentials `kubectl` needs to access your cluster. For other installation options, and information about configuring `kubectl` yourself, see the [Kubernetes documentation](https://kubernetes.io/docs/tasks/kubectl/install/). | |||
## Deploy the application with the deployment script | |||
1. Open a PowerShell command line at the `k8s` directory of your local eShopOnContainers repository. | |||
1. Ensure `docker`, `docker-compose`, and `kubectl` are on the path, and configured for your Docker machine and Kubernetes cluster. | |||
1. Run `deploy.ps1` with your registry information. The Docker username and password are provided by Azure Container Registry, and can be retrieved from the Azure portal. Optionally, ACR credentials can be obtained by running the following command: | |||
>``` | |||
>az acr credential show -n eshopregistry | |||
>``` | |||
Once the user and password are retrieved, run the following script for deployment. For example: | |||
>``` | |||
>./deploy.ps1 -registry myregistry.azurecr.io -dockerUser User -dockerPassword SecretPassword | |||
>``` | |||
The script will build the code and corresponding Docker images, push the latter to your registry, and deploy the application to your cluster. You can watch the deployment unfold from the Kubernetes web interface: run `kubectl proxy` and open a browser to [http://localhost:8001/ui](http://localhost:8001/ui) |
@ -1,25 +1,121 @@ | |||
# eShopOnContainers for Azure | |||
Azure-based version og the eShopOnContainers reference application | |||
**Please refer to the [original eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers) for general info about the project** | |||
# eShopOnContainers - Microservices Architecture and Containers based Reference Application (**BETA state** - Visual Studio 2017 and CLI environments compatible) | |||
Sample .NET Core reference application, powered by Microsoft, based on a simplified microservices architecture and Docker containers. <p> | |||
**Note for Pull Requests**: We accept pull request from the community. When doing it, please do it onto the DEV branch which is the consolidated work-in-progress branch. Do not request it onto Master, if possible. | |||
> ### DISCLAIMER | |||
> **IMPORTANT:** The current state of this sample application is **BETA**, consider it version a 0.1 foundational version, therefore, many areas could be improved and change significantly while refactoring current code and implementing new features. **Feedback with improvements and pull requests from the community will be highly appreciated and accepted.** | |||
> | |||
> This reference application proposes a simplified microservice oriented architecture implementation to introduce technologies like .NET Core with Docker containers through a comprehensive application. The chosen domain is an eShop/eCommerce but simply because it is a well-know domain by most people/developers. | |||
However, this sample application should not be considered as an "eCommerce reference model", at all. The implemented business domain might not be ideal from an eCommerce business point of view. It is neither trying to solve all the problems in a large, scalable and mission-critical distributed system. It is just a bootstrap for developers to easily get started in the world of Docker containers and microservices with .NET Core. | |||
> <p>For example, the next step (still not covered in eShopOnContainers) after understanding Docker containers and microservices development with .NET Core, is to select a microservice cluster/orchestrator like Docker Swarm, Kubernetes or DC/OS (in Azure Container Service) or Azure Service Fabric which in most of the cases will require additional partial changes to your application's configuration (although the present architecture should work on most orchestrators with small changes). | |||
> Additional steps would be to move your databases to HA cloud services, or to implement your EventBus with Azure Service Bus or any other production ready Service Bus in the market. | |||
> <p> In the future we might fork this project and make multiple versions targeting specific microservice cluster/orchestrators plus using additional cloud infrastructure. <p> | |||
> <img src="img/exploring-to-production-ready.png"> | |||
> Read the planned <a href='https://github.com/dotnet/eShopOnContainers/wiki/01.-Roadmap-and-Milestones-for-future-releases'>Roadmap and Milestones for future releases of eShopOnContainers</a> within the Wiki for further info about possible new implementations and provide feedback at the <a href='https://github.com/dotnet/eShopOnContainers/issues'>ISSUES section</a> if you'd like to see any specific scenario implemented or improved. Also, feel free to discuss on any current issue. | |||
**Architecture overview**: This reference application is cross-platform either at the server and client side, thanks to .NET Core services capable of running on Linux or Windows containers depending on your Docker host, and to Xamarin for mobile apps running on Android, iOS or Windows/UWP plus any browser for the client web apps. | |||
The architecture proposes a simplified microservice oriented architecture implementation with multiple autonomous microservices (each one owning its own data/db) and implementing different approaches within each microservice (simple CRUD vs. DDD/CQRS patterns) using Http as the current communication protocol. | |||
<p> | |||
It also supports asynchronous communication for data updates propagation across multiple services based on Integration Events and an Event Bus plus other features defined at the <a href='https://github.com/dotnet/eShopOnContainers/wiki/01.-Roadmap-and-Milestones-for-future-releases'>roadmap</a>. | |||
<p> | |||
<img src="img/eshop_logo.png"> | |||
<img src="img/eShopOnContainers_Architecture_Diagram.png"> | |||
<p> | |||
The microservices are different in type, meaning different internal architecture patterns approaches depending on it purpose, as shown in the image below. | |||
<p> | |||
<img src="img/eShopOnContainers_Types_Of_Microservices.png"> | |||
<p> | |||
<p> | |||
Additional miroservice styles with other frameworks and No-SQL databases will be added, eventually. This is a great opportunity for pull requests from the community, like a new microservice using Nancy, or even other languages like Node, Go, Python or data containers with MongoDB with Azure DocDB compatibility, PostgreSQL, RavenDB, Event Store, MySql, etc. You name it! :) | |||
> ### Important Note on Database Servers/Containers | |||
> In this solution's current configuration for a development environment, the SQL databases are automatically deployed with sample data into a single SQL Server for Linux container (a single shared Docker container for SQL databases) so the whole solution can be up and running without any dependency to any cloud or specific server. Each database could also be deployed as a single Docker container, but then you'd need more then 8GB or memory RAM assigned to Docker in your development machine in order to be able to run 3 SQL Server Docker containers in your Docker Linux host in "Docker for Windows" or "Docker for Mac" development environments. | |||
> <p> A similar case is defined in regards Redis cache running as a container for the development environment. | |||
> <p> However, in a real production environment it is recommended to have your databases (SQL Server and Redis, in this case) in HA (High Available) services like Azure SQL Database, Redis as a service or any other clustering system. If you want to change to a production configuration, you'll just need to change the connection strings once you have set up the servers in a HA cloud or on-premises. | |||
## Related documentation and guidance | |||
While developing this reference application, we've been creating a reference <b>Guide/eBook</b> focusing on <b>architecting and developing containerized and microservice based .NET Applications</b> (download link available below) which explains in detail how to develop this kind of architectural style (microservices, Docker containers, Domain-Driven Design for certain microservices) plus other simpler architectural styles, like monolithic apps that can also live as Docker containers. | |||
<p> | |||
There are also additional eBooks focusing on Containers/Docker lifecycle (DevOps, CI/CD, etc.) with Microsoft Tools, already published plus an additional eBook focusing on Enterprise Apps Patterns with Xamarin.Forms. | |||
You can download them and start reviewing these Guides/eBooks here: | |||
<p> | |||
| Architecting & Developing | Containers Lifecycle & CI/CD | App patterns with Xamarin.Forms | | |||
| ------------ | ------------| ------------| | |||
| <a href='https://aka.ms/microservicesebook'><img src="img/ebook_arch_dev_microservices_containers_cover.png"> </a> | <a href='https://aka.ms/dockerlifecycleebook'> <img src="img/ebook_containers_lifecycle.png"> </a> | <a href='https://aka.ms/xamarinpatternsebook'> <img src="img/xamarin-enterprise-patterns-ebook-cover-small.png"> </a> | | |||
| <sup> <a href='https://aka.ms/microservicesebook'>**Download** (Early DRAFT, still work in progress)</a> </sup> | <sup> <a href='https://aka.ms/dockerlifecycleebook'>**Download** (First Edition from late 2016) </a> </sup> | <sup> <a href='https://aka.ms/xamarinpatternsebook'>**Download** (Preview Edition) </a> </sup> | | |||
Send feedback to [dotnet-architecture-ebooks-feedback@service.microsoft.com](dotnet-architecture-ebooks-feedback@service.microsoft.com) | |||
<p> | |||
However, we encourage to download and review the "Architecting & Developing eBook" because the architectural styles and architectural patterns and technologies explained in the guidance are using this reference application when explaining many pattern implementations, so you'll understand much better the context, design and decisions taken in the current architecture and internal designs. | |||
## Overview of the application code | |||
In this repo you can find a sample reference application that will help you to understand how to implement a microservice architecture based application using <b>.NET Core</b> and <b>Docker</b>. | |||
The example business domain or scenario is based on an eShop or eCommerce which is implemented as a multi-container application. Each container is a microservice deployment (like the basket-microservice, catalog-microservice, ordering-microservice and the identity-microservice) which are developed using ASP.NET Core running on .NET Core so they can run either on Linux Containers and Windows Containers. | |||
The screenshot below shows the VS Solution structure for those microservices/containers and client apps. | |||
## WHAT IS ON THIS REPO? | |||
This repo contains an implementation of eShopOnContainers using Azure services when applicable. Its code is synced periodically with the code of [eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers). Also unique features using Azure services will be implemented in this repo (while generic features will be | |||
implemented on _eShopOnContainers_ and integrated in this repo). | |||
- (*Recommended when getting started*) Open <b>eShopOnContainers-ServicesAndWebApps.sln</b> for a solution containing just the server-side projects related to the microservices and web applications. | |||
- Open <b>eShopOnContainers-MobileApps.sln</b> for a solution containing just the client mobile app projects (Xamarin mobile apps only). It works independently based on mocks, too. | |||
- Open <b>eShopOnContainers.sln</b> for a solution containing all the projects (All client apps and services). | |||
This repo also contains scripts for an autometed deploy of all Azure resources and information about how to configure a CI/CD pipeline. | |||
<img src="img/vs-solution-structure.png"> | |||
Status of this repo is in **early development**. | |||
Finally, those microservices are consumed by multiple client web and mobile apps, as described below. | |||
<br> | |||
<b>*MVC Application (ASP.NET Core)*</b>: Its an MVC application where you can find interesting scenarios on how to consume HTTP-based microservices from C# running in the server side, as it is a typical ASP.NET Core MVC application. Since it is a server-side application, access to other containers/microservices is done within the internal Docker Host network with its internal name resolution. | |||
<img src="img/eshop-webmvc-app-screenshot.png"> | |||
<br> | |||
<b>*SPA (Single Page Application)*</b>: Providing similar "eShop business functionality" but developed with Angular 2, Typescript and slightly using ASP.NET Core MVC. This is another approach for client web applications to be used when you want to have a more modern client behavior which is not behaving with the typical browser round-trip on every action but behaving like a Single-Page-Application which is more similar to a desktop app usage experience. The consumption of the HTTP-based microservices is done from TypeScript/JavaScript in the client browser, so the client calls to the microservices come from out of the Docker Host internal network (Like from your network or even from the Internet). | |||
<img src="img/eshop-webspa-app-screenshot.png"> | |||
<br> | |||
<b>*Xamarin Mobile App (For iOS, Android and Windows/UWP)*</b>: It is a client mobile app supporting the most common mobile OS platforms (iOS, Android and Windows/UWP). In this case, the consumption of the microservices is done from C# but running on the client devices, so out of the Docker Host internal network (Like from your network or even the Internet). | |||
## HOW TO CONTRIBUTE | |||
<img src="img/xamarin-mobile-App.png"> | |||
## Setting up your development environment for eShopOnContainers | |||
### Visual Studio 2017 and Windows based | |||
This is the more straightforward way to get started: | |||
https://github.com/dotnet/eShopOnContainers/wiki/02.-Setting-eShopOnContainer-solution-up-in-a-Visual-Studio-2017-environment | |||
### CLI and Windows based | |||
For those who prefer the CLI on Windows, using dotnet CLI, docker CLI and VS Code for Windows: | |||
https://github.com/dotnet/eShopOnContainers/wiki/03.-Setting-the-eShopOnContainers-solution-up-in-a-Windows-CLI-environment-(dotnet-CLI,-Docker-CLI-and-VS-Code) | |||
### CLI and Mac based | |||
For those who prefer the CLI on a Mac, using dotnet CLI, docker CLI and VS Code for Mac | |||
(Instructions still TBD, but similar to Windows CLI): | |||
https://github.com/dotnet/eShopOnContainers/wiki/04.-Setting-eShopOnContainer-solution-up-in-a-Mac,-VS-Code-and-CLI-environment--(dotnet-CLI,-Docker-CLI-and-VS-Code) | |||
> ### Note on tested Docker Containers/Images | |||
> Most of the development and testing of this project was (as of early March 2017) done <b> on Docker Linux containers</b> running in development machines with "Docker for Windows" and the default Hyper-V Linux VM (MobiLinuxVM) installed by "Docker for Windows". | |||
The <b>Windows Containers scenario is currently being implemented/tested yet</b>. The application should be able to run on Windows Nano Containers based on different Docker base images, as well, as the .NET Core services have also been tested running on plain Windows (with no Docker). | |||
The app was also partially tested on "Docker for Mac" using a development MacOS machine with .NET Core and VS Code installed, which is still a scenario using Linux containers running on the VM setup in the Mac by the "Docker for Windows" setup. But further testing and feedback on Mac environments and Windows Containers, from the community, will be appreciated. | |||
## Kubernetes | |||
The k8s directory contains Kubernetes configuration for the eShopOnContainers app and a PowerShell script to deploy it to a cluster. Each eShopOnContainers microservice has a deployment configuration in `deployments.yaml`, and is exposed to the cluster by a service in `services.yaml`. The microservices are exposed externally on individual routes (`/basket-api`, `/webmvc`, etc.) by an nginx reverse proxy specified in `frontend.yaml` and `nginx.conf`. | |||
### Prerequisites | |||
* A Kubernetes cluster. Follow Azure Container Service's [walkthrough](https://docs.microsoft.com/en-us/azure/container-service/container-service-kubernetes-walkthrough) to create one. | |||
* A private Docker registry. Follow Azure Container Registry's [guide](https://docs.microsoft.com/en-us/azure/container-registry/container-registry-get-started-portal) to create one. | |||
* A Docker development environment with `docker` and `docker-compose`. | |||
* Visit [docker.com](https://docker.com) to download the tools and set up the environment. Docker's [installation guide](https://docs.docker.com/engine/getstarted/step_one/#step-3-verify-your-installation) covers verifying your Docker installation. | |||
* The Kubernetes command line client, `kubectl`. | |||
* This can be installed with the `az` tool as described in the Azure Container Service [walkthrough](https://docs.microsoft.com/en-us/azure/container-service/container-service-kubernetes-walkthrough). `az` is also helpful for getting the credentials `kubectl` needs to access your cluster. For other installation options, and information about configuring `kubectl` yourself, see the [Kubernetes documentation](https://kubernetes.io/docs/tasks/kubectl/install/). | |||
### Deploy the application with the deployment script | |||
1. Open a PowerShell command line at the `k8s` directory of your local eShopOnContainers repository. | |||
1. Ensure `docker`, `docker-compose`, and `kubectl` are on the path, and configured for your Docker machine and Kubernetes cluster. | |||
1. Run `deploy.ps1` with your registry information. The Docker username and password are provided by Azure Container Registry, and can be retrieved from the Azure portal. For example: | |||
>``` | |||
>./deploy.ps1 -registry myregistry.azurecr.io -dockerUser User -dockerPassword SecretPassword | |||
>``` | |||
The script will build the code and corresponding Docker images, push the latter to your registry, and deploy the application to your cluster. You can watch the deployment unfold from the Kubernetes web interface: run `kubectl proxy` and open a browser to [http://localhost:8001/ui](http://localhost:8001/ui) | |||
## Sending feedback and pull requests | |||
As mentioned, we'd appreciate to your feedback, improvements and ideas. | |||
You can create new issues at the issues section, do pull requests and/or send emails to **eshop_feedback@service.microsoft.com** | |||
## Questions | |||
[QUESTION] Answer +1 if the solution is working for you (Through VS2017 or CLI environment): | |||
https://github.com/dotnet/eShopOnContainers/issues/107 | |||
@ -0,0 +1,80 @@ | |||
Param( | |||
[parameter(Mandatory=$true)][string]$registry, | |||
[parameter(Mandatory=$true)][string]$dockerUser, | |||
[parameter(Mandatory=$true)][string]$dockerPassword | |||
) | |||
$requiredCommands = ("docker", "docker-compose", "kubectl") | |||
foreach ($command in $requiredCommands) { | |||
if ((Get-Command $command -ErrorAction SilentlyContinue) -eq $null) { | |||
Write-Host "$command must be on path" -ForegroundColor Red | |||
exit | |||
} | |||
} | |||
Write-Host "Logging in to $registry" -ForegroundColor Yellow | |||
docker login -u $dockerUser -p $dockerPassword $registry | |||
if (-not $LastExitCode -eq 0) { | |||
Write-Host "Login failed" -ForegroundColor Red | |||
exit | |||
} | |||
# create registry key secret | |||
kubectl create secret docker-registry registry-key ` | |||
--docker-server=$registry ` | |||
--docker-username=$dockerUser ` | |||
--docker-password=$dockerPassword ` | |||
--docker-email=not@used.com | |||
# start sql, rabbitmq, frontend deployments | |||
kubectl create configmap config-files --from-file=nginx-conf=nginx.conf | |||
kubectl label configmap config-files app=eshop | |||
kubectl create -f sql-data.yaml -f rabbitmq.yaml -f services.yaml -f frontend.yaml | |||
Write-Host "Building and publishing eShopOnContainers..." -ForegroundColor Yellow | |||
dotnet restore ../eShopOnContainers-ServicesAndWebApps.sln | |||
dotnet publish -c Release -o obj/Docker/publish ../eShopOnContainers-ServicesAndWebApps.sln | |||
Write-Host "Building Docker images..." -ForegroundColor Yellow | |||
docker-compose -p .. -f ../docker-compose.yml build | |||
Write-Host "Pushing images to $registry..." -ForegroundColor Yellow | |||
$services = ("basket.api", "catalog.api", "identity.api", "ordering.api", "webmvc", "webspa") | |||
foreach ($service in $services) { | |||
docker tag eshop/$service $registry/eshop/$service | |||
docker push $registry/eshop/$service | |||
} | |||
Write-Host "Waiting for frontend's external ip..." -ForegroundColor Yellow | |||
while ($true) { | |||
$frontendUrl = kubectl get svc frontend -o=jsonpath="{.status.loadBalancer.ingress[0].ip}" | |||
if ([bool]($frontendUrl -as [ipaddress])) { | |||
break | |||
} | |||
Start-Sleep -s 15 | |||
} | |||
kubectl create configmap urls ` | |||
--from-literal=BasketUrl=http://$($frontendUrl)/basket-api ` | |||
--from-literal=CatalogUrl=http://$($frontendUrl)/catalog-api ` | |||
--from-literal=IdentityUrl=http://$($frontendUrl)/identity ` | |||
--from-literal=OrderingUrl=http://$($frontendUrl)/ordering-api ` | |||
--from-literal=MvcClient=http://$($frontendUrl)/webmvc ` | |||
--from-literal=SpaClient=http://$($frontendUrl) | |||
kubectl label configmap urls app=eshop | |||
Write-Host "Creating deployments..." | |||
kubectl apply -f deployments.yaml | |||
# update deployments with the private registry before k8s tries to pull images | |||
# (deployment templating, or Helm, would obviate this) | |||
kubectl set image -f deployments.yaml ` | |||
basket=$registry/eshop/basket.api ` | |||
catalog=$registry/eshop/catalog.api ` | |||
identity=$registry/eshop/identity.api ` | |||
ordering=$registry/eshop/ordering.api ` | |||
webmvc=$registry/eshop/webmvc ` | |||
webspa=$registry/eshop/webspa | |||
kubectl rollout resume -f deployments.yaml | |||
Write-Host "WebSPA is exposed at http://$frontendUrl, WebMVC at http://$frontendUrl/webmvc" -ForegroundColor Yellow |
@ -0,0 +1,236 @@ | |||
apiVersion: extensions/v1beta1 | |||
kind: Deployment | |||
metadata: | |||
name: basket | |||
spec: | |||
paused: true | |||
template: | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: basket | |||
spec: | |||
containers: | |||
- name: basket | |||
image: eshop/basket.api | |||
imagePullPolicy: Always | |||
env: | |||
- name: ASPNETCORE_URLS | |||
value: http://0.0.0.0:80/basket-api | |||
- name: ConnectionString | |||
value: 127.0.0.1 | |||
- name: EventBusConnection | |||
value: rabbitmq | |||
- name: IdentityUrl | |||
valueFrom: | |||
configMapKeyRef: | |||
name: urls | |||
key: IdentityUrl | |||
ports: | |||
- containerPort: 80 | |||
- name: basket-data | |||
image: redis:3.2-alpine | |||
ports: | |||
- containerPort: 6379 | |||
imagePullSecrets: | |||
- name: registry-key | |||
--- | |||
apiVersion: extensions/v1beta1 | |||
kind: Deployment | |||
metadata: | |||
name: catalog | |||
spec: | |||
paused: true | |||
template: | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: catalog | |||
spec: | |||
containers: | |||
- name: catalog | |||
image: eshop/catalog.api | |||
imagePullPolicy: Always | |||
env: | |||
- name: ASPNETCORE_URLS | |||
value: http://0.0.0.0:80/catalog-api | |||
- name: ConnectionString | |||
value: "Server=sql-data;Initial Catalog=Microsoft.eShopOnContainers.Services.CatalogDb;User Id=sa;Password=Pass@word" | |||
- name: EventBusConnection | |||
value: rabbitmq | |||
- name: ExternalCatalogBaseUrl | |||
valueFrom: | |||
configMapKeyRef: | |||
name: urls | |||
key: CatalogUrl | |||
ports: | |||
- containerPort: 80 | |||
imagePullSecrets: | |||
- name: registry-key | |||
--- | |||
apiVersion: extensions/v1beta1 | |||
kind: Deployment | |||
metadata: | |||
name: identity | |||
spec: | |||
paused: true | |||
template: | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: identity | |||
spec: | |||
containers: | |||
- name: identity | |||
image: eshop/identity.api | |||
imagePullPolicy: Always | |||
env: | |||
- name: ASPNETCORE_URLS | |||
value: http://0.0.0.0:80/identity | |||
- name: ConnectionStrings__DefaultConnection | |||
value: "Server=sql-data;Initial Catalog=Microsoft.eShopOnContainers.Services.IdentityDb;User Id=sa;Password=Pass@word" | |||
- name: MvcClient | |||
valueFrom: | |||
configMapKeyRef: | |||
name: urls | |||
key: MvcClient | |||
- name: SpaClient | |||
valueFrom: | |||
configMapKeyRef: | |||
name: urls | |||
key: SpaClient | |||
ports: | |||
- containerPort: 80 | |||
imagePullSecrets: | |||
- name: registry-key | |||
--- | |||
apiVersion: extensions/v1beta1 | |||
kind: Deployment | |||
metadata: | |||
name: ordering | |||
spec: | |||
paused: true | |||
template: | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: ordering | |||
spec: | |||
containers: | |||
- name: ordering | |||
image: eshop/ordering.api | |||
imagePullPolicy: Always | |||
env: | |||
- name: ASPNETCORE_URLS | |||
value: http://0.0.0.0:80/ordering-api | |||
- name: ConnectionString | |||
value: "Server=sql-data;Database=Microsoft.eShopOnContainers.Services.OrderingDb;User Id=sa;Password=Pass@word;" | |||
- name: EventBusConnection | |||
value: rabbitmq | |||
- name: IdentityUrl | |||
valueFrom: | |||
configMapKeyRef: | |||
name: urls | |||
key: IdentityUrl | |||
ports: | |||
- containerPort: 80 | |||
imagePullSecrets: | |||
- name: registry-key | |||
--- | |||
apiVersion: extensions/v1beta1 | |||
kind: Deployment | |||
metadata: | |||
name: webmvc | |||
spec: | |||
paused: true | |||
template: | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: webmvc | |||
spec: | |||
containers: | |||
- name: webmvc | |||
image: eshop/webmvc | |||
imagePullPolicy: Always | |||
env: | |||
- name: ASPNETCORE_URLS | |||
value: http://0.0.0.0:80/webmvc | |||
- name: BasketUrl | |||
valueFrom: | |||
configMapKeyRef: | |||
name: urls | |||
key: BasketUrl | |||
- name: CallBackUrl | |||
valueFrom: | |||
configMapKeyRef: | |||
name: urls | |||
key: MvcClient | |||
- name: CatalogUrl | |||
valueFrom: | |||
configMapKeyRef: | |||
name: urls | |||
key: CatalogUrl | |||
- name: IdentityUrl | |||
valueFrom: | |||
configMapKeyRef: | |||
name: urls | |||
key: IdentityUrl | |||
- name: OrderingUrl | |||
valueFrom: | |||
configMapKeyRef: | |||
name: urls | |||
key: OrderingUrl | |||
ports: | |||
- containerPort: 80 | |||
imagePullSecrets: | |||
- name: registry-key | |||
--- | |||
apiVersion: extensions/v1beta1 | |||
kind: Deployment | |||
metadata: | |||
name: webspa | |||
spec: | |||
paused: true | |||
template: | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: webspa | |||
spec: | |||
containers: | |||
- name: webspa | |||
image: eshop/webspa | |||
imagePullPolicy: Always | |||
env: | |||
- name: ASPNETCORE_URLS | |||
value: http://0.0.0.0:80 | |||
- name: BasketUrl | |||
valueFrom: | |||
configMapKeyRef: | |||
name: urls | |||
key: BasketUrl | |||
- name: CallBackUrl | |||
valueFrom: | |||
configMapKeyRef: | |||
name: urls | |||
key: SpaClient | |||
- name: CatalogUrl | |||
valueFrom: | |||
configMapKeyRef: | |||
name: urls | |||
key: CatalogUrl | |||
- name: IdentityUrl | |||
valueFrom: | |||
configMapKeyRef: | |||
name: urls | |||
key: IdentityUrl | |||
- name: OrderingUrl | |||
valueFrom: | |||
configMapKeyRef: | |||
name: urls | |||
key: OrderingUrl | |||
ports: | |||
- containerPort: 80 | |||
imagePullSecrets: | |||
- name: registry-key |
@ -0,0 +1,47 @@ | |||
apiVersion: v1 | |||
kind: Service | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: frontend | |||
name: frontend | |||
spec: | |||
ports: | |||
- port: 80 | |||
targetPort: 8080 | |||
selector: | |||
app: eshop | |||
component: frontend | |||
type: LoadBalancer | |||
--- | |||
apiVersion: extensions/v1beta1 | |||
kind: Deployment | |||
metadata: | |||
name: frontend | |||
spec: | |||
template: | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: frontend | |||
spec: | |||
containers: | |||
- name: nginx | |||
image: nginx:1.11.10-alpine | |||
imagePullPolicy: IfNotPresent | |||
ports: | |||
- containerPort: 8080 | |||
lifecycle: | |||
preStop: | |||
exec: | |||
command: ["/usr/sbin/nginx","-s","quit"] | |||
volumeMounts: | |||
- name: config | |||
mountPath: /etc/nginx | |||
volumes: | |||
- name: config | |||
configMap: | |||
name: config-files | |||
items: | |||
- key: nginx-conf | |||
path: nginx.conf |
@ -0,0 +1,25 @@ | |||
Param( | |||
[parameter(Mandatory=$true)][string]$resourceGroupName, | |||
[parameter(Mandatory=$true)][string]$location, | |||
[parameter(Mandatory=$true)][string]$registryName, | |||
[parameter(Mandatory=$true)][string]$orchestratorName, | |||
[parameter(Mandatory=$true)][string]$dnsName | |||
) | |||
# Create resource group | |||
Write-Host "Creating resource group..." -ForegroundColor Yellow | |||
az group create --name=$resourceGroupName --location=$location | |||
# Create Azure Container Registry | |||
Write-Host "Creating Azure Container Registry..." -ForegroundColor Yellow | |||
az acr create -n $registryName -g $resourceGroupName -l $location --admin-enabled true --sku Basic | |||
# Create kubernetes orchestrator | |||
Write-Host "Creating kubernetes orchestrator..." -ForegroundColor Yellow | |||
az acs create --orchestrator-type=kubernetes --resource-group $resourceGroupName --name=$orchestratorName --dns-prefix=$dnsName --generate-ssh-keys | |||
# Retrieve kubernetes cluster configuration and save it under ~/.kube/config | |||
az acs kubernetes get-credentials --resource-group=$resourceGroupName --name=$orchestratorName | |||
# Show ACR credentials | |||
az acr credential show -n $registryName |
@ -0,0 +1,74 @@ | |||
pid /tmp/nginx.pid; | |||
worker_processes 1; | |||
events { | |||
worker_connections 1024; | |||
} | |||
http { | |||
server_tokens off; | |||
add_header X-Frame-Options SAMEORIGIN; | |||
add_header X-Content-Type-Options nosniff; | |||
add_header X-XSS-Protection "1; mode=block"; | |||
client_body_temp_path /tmp/client_body; | |||
fastcgi_temp_path /tmp/fastcgi_temp; | |||
proxy_temp_path /tmp/proxy_temp; | |||
scgi_temp_path /tmp/scgi_temp; | |||
uwsgi_temp_path /tmp/uwsgi_temp; | |||
gzip on; | |||
gzip_comp_level 6; | |||
gzip_min_length 1024; | |||
gzip_buffers 4 32k; | |||
gzip_types text/plain application/javascript text/css; | |||
gzip_vary on; | |||
keepalive_timeout 65; | |||
proxy_buffer_size 128k; | |||
proxy_buffers 4 256k; | |||
proxy_busy_buffers_size 256k; | |||
server { | |||
listen 8080; | |||
location /basket-api { | |||
proxy_pass http://basket; | |||
proxy_redirect off; | |||
proxy_set_header Host $host; | |||
} | |||
location /catalog-api { | |||
proxy_pass http://catalog; | |||
proxy_redirect off; | |||
proxy_set_header Host $host; | |||
} | |||
location /identity { | |||
proxy_pass http://identity; | |||
proxy_redirect off; | |||
proxy_set_header Host $host; | |||
} | |||
location /ordering-api { | |||
proxy_pass http://ordering; | |||
proxy_redirect off; | |||
proxy_set_header Host $host; | |||
} | |||
location /webmvc { | |||
proxy_pass http://webmvc; | |||
proxy_redirect off; | |||
proxy_set_header Host $host; | |||
} | |||
location / { | |||
proxy_pass http://webspa; | |||
proxy_redirect off; | |||
proxy_set_header Host $host; | |||
} | |||
} | |||
} |
@ -0,0 +1,30 @@ | |||
apiVersion: v1 | |||
kind: Service | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: rabbitmq | |||
name: rabbitmq | |||
spec: | |||
ports: | |||
- port: 5672 | |||
selector: | |||
app: eshop | |||
component: rabbitmq | |||
--- | |||
apiVersion: extensions/v1beta1 | |||
kind: Deployment | |||
metadata: | |||
name: rabbitmq | |||
spec: | |||
template: | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: rabbitmq | |||
spec: | |||
containers: | |||
- name: rabbitmq | |||
image: rabbitmq:3.6.9-alpine | |||
ports: | |||
- containerPort: 5672 |
@ -0,0 +1,83 @@ | |||
apiVersion: v1 | |||
kind: Service | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: basket | |||
name: basket | |||
spec: | |||
ports: | |||
- port: 80 | |||
selector: | |||
app: eshop | |||
component: basket | |||
--- | |||
apiVersion: v1 | |||
kind: Service | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: catalog | |||
name: catalog | |||
spec: | |||
ports: | |||
- port: 80 | |||
selector: | |||
app: eshop | |||
component: catalog | |||
--- | |||
apiVersion: v1 | |||
kind: Service | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: identity | |||
name: identity | |||
spec: | |||
ports: | |||
- port: 80 | |||
selector: | |||
app: eshop | |||
component: identity | |||
--- | |||
apiVersion: v1 | |||
kind: Service | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: ordering | |||
name: ordering | |||
spec: | |||
ports: | |||
- port: 80 | |||
selector: | |||
app: eshop | |||
component: ordering | |||
--- | |||
apiVersion: v1 | |||
kind: Service | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: webmvc | |||
name: webmvc | |||
spec: | |||
ports: | |||
- port: 80 | |||
selector: | |||
app: eshop | |||
component: webmvc | |||
--- | |||
apiVersion: v1 | |||
kind: Service | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: webspa | |||
name: webspa | |||
spec: | |||
ports: | |||
- port: 80 | |||
selector: | |||
app: eshop | |||
component: webspa |
@ -0,0 +1,33 @@ | |||
apiVersion: v1 | |||
kind: Service | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: sql-data | |||
name: sql-data | |||
spec: | |||
ports: | |||
- port: 1433 | |||
selector: | |||
app: eshop | |||
component: sql-data | |||
--- | |||
apiVersion: extensions/v1beta1 | |||
kind: Deployment | |||
metadata: | |||
name: sql-data | |||
spec: | |||
template: | |||
metadata: | |||
labels: | |||
app: eshop | |||
component: sql-data | |||
spec: | |||
containers: | |||
- name: sql-data | |||
image: microsoft/mssql-server-linux:ctp1-3 | |||
env: | |||
- name: ACCEPT_EULA | |||
value: "Y" | |||
- name: SA_PASSWORD | |||
value: Pass@word |
@ -0,0 +1,22 @@ | |||
<Project Sdk="Microsoft.NET.Sdk"> | |||
<PropertyGroup> | |||
<TargetFramework>netcoreapp1.1</TargetFramework> | |||
</PropertyGroup> | |||
<ItemGroup> | |||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" /> | |||
<PackageReference Include="xunit" Version="2.2.0" /> | |||
<PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" /> | |||
</ItemGroup> | |||
<ItemGroup> | |||
<ProjectReference Include="..\EventBusRabbitMQ\EventBusRabbitMQ.csproj" /> | |||
<ProjectReference Include="..\EventBus\EventBus.csproj" /> | |||
</ItemGroup> | |||
<ItemGroup> | |||
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> | |||
</ItemGroup> | |||
</Project> |
@ -0,0 +1,56 @@ | |||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus; | |||
using System; | |||
using System.Linq; | |||
using Xunit; | |||
namespace EventBus.Tests | |||
{ | |||
public class InMemory_SubscriptionManager_Tests | |||
{ | |||
[Fact] | |||
public void After_Creation_Should_Be_Empty() | |||
{ | |||
var manager = new InMemoryEventBusSubscriptionsManager(); | |||
Assert.True(manager.IsEmpty); | |||
} | |||
[Fact] | |||
public void After_One_Event_Subscription_Should_Contain_The_Event() | |||
{ | |||
var manager = new InMemoryEventBusSubscriptionsManager(); | |||
manager.AddSubscription<TestIntegrationEvent,TestIntegrationEventHandler>(() => new TestIntegrationEventHandler()); | |||
Assert.True(manager.HasSubscriptionsForEvent<TestIntegrationEvent>()); | |||
} | |||
[Fact] | |||
public void After_All_Subscriptions_Are_Deleted_Event_Should_No_Longer_Exists() | |||
{ | |||
var manager = new InMemoryEventBusSubscriptionsManager(); | |||
manager.AddSubscription<TestIntegrationEvent, TestIntegrationEventHandler>(() => new TestIntegrationEventHandler()); | |||
manager.RemoveSubscription<TestIntegrationEvent, TestIntegrationEventHandler>(); | |||
Assert.False(manager.HasSubscriptionsForEvent<TestIntegrationEvent>()); | |||
} | |||
[Fact] | |||
public void Deleting_Last_Subscription_Should_Raise_On_Deleted_Event() | |||
{ | |||
bool raised = false; | |||
var manager = new InMemoryEventBusSubscriptionsManager(); | |||
manager.OnEventRemoved += (o, e) => raised = true; | |||
manager.AddSubscription<TestIntegrationEvent, TestIntegrationEventHandler>(() => new TestIntegrationEventHandler()); | |||
manager.RemoveSubscription<TestIntegrationEvent, TestIntegrationEventHandler>(); | |||
Assert.True(raised); | |||
} | |||
[Fact] | |||
public void Get_Handlers_For_Event_Should_Return_All_Handlers() | |||
{ | |||
var manager = new InMemoryEventBusSubscriptionsManager(); | |||
manager.AddSubscription<TestIntegrationEvent, TestIntegrationEventHandler>(() => new TestIntegrationEventHandler()); | |||
manager.AddSubscription<TestIntegrationEvent, TestIntegrationOtherEventHandler>(() => new TestIntegrationOtherEventHandler()); | |||
var handlers = manager.GetHandlersForEvent<TestIntegrationEvent>(); | |||
Assert.Equal(2, handlers.Count()); | |||
} | |||
} | |||
} |
@ -0,0 +1,11 @@ | |||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events; | |||
using System; | |||
using System.Collections.Generic; | |||
using System.Text; | |||
namespace EventBus.Tests | |||
{ | |||
public class TestIntegrationEvent : IntegrationEvent | |||
{ | |||
} | |||
} |
@ -0,0 +1,23 @@ | |||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; | |||
using System; | |||
using System.Collections.Generic; | |||
using System.Text; | |||
using System.Threading.Tasks; | |||
namespace EventBus.Tests | |||
{ | |||
public class TestIntegrationOtherEventHandler : IIntegrationEventHandler<TestIntegrationEvent> | |||
{ | |||
public bool Handled { get; private set; } | |||
public TestIntegrationOtherEventHandler() | |||
{ | |||
Handled = false; | |||
} | |||
public async Task Handle(TestIntegrationEvent @event) | |||
{ | |||
Handled = true; | |||
} | |||
} | |||
} |
@ -0,0 +1,23 @@ | |||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; | |||
using System; | |||
using System.Collections.Generic; | |||
using System.Text; | |||
using System.Threading.Tasks; | |||
namespace EventBus.Tests | |||
{ | |||
public class TestIntegrationEventHandler : IIntegrationEventHandler<TestIntegrationEvent> | |||
{ | |||
public bool Handled { get; private set; } | |||
public TestIntegrationEventHandler() | |||
{ | |||
Handled = false; | |||
} | |||
public async Task Handle(TestIntegrationEvent @event) | |||
{ | |||
Handled = true; | |||
} | |||
} | |||
} |
@ -1,11 +1,17 @@ | |||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events; | |||
using System; | |||
namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions | |||
{ | |||
public interface IEventBus | |||
{ | |||
void Subscribe<T>(IIntegrationEventHandler<T> handler) where T: IntegrationEvent; | |||
void Unsubscribe<T>(IIntegrationEventHandler<T> handler) where T : IntegrationEvent; | |||
void Subscribe<T, TH>(Func<TH> handler) | |||
where T : IntegrationEvent | |||
where TH : IIntegrationEventHandler<T>; | |||
void Unsubscribe<T, TH>() | |||
where TH : IIntegrationEventHandler<T> | |||
where T : IntegrationEvent; | |||
void Publish(IntegrationEvent @event); | |||
} | |||
} |
@ -0,0 +1,26 @@ | |||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; | |||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events; | |||
using System; | |||
using System.Collections.Generic; | |||
namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBus | |||
{ | |||
public interface IEventBusSubscriptionsManager | |||
{ | |||
bool IsEmpty { get; } | |||
event EventHandler<string> OnEventRemoved; | |||
void AddSubscription<T, TH>(Func<TH> handler) | |||
where T : IntegrationEvent | |||
where TH : IIntegrationEventHandler<T>; | |||
void RemoveSubscription<T, TH>() | |||
where TH : IIntegrationEventHandler<T> | |||
where T : IntegrationEvent; | |||
bool HasSubscriptionsForEvent<T>() where T : IntegrationEvent; | |||
bool HasSubscriptionsForEvent(string eventName); | |||
Type GetEventTypeByName(string eventName); | |||
void Clear(); | |||
IEnumerable<Delegate> GetHandlersForEvent<T>() where T : IntegrationEvent; | |||
IEnumerable<Delegate> GetHandlersForEvent(string eventName); | |||
} | |||
} |
@ -0,0 +1,115 @@ | |||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; | |||
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events; | |||
using System; | |||
using System.Collections.Generic; | |||
using System.Linq; | |||
using System.Reflection; | |||
using System.Text; | |||
namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBus | |||
{ | |||
public class InMemoryEventBusSubscriptionsManager : IEventBusSubscriptionsManager | |||
{ | |||
private readonly Dictionary<string, List<Delegate>> _handlers; | |||
private readonly List<Type> _eventTypes; | |||
public event EventHandler<string> OnEventRemoved; | |||
public InMemoryEventBusSubscriptionsManager() | |||
{ | |||
_handlers = new Dictionary<string, List<Delegate>>(); | |||
_eventTypes = new List<Type>(); | |||
} | |||
public bool IsEmpty => !_handlers.Keys.Any(); | |||
public void Clear() => _handlers.Clear(); | |||
public void AddSubscription<T, TH>(Func<TH> handler) | |||
where T : IntegrationEvent | |||
where TH : IIntegrationEventHandler<T> | |||
{ | |||
var key = GetEventKey<T>(); | |||
if (!HasSubscriptionsForEvent<T>()) | |||
{ | |||
_handlers.Add(key, new List<Delegate>()); | |||
} | |||
_handlers[key].Add(handler); | |||
_eventTypes.Add(typeof(T)); | |||
} | |||
public void RemoveSubscription<T, TH>() | |||
where TH : IIntegrationEventHandler<T> | |||
where T : IntegrationEvent | |||
{ | |||
var handlerToRemove = FindHandlerToRemove<T, TH>(); | |||
if (handlerToRemove != null) | |||
{ | |||
var key = GetEventKey<T>(); | |||
_handlers[key].Remove(handlerToRemove); | |||
if (!_handlers[key].Any()) | |||
{ | |||
_handlers.Remove(key); | |||
var eventType = _eventTypes.SingleOrDefault(e => e.Name == key); | |||
if (eventType != null) | |||
{ | |||
_eventTypes.Remove(eventType); | |||
RaiseOnEventRemoved(eventType.Name); | |||
} | |||
} | |||
} | |||
} | |||
public IEnumerable<Delegate> GetHandlersForEvent<T>() where T : IntegrationEvent | |||
{ | |||
var key = GetEventKey<T>(); | |||
return GetHandlersForEvent(key); | |||
} | |||
public IEnumerable<Delegate> GetHandlersForEvent(string eventName) => _handlers[eventName]; | |||
private void RaiseOnEventRemoved(string eventName) | |||
{ | |||
var handler = OnEventRemoved; | |||
if (handler != null) | |||
{ | |||
OnEventRemoved(this, eventName); | |||
} | |||
} | |||
private Delegate FindHandlerToRemove<T, TH>() | |||
where T : IntegrationEvent | |||
where TH : IIntegrationEventHandler<T> | |||
{ | |||
if (!HasSubscriptionsForEvent<T>()) | |||
{ | |||
return null; | |||
} | |||
var key = GetEventKey<T>(); | |||
foreach (var func in _handlers[key]) | |||
{ | |||
var genericArgs = func.GetType().GetGenericArguments(); | |||
if (genericArgs.SingleOrDefault() == typeof(TH)) | |||
{ | |||
return func; | |||
} | |||
} | |||
return null; | |||
} | |||
public bool HasSubscriptionsForEvent<T>() where T : IntegrationEvent | |||
{ | |||
var key = GetEventKey<T>(); | |||
return HasSubscriptionsForEvent(key); | |||
} | |||
public bool HasSubscriptionsForEvent(string eventName) => _handlers.ContainsKey(eventName); | |||
public Type GetEventTypeByName(string eventName) => _eventTypes.Single(t => t.Name == eventName); | |||
private string GetEventKey<T>() | |||
{ | |||
return typeof(T).Name; | |||
} | |||
} | |||
} |
@ -0,0 +1,109 @@ | |||
// Copyright (c) .NET Foundation. All rights reserved. | |||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | |||
using System; | |||
using System.Reflection; | |||
using System.Threading; | |||
using System.Threading.Tasks; | |||
using Microsoft.Extensions.DependencyInjection; | |||
namespace Microsoft.Extensions.HealthChecks | |||
{ | |||
public abstract class CachedHealthCheck | |||
{ | |||
private static readonly TypeInfo HealthCheckTypeInfo = typeof(IHealthCheck).GetTypeInfo(); | |||
private volatile int _writerCount; | |||
public CachedHealthCheck(string name, TimeSpan cacheDuration) | |||
{ | |||
Guard.ArgumentNotNullOrEmpty(nameof(name), name); | |||
Guard.ArgumentValid(cacheDuration.TotalMilliseconds >= 0, nameof(cacheDuration), "Cache duration must be zero (disabled) or greater than zero."); | |||
Name = name; | |||
CacheDuration = cacheDuration; | |||
} | |||
public IHealthCheckResult CachedResult { get; internal set; } | |||
public TimeSpan CacheDuration { get; } | |||
public DateTimeOffset CacheExpiration { get; internal set; } | |||
public string Name { get; } | |||
protected virtual DateTimeOffset UtcNow => DateTimeOffset.UtcNow; | |||
protected abstract IHealthCheck Resolve(IServiceProvider serviceProvider); | |||
public async ValueTask<IHealthCheckResult> RunAsync(IServiceProvider serviceProvider, CancellationToken cancellationToken = default(CancellationToken)) | |||
{ | |||
while (CacheExpiration <= UtcNow) | |||
{ | |||
// Can't use a standard lock here because of async, so we'll use this flag to determine when we should write a value, | |||
// and the waiters who aren't allowed to write will just spin wait for the new value. | |||
if (Interlocked.Exchange(ref _writerCount, 1) != 0) | |||
{ | |||
await Task.Delay(5, cancellationToken).ConfigureAwait(false); | |||
continue; | |||
} | |||
try | |||
{ | |||
var check = Resolve(serviceProvider); | |||
CachedResult = await check.CheckAsync(cancellationToken); | |||
} | |||
catch (OperationCanceledException) | |||
{ | |||
CachedResult = HealthCheckResult.Unhealthy("The health check operation timed out"); | |||
} | |||
catch (Exception ex) | |||
{ | |||
CachedResult = HealthCheckResult.Unhealthy($"Exception during check: {ex.GetType().FullName}"); | |||
} | |||
CacheExpiration = UtcNow + CacheDuration; | |||
_writerCount = 0; | |||
break; | |||
} | |||
return CachedResult; | |||
} | |||
public static CachedHealthCheck FromHealthCheck(string name, TimeSpan cacheDuration, IHealthCheck healthCheck) | |||
{ | |||
Guard.ArgumentNotNull(nameof(healthCheck), healthCheck); | |||
return new TypeOrHealthCheck_HealthCheck(name, cacheDuration, healthCheck); | |||
} | |||
public static CachedHealthCheck FromType(string name, TimeSpan cacheDuration, Type healthCheckType) | |||
{ | |||
Guard.ArgumentNotNull(nameof(healthCheckType), healthCheckType); | |||
Guard.ArgumentValid(HealthCheckTypeInfo.IsAssignableFrom(healthCheckType.GetTypeInfo()), nameof(healthCheckType), $"Health check must implement '{typeof(IHealthCheck).FullName}'."); | |||
return new TypeOrHealthCheck_Type(name, cacheDuration, healthCheckType); | |||
} | |||
class TypeOrHealthCheck_HealthCheck : CachedHealthCheck | |||
{ | |||
private readonly IHealthCheck _healthCheck; | |||
public TypeOrHealthCheck_HealthCheck(string name, TimeSpan cacheDuration, IHealthCheck healthCheck) : base(name, cacheDuration) | |||
=> _healthCheck = healthCheck; | |||
protected override IHealthCheck Resolve(IServiceProvider serviceProvider) => _healthCheck; | |||
} | |||
class TypeOrHealthCheck_Type : CachedHealthCheck | |||
{ | |||
private readonly Type _healthCheckType; | |||
public TypeOrHealthCheck_Type(string name, TimeSpan cacheDuration, Type healthCheckType) : base(name, cacheDuration) | |||
=> _healthCheckType = healthCheckType; | |||
protected override IHealthCheck Resolve(IServiceProvider serviceProvider) | |||
=> (IHealthCheck)serviceProvider.GetRequiredService(_healthCheckType); | |||
} | |||
} | |||
} |
@ -0,0 +1,19 @@ | |||
// Copyright (c) .NET Foundation. All rights reserved. | |||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | |||
using System; | |||
using System.Threading; | |||
using System.Threading.Tasks; | |||
namespace Microsoft.Extensions.HealthChecks | |||
{ | |||
public static class CachedHealthCheckExtensions | |||
{ | |||
public static ValueTask<IHealthCheckResult> RunAsync(this CachedHealthCheck check, IServiceProvider serviceProvider) | |||
{ | |||
Guard.ArgumentNotNull(nameof(check), check); | |||
return check.RunAsync(serviceProvider, CancellationToken.None); | |||
} | |||
} | |||
} |
@ -1,18 +0,0 @@ | |||
// Copyright (c) .NET Foundation. All rights reserved. | |||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | |||
using System.Threading; | |||
using System.Threading.Tasks; | |||
namespace Microsoft.Extensions.HealthChecks | |||
{ | |||
public static class HealthCheckExtensions | |||
{ | |||
public static ValueTask<IHealthCheckResult> CheckAsync(this IHealthCheck healthCheck) | |||
{ | |||
Guard.ArgumentNotNull(nameof(healthCheck), healthCheck); | |||
return healthCheck.CheckAsync(CancellationToken.None); | |||
} | |||
} | |||
} |
@ -0,0 +1,37 @@ | |||
// Copyright (c) .NET Foundation. All rights reserved. | |||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | |||
using System.Collections.Generic; | |||
namespace Microsoft.Extensions.HealthChecks | |||
{ | |||
public class HealthCheckGroup | |||
{ | |||
private CheckStatus _partialSuccessStatus; | |||
public HealthCheckGroup(string groupName, CheckStatus partialSuccessStatus) | |||
{ | |||
Guard.ArgumentNotNull(nameof(groupName), groupName); | |||
GroupName = groupName; | |||
PartiallyHealthyStatus = partialSuccessStatus; | |||
} | |||
public IReadOnlyList<CachedHealthCheck> Checks => ChecksInternal.AsReadOnly(); | |||
internal List<CachedHealthCheck> ChecksInternal { get; } = new List<CachedHealthCheck>(); | |||
public string GroupName { get; } | |||
public CheckStatus PartiallyHealthyStatus | |||
{ | |||
get => _partialSuccessStatus; | |||
internal set | |||
{ | |||
Guard.ArgumentValid(value != CheckStatus.Unknown, nameof(value), "Check status 'Unknown' is not valid for partial success."); | |||
_partialSuccessStatus = value; | |||
} | |||
} | |||
} | |||
} |
@ -1,38 +0,0 @@ | |||
// Copyright (c) .NET Foundation. All rights reserved. | |||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | |||
using System.Threading; | |||
using System.Threading.Tasks; | |||
namespace Microsoft.Extensions.HealthChecks | |||
{ | |||
public static class HealthCheckServiceExtensions | |||
{ | |||
public static Task<CompositeHealthCheckResult> CheckHealthAsync(this IHealthCheckService service) | |||
{ | |||
Guard.ArgumentNotNull(nameof(service), service); | |||
return service.CheckHealthAsync(CheckStatus.Unhealthy, CancellationToken.None); | |||
} | |||
public static Task<CompositeHealthCheckResult> CheckHealthAsync(this IHealthCheckService service, CheckStatus partiallyHealthyStatus) | |||
{ | |||
Guard.ArgumentNotNull(nameof(service), service); | |||
return service.CheckHealthAsync(partiallyHealthyStatus, CancellationToken.None); | |||
} | |||
public static Task<CompositeHealthCheckResult> CheckHealthAsync(this IHealthCheckService service, CancellationToken cancellationToken) | |||
{ | |||
Guard.ArgumentNotNull(nameof(service), service); | |||
return service.CheckHealthAsync(CheckStatus.Unhealthy, cancellationToken); | |||
} | |||
public static Task<CompositeHealthCheckResult> CheckHealthAsync(this IHealthCheckService service, CheckStatus partiallyHealthyStatus, CancellationToken cancellationToken) | |||
{ | |||
Guard.ArgumentNotNull(nameof(service), service); | |||
return service.CheckHealthAsync(partiallyHealthyStatus, cancellationToken); | |||
} | |||
} | |||
} |
@ -0,0 +1,120 @@ | |||
using Xunit; | |||
using Xamarin.Forms; | |||
using System; | |||
using System.Globalization; | |||
namespace eShopOnContainers.UnitTests | |||
{ | |||
public class EventToCommandBehaviorTests | |||
{ | |||
[Fact] | |||
public void InvalidEventNameShouldThrowArgumentExceptionText() | |||
{ | |||
var behavior = new MockEventToCommandBehavior | |||
{ | |||
EventName = "OnItemTapped" | |||
}; | |||
var listView = new ListView(); | |||
Assert.Throws<ArgumentException>(() => listView.Behaviors.Add(behavior)); | |||
} | |||
[Fact] | |||
public void CommandExecutedWhenEventFiresText() | |||
{ | |||
bool executedCommand = false; | |||
var behavior = new MockEventToCommandBehavior | |||
{ | |||
EventName = "ItemTapped", | |||
Command = new Command(() => | |||
{ | |||
executedCommand = true; | |||
}) | |||
}; | |||
var listView = new ListView(); | |||
listView.Behaviors.Add(behavior); | |||
behavior.RaiseEvent(listView, null); | |||
Assert.True(executedCommand); | |||
} | |||
[Fact] | |||
public void CommandCanExecuteTest() | |||
{ | |||
var behavior = new MockEventToCommandBehavior | |||
{ | |||
EventName = "ItemTapped", | |||
Command = new Command(() => Assert.True(false), () => false) | |||
}; | |||
var listView = new ListView(); | |||
listView.Behaviors.Add(behavior); | |||
behavior.RaiseEvent(listView, null); | |||
} | |||
[Fact] | |||
public void CommandCanExecuteWithParameterShouldNotExecuteTest() | |||
{ | |||
bool shouldExecute = false; | |||
var behavior = new MockEventToCommandBehavior | |||
{ | |||
EventName = "ItemTapped", | |||
CommandParameter = shouldExecute, | |||
Command = new Command<string>(o => Assert.True(false), o => o.Equals(true)) | |||
}; | |||
var listView = new ListView(); | |||
listView.Behaviors.Add(behavior); | |||
behavior.RaiseEvent(listView, null); | |||
} | |||
[Fact] | |||
public void CommandWithConverterTest() | |||
{ | |||
const string item = "ItemProperty"; | |||
bool executedCommand = false; | |||
var behavior = new MockEventToCommandBehavior | |||
{ | |||
EventName = "ItemTapped", | |||
EventArgsConverter = new ItemTappedEventArgsConverter(false), | |||
Command = new Command<string>(o => | |||
{ | |||
executedCommand = true; | |||
Assert.NotNull(o); | |||
Assert.Equal(item, o); | |||
}) | |||
}; | |||
var listView = new ListView(); | |||
listView.Behaviors.Add(behavior); | |||
behavior.RaiseEvent(listView, new ItemTappedEventArgs(listView, item)); | |||
Assert.True(executedCommand); | |||
} | |||
private class ItemTappedEventArgsConverter : IValueConverter | |||
{ | |||
private readonly bool _returnParameter; | |||
public bool HasConverted { get; private set; } | |||
public ItemTappedEventArgsConverter(bool returnParameter) | |||
{ | |||
_returnParameter = returnParameter; | |||
} | |||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) | |||
{ | |||
HasConverted = true; | |||
return _returnParameter ? parameter : (value as ItemTappedEventArgs)?.Item; | |||
} | |||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) | |||
{ | |||
throw new NotImplementedException(); | |||
} | |||
} | |||
} | |||
} |
@ -1,27 +0,0 @@ | |||
using System; | |||
using System.Threading.Tasks; | |||
using Xunit; | |||
namespace eShopOnContainers.UnitTests | |||
{ | |||
public class DummyTests | |||
{ | |||
[Fact] | |||
public void ThisShouldPass_Sync() | |||
{ | |||
Assert.True(true); | |||
} | |||
[Fact] | |||
public async Task ThisShouldPass_Async() | |||
{ | |||
await Task.Run(() => { Assert.True(true); }); | |||
} | |||
[Fact] | |||
public async Task ThisShouldFail_Async() | |||
{ | |||
await Task.Run(() => { throw new Exception("Oops!"); }); | |||
} | |||
} | |||
} |
@ -0,0 +1,12 @@ | |||
using eShopOnContainers.Core.Behaviors; | |||
namespace eShopOnContainers.UnitTests | |||
{ | |||
public class MockEventToCommandBehavior : EventToCommandBehavior | |||
{ | |||
public void RaiseEvent(params object[] args) | |||
{ | |||
_handler.DynamicInvoke(args); | |||
} | |||
} | |||
} |
@ -0,0 +1,53 @@ | |||
using eShopOnContainers.Core.ViewModels.Base; | |||
using eShopOnContainers.Core.Validations; | |||
namespace eShopOnContainers.UnitTests | |||
{ | |||
public class MockViewModel : ViewModelBase | |||
{ | |||
private ValidatableObject<string> _forename; | |||
private ValidatableObject<string> _surname; | |||
public ValidatableObject<string> Forename | |||
{ | |||
get | |||
{ | |||
return _forename; | |||
} | |||
set | |||
{ | |||
_forename = value; | |||
RaisePropertyChanged(() => Forename); | |||
} | |||
} | |||
public ValidatableObject<string> Surname | |||
{ | |||
get | |||
{ | |||
return _surname; | |||
} | |||
set | |||
{ | |||
_surname = value; | |||
RaisePropertyChanged(() => Surname); | |||
} | |||
} | |||
public MockViewModel() | |||
{ | |||
_forename = new ValidatableObject<string>(); | |||
_surname = new ValidatableObject<string>(); | |||
_forename.Validations.Add(new IsNotNullOrEmptyRule<string> { ValidationMessage = "Forename is required." }); | |||
_surname.Validations.Add(new IsNotNullOrEmptyRule<string> { ValidationMessage = "Surname name is required." }); | |||
} | |||
public bool Validate() | |||
{ | |||
bool isValidForename = _forename.Validate(); | |||
bool isValidSurname = _surname.Validate(); | |||
return isValidForename && isValidSurname; | |||
} | |||
} | |||
} |
@ -0,0 +1,223 @@ | |||
using Xunit; | |||
using eShopOnContainers.Core.ViewModels; | |||
using eShopOnContainers.Core.ViewModels.Base; | |||
using eShopOnContainers.Core.Services.Catalog; | |||
using eShopOnContainers.Core.Models.Catalog; | |||
using System.Threading.Tasks; | |||
using System.Linq; | |||
namespace eShopOnContainers.UnitTests | |||
{ | |||
public class CatalogViewModelTests | |||
{ | |||
public CatalogViewModelTests() | |||
{ | |||
ViewModelLocator.RegisterDependencies(true); | |||
} | |||
[Fact] | |||
public void AddCatalogItemCommandIsNotNullTest() | |||
{ | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
Assert.NotNull(catalogViewModel.AddCatalogItemCommand); | |||
} | |||
[Fact] | |||
public void FilterCommandIsNotNullTest() | |||
{ | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
Assert.NotNull(catalogViewModel.FilterCommand); | |||
} | |||
[Fact] | |||
public void ClearFilterCommandIsNotNullTest() | |||
{ | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
Assert.NotNull(catalogViewModel.ClearFilterCommand); | |||
} | |||
[Fact] | |||
public void ProductsPropertyIsNullWhenViewModelInstantiatedTest() | |||
{ | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
Assert.Null(catalogViewModel.Products); | |||
} | |||
[Fact] | |||
public void BrandsPropertyuIsNullWhenViewModelInstantiatedTest() | |||
{ | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
Assert.Null(catalogViewModel.Brands); | |||
} | |||
[Fact] | |||
public void BrandPropertyIsNullWhenViewModelInstantiatedTest() | |||
{ | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
Assert.Null(catalogViewModel.Brand); | |||
} | |||
[Fact] | |||
public void TypesPropertyIsNullWhenViewModelInstantiatedTest() | |||
{ | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
Assert.Null(catalogViewModel.Types); | |||
} | |||
[Fact] | |||
public void TypePropertyIsNullWhenViewModelInstantiatedTest() | |||
{ | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
Assert.Null(catalogViewModel.Type); | |||
} | |||
[Fact] | |||
public void IsFilterPropertyIsFalseWhenViewModelInstantiatedTest() | |||
{ | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
Assert.False(catalogViewModel.IsFilter); | |||
} | |||
[Fact] | |||
public async Task ProductsPropertyIsNotNullAfterViewModelInitializationTest() | |||
{ | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
await catalogViewModel.InitializeAsync(null); | |||
Assert.NotNull(catalogViewModel.Products); | |||
} | |||
[Fact] | |||
public async Task BrandsPropertyIsNotNullAfterViewModelInitializationTest() | |||
{ | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
await catalogViewModel.InitializeAsync(null); | |||
Assert.NotNull(catalogViewModel.Brands); | |||
} | |||
[Fact] | |||
public async Task TypesPropertyIsNotNullAfterViewModelInitializationTest() | |||
{ | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
await catalogViewModel.InitializeAsync(null); | |||
Assert.NotNull(catalogViewModel.Types); | |||
} | |||
[Fact] | |||
public async Task SettingProductsPropertyShouldRaisePropertyChanged() | |||
{ | |||
bool invoked = false; | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
catalogViewModel.PropertyChanged += (sender, e) => | |||
{ | |||
if (e.PropertyName.Equals("Products")) | |||
invoked = true; | |||
}; | |||
await catalogViewModel.InitializeAsync(null); | |||
Assert.True(invoked); | |||
} | |||
[Fact] | |||
public async Task SettingBrandsPropertyShouldRaisePropertyChanged() | |||
{ | |||
bool invoked = false; | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
catalogViewModel.PropertyChanged += (sender, e) => | |||
{ | |||
if (e.PropertyName.Equals("Brands")) | |||
invoked = true; | |||
}; | |||
await catalogViewModel.InitializeAsync(null); | |||
Assert.True(invoked); | |||
} | |||
[Fact] | |||
public async Task SettingTypesPropertyShouldRaisePropertyChanged() | |||
{ | |||
bool invoked = false; | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
catalogViewModel.PropertyChanged += (sender, e) => | |||
{ | |||
if (e.PropertyName.Equals("Types")) | |||
invoked = true; | |||
}; | |||
await catalogViewModel.InitializeAsync(null); | |||
Assert.True(invoked); | |||
} | |||
[Fact] | |||
public void AddCatalogItemCommandSendsAddProductMessageTest() | |||
{ | |||
bool messageReceived = false; | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
Xamarin.Forms.MessagingCenter.Subscribe<CatalogViewModel, CatalogItem>(this, MessageKeys.AddProduct, (sender, arg) => | |||
{ | |||
messageReceived = true; | |||
}); | |||
catalogViewModel.AddCatalogItemCommand.Execute(null); | |||
Assert.True(messageReceived); | |||
} | |||
[Fact] | |||
public async Task FilterCommandSendsFilterMessageTest() | |||
{ | |||
bool messageReceived = false; | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
await catalogViewModel.InitializeAsync(null); | |||
catalogViewModel.Brand = catalogViewModel.Brands.FirstOrDefault(); | |||
catalogViewModel.Type = catalogViewModel.Types.FirstOrDefault(); | |||
Xamarin.Forms.MessagingCenter.Subscribe<CatalogViewModel>(this, MessageKeys.Filter, (sender) => | |||
{ | |||
messageReceived = true; | |||
}); | |||
catalogViewModel.FilterCommand.Execute(null); | |||
Assert.True(messageReceived); | |||
} | |||
[Fact] | |||
public async Task ClearFilterCommandResetsPropertiesTest() | |||
{ | |||
var catalogService = new CatalogMockService(); | |||
var catalogViewModel = new CatalogViewModel(catalogService); | |||
await catalogViewModel.InitializeAsync(null); | |||
catalogViewModel.ClearFilterCommand.Execute(null); | |||
Assert.Null(catalogViewModel.Brand); | |||
Assert.Null(catalogViewModel.Type); | |||
Assert.NotNull(catalogViewModel.Products); | |||
} | |||
} | |||
} |
@ -0,0 +1,54 @@ | |||
using Xunit; | |||
using eShopOnContainers.Core.ViewModels; | |||
using eShopOnContainers.Core.ViewModels.Base; | |||
using eShopOnContainers.Core.Models.Navigation; | |||
using System.Threading.Tasks; | |||
namespace eShopOnContainers.UnitTests | |||
{ | |||
public class MainViewModelTests | |||
{ | |||
public MainViewModelTests() | |||
{ | |||
ViewModelLocator.RegisterDependencies(true); | |||
} | |||
[Fact] | |||
public void SettingsCommandIsNotNullWhenViewModelInstantiatedTest() | |||
{ | |||
var mainViewModel = new MainViewModel(); | |||
Assert.NotNull(mainViewModel.SettingsCommand); | |||
} | |||
[Fact] | |||
public async Task ViewModelInitializationSendsChangeTabMessageTest() | |||
{ | |||
bool messageReceived = false; | |||
var mainViewModel = new MainViewModel(); | |||
var tabParam = new TabParameter { TabIndex = 2 }; | |||
Xamarin.Forms.MessagingCenter.Subscribe<MainViewModel, int>(this, MessageKeys.ChangeTab, (sender, arg) => | |||
{ | |||
messageReceived = true; | |||
}); | |||
await mainViewModel.InitializeAsync(tabParam); | |||
Assert.True(messageReceived); | |||
} | |||
[Fact] | |||
public void IsBusyPropertyIsFalseWhenViewModelInstantiatedTest() | |||
{ | |||
var mainViewModel = new MainViewModel(); | |||
Assert.False(mainViewModel.IsBusy); | |||
} | |||
[Fact] | |||
public async Task IsBusyPropertyIsTrueAfterViewModelInitializationTest() | |||
{ | |||
var mainViewModel = new MainViewModel(); | |||
await mainViewModel.InitializeAsync(null); | |||
Assert.True(mainViewModel.IsBusy); | |||
} | |||
} | |||
} |
@ -0,0 +1,113 @@ | |||
using Xunit; | |||
using eShopOnContainers.Core.ViewModels.Base; | |||
namespace eShopOnContainers.UnitTests | |||
{ | |||
public class MockViewModelTests | |||
{ | |||
public MockViewModelTests() | |||
{ | |||
ViewModelLocator.RegisterDependencies(true); | |||
} | |||
[Fact] | |||
public void CheckValidationFailsWhenPropertiesAreEmptyTest() | |||
{ | |||
var mockViewModel = new MockViewModel(); | |||
bool isValid = mockViewModel.Validate(); | |||
Assert.False(isValid); | |||
Assert.Null(mockViewModel.Forename.Value); | |||
Assert.Null(mockViewModel.Surname.Value); | |||
Assert.False(mockViewModel.Forename.IsValid); | |||
Assert.False(mockViewModel.Surname.IsValid); | |||
Assert.NotEmpty(mockViewModel.Forename.Errors); | |||
Assert.NotEmpty(mockViewModel.Surname.Errors); | |||
} | |||
[Fact] | |||
public void CheckValidationFailsWhenOnlyForenameHasDataTest() | |||
{ | |||
var mockViewModel = new MockViewModel(); | |||
mockViewModel.Forename.Value = "John"; | |||
bool isValid = mockViewModel.Validate(); | |||
Assert.False(isValid); | |||
Assert.NotNull(mockViewModel.Forename.Value); | |||
Assert.Null(mockViewModel.Surname.Value); | |||
Assert.True(mockViewModel.Forename.IsValid); | |||
Assert.False(mockViewModel.Surname.IsValid); | |||
Assert.Empty(mockViewModel.Forename.Errors); | |||
Assert.NotEmpty(mockViewModel.Surname.Errors); | |||
} | |||
[Fact] | |||
public void CheckValidationPassesWhenOnlySurnameHasDataTest() | |||
{ | |||
var mockViewModel = new MockViewModel(); | |||
mockViewModel.Surname.Value = "Smith"; | |||
bool isValid = mockViewModel.Validate(); | |||
Assert.False(isValid); | |||
Assert.Null(mockViewModel.Forename.Value); | |||
Assert.NotNull(mockViewModel.Surname.Value); | |||
Assert.False(mockViewModel.Forename.IsValid); | |||
Assert.True(mockViewModel.Surname.IsValid); | |||
Assert.NotEmpty(mockViewModel.Forename.Errors); | |||
Assert.Empty(mockViewModel.Surname.Errors); | |||
} | |||
[Fact] | |||
public void CheckValidationPassesWhenBothPropertiesHaveDataTest() | |||
{ | |||
var mockViewModel = new MockViewModel(); | |||
mockViewModel.Forename.Value = "John"; | |||
mockViewModel.Surname.Value = "Smith"; | |||
bool isValid = mockViewModel.Validate(); | |||
Assert.True(isValid); | |||
Assert.NotNull(mockViewModel.Forename.Value); | |||
Assert.NotNull(mockViewModel.Surname.Value); | |||
Assert.True(mockViewModel.Forename.IsValid); | |||
Assert.True(mockViewModel.Surname.IsValid); | |||
Assert.Empty(mockViewModel.Forename.Errors); | |||
Assert.Empty(mockViewModel.Surname.Errors); | |||
} | |||
[Fact] | |||
public void SettingForenamePropertyShouldRaisePropertyChanged() | |||
{ | |||
bool invoked = false; | |||
var mockViewModel = new MockViewModel(); | |||
mockViewModel.Forename.PropertyChanged += (sender, e) => | |||
{ | |||
if (e.PropertyName.Equals("Value")) | |||
invoked = true; | |||
}; | |||
mockViewModel.Forename.Value = "John"; | |||
Assert.True(invoked); | |||
} | |||
[Fact] | |||
public void SettingSurnamePropertyShouldRaisePropertyChanged() | |||
{ | |||
bool invoked = false; | |||
var mockViewModel = new MockViewModel(); | |||
mockViewModel.Surname.PropertyChanged += (sender, e) => | |||
{ | |||
if (e.PropertyName.Equals("Value")) | |||
invoked = true; | |||
}; | |||
mockViewModel.Surname.Value = "Smith"; | |||
Assert.True(invoked); | |||
} | |||
} | |||
} |
@ -0,0 +1,55 @@ | |||
using Xunit; | |||
using eShopOnContainers.Core; | |||
using eShopOnContainers.Core.ViewModels; | |||
using eShopOnContainers.Core.ViewModels.Base; | |||
using eShopOnContainers.Core.Services.Order; | |||
using System.Threading.Tasks; | |||
namespace eShopOnContainers.UnitTests | |||
{ | |||
public class OrderViewModelTests | |||
{ | |||
public OrderViewModelTests() | |||
{ | |||
ViewModelLocator.RegisterDependencies(true); | |||
} | |||
[Fact] | |||
public void OrderPropertyIsNullWhenViewModelInstantiatedTest() | |||
{ | |||
var orderService = new OrderMockService(); | |||
var orderViewModel = new OrderDetailViewModel(orderService); | |||
Assert.Null(orderViewModel.Order); | |||
} | |||
[Fact] | |||
public async Task OrderPropertyIsNotNullAfterViewModelInitializationTest() | |||
{ | |||
var orderService = new OrderMockService(); | |||
var orderViewModel = new OrderDetailViewModel(orderService); | |||
var order = await orderService.GetOrderAsync(1, GlobalSetting.Instance.AuthToken); | |||
await orderViewModel.InitializeAsync(order); | |||
Assert.NotNull(orderViewModel.Order); | |||
} | |||
[Fact] | |||
public async Task SettingOrderPropertyShouldRaisePropertyChanged() | |||
{ | |||
bool invoked = false; | |||
var orderService = new OrderMockService(); | |||
var orderViewModel = new OrderDetailViewModel(orderService); | |||
orderViewModel.PropertyChanged += (sender, e) => | |||
{ | |||
if (e.PropertyName.Equals("Order")) | |||
invoked = true; | |||
}; | |||
var order = await orderService.GetOrderAsync(1, GlobalSetting.Instance.AuthToken); | |||
await orderViewModel.InitializeAsync(order); | |||
Assert.True(invoked); | |||
} | |||
} | |||
} |
@ -1,10 +1,11 @@ | |||
<?xml version="1.0" encoding="utf-8"?> | |||
<packages> | |||
<package id="xunit" version="2.2.0-beta4-build3444" targetFramework="portable46-net451+win81" /> | |||
<package id="xunit.abstractions" version="2.0.1" targetFramework="portable46-net451+win81" /> | |||
<package id="xunit.assert" version="2.2.0-beta4-build3444" targetFramework="portable46-net451+win81" /> | |||
<package id="xunit.core" version="2.2.0-beta4-build3444" targetFramework="portable46-net451+win81" /> | |||
<package id="xunit.extensibility.core" version="2.2.0-beta4-build3444" targetFramework="portable46-net451+win81" /> | |||
<package id="xunit.extensibility.execution" version="2.2.0-beta4-build3444" targetFramework="portable46-net451+win81" /> | |||
<package id="xunit.runner.console" version="2.2.0-beta4-build3444" targetFramework="portable46-net451+win81" developmentDependency="true" /> | |||
<package id="Xamarin.Forms" version="2.3.4.231" targetFramework="portable46-net451+win81" /> | |||
<package id="xunit" version="2.2.0-beta4-build3444" targetFramework="portable-net451+win81" /> | |||
<package id="xunit.abstractions" version="2.0.1" targetFramework="portable-net451+win81" requireReinstallation="True" /> | |||
<package id="xunit.assert" version="2.2.0-beta4-build3444" targetFramework="portable-net451+win81" requireReinstallation="True" /> | |||
<package id="xunit.core" version="2.2.0-beta4-build3444" targetFramework="portable-net451+win81" requireReinstallation="True" /> | |||
<package id="xunit.extensibility.core" version="2.2.0-beta4-build3444" targetFramework="portable-net451+win81" requireReinstallation="True" /> | |||
<package id="xunit.extensibility.execution" version="2.2.0-beta4-build3444" targetFramework="portable-net451+win81" requireReinstallation="True" /> | |||
<package id="xunit.runner.console" version="2.2.0-beta4-build3444" targetFramework="portable-net451+win81" developmentDependency="true" /> | |||
</packages> |
@ -0,0 +1,58 @@ | |||
{ | |||
"$schema": "./node_modules/@angular/cli/lib/config/schema.json", | |||
"project": { | |||
"name": "WebSPA" | |||
}, | |||
"apps": [ | |||
{ | |||
"root": "Client", | |||
"outDir": "wwwroot", | |||
"assets": [ | |||
"assets", | |||
"favicon.ico" | |||
], | |||
"index": "index.html", | |||
"main": "main.ts", | |||
"polyfills": "polyfills.ts", | |||
"test": "test.ts", | |||
"tsconfig": "tsconfig.app.json", | |||
"testTsconfig": "tsconfig.spec.json", | |||
"prefix": "app", | |||
"styles": [ | |||
"globals.scss", | |||
"../node_modules/bootstrap/scss/bootstrap.scss" | |||
], | |||
"scripts": [], | |||
"environmentSource": "environments/environment.ts", | |||
"environments": { | |||
"dev": "environments/environment.ts", | |||
"prod": "environments/environment.prod.ts" | |||
} | |||
} | |||
], | |||
"e2e": { | |||
"protractor": { | |||
"config": "./protractor.conf.js" | |||
} | |||
}, | |||
"lint": [ | |||
{ | |||
"project": "Client/tsconfig.app.json" | |||
}, | |||
{ | |||
"project": "Client/tsconfig.spec.json" | |||
}, | |||
{ | |||
"project": "e2e/tsconfig.e2e.json" | |||
} | |||
], | |||
"test": { | |||
"karma": { | |||
"config": "./karma.conf.js" | |||
} | |||
}, | |||
"defaults": { | |||
"styleExt": "scss", | |||
"component": {} | |||
} | |||
} |