master c6ebbb208e1d cached
146 files
414.5 KB
97.1k tokens
367 symbols
1 requests
Download .txt
Showing preview only (456K chars total). Download the full file or copy to clipboard to get everything.
Repository: Azure-Samples/service-fabric-dotnet-web-reference-app
Branch: master
Commit: c6ebbb208e1d
Files: 146
Total size: 414.5 KB

Directory structure:
gitextract_lulu55kd/

├── .gitignore
├── CONTRIBUTING.md
├── Docs/
│   └── architecture.md
├── LICENSE
├── README.md
└── ReferenceApp/
    ├── Common/
    │   ├── ActorMessageId.cs
    │   ├── Common.csproj
    │   ├── HashUtil.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── ServiceUriBuilder.cs
    │   └── packages.config
    ├── CustomerOrder.Actor/
    │   ├── ActorEventSource.cs
    │   ├── App.config
    │   ├── CustomerOrder.Actor.csproj
    │   ├── CustomerOrderActor.cs
    │   ├── CustomerOrderReminderNames.cs
    │   ├── PackageRoot/
    │   │   ├── Config/
    │   │   │   └── Settings.xml
    │   │   └── ServiceManifest.xml
    │   ├── Program.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   └── packages.config
    ├── CustomerOrder.Domain/
    │   ├── CustomerOrder.Domain.csproj
    │   ├── CustomerOrderItem.cs
    │   ├── CustomerOrderStatus.cs
    │   ├── ICustomerOrderActor.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── app.config
    │   └── packages.config
    ├── CustomerOrder.UnitTests/
    │   ├── CustomerOrder.UnitTests.csproj
    │   ├── CustomerOrderActorTests.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── app.config
    │   └── packages.config
    ├── Inventory.Domain/
    │   ├── IInventoryService.cs
    │   ├── Inventory.Domain.csproj
    │   ├── InventoryItem.cs
    │   ├── InventoryItemId.cs
    │   ├── InventoryItemView.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   └── packages.config
    ├── Inventory.Service/
    │   ├── App.config
    │   ├── AzureBackupStore.cs
    │   ├── IBackupStore.cs
    │   ├── Inventory.Service.csproj
    │   ├── InventoryService.cs
    │   ├── LocalBackupStore.cs
    │   ├── PackageRoot/
    │   │   ├── Config/
    │   │   │   └── Settings.xml
    │   │   └── ServiceManifest.xml
    │   ├── Program.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── ServiceEventSource.cs
    │   ├── StatefulServiceParameters.cs
    │   └── packages.config
    ├── Inventory.UnitTests/
    │   ├── Inventory.UnitTests.csproj
    │   ├── InventoryServiceTests.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── app.config
    │   └── packages.config
    ├── Mocks/
    │   ├── MockActorStateManager.cs
    │   ├── MockAsyncEnumerable.cs
    │   ├── MockCodePackageActivationContext.cs
    │   ├── MockInventoryService.cs
    │   ├── MockReliableDictionary.cs
    │   ├── MockReliableQueue.cs
    │   ├── MockReliableStateManager.cs
    │   ├── MockServiceProxy.cs
    │   ├── MockServiceProxyFactory.cs
    │   ├── MockTransaction.cs
    │   ├── Mocks.csproj
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── app.config
    │   └── packages.config
    ├── Nuget.Config
    ├── RestockRequest.Actor/
    │   ├── ActorEventSource.cs
    │   ├── App.config
    │   ├── PackageRoot/
    │   │   ├── Config/
    │   │   │   └── Settings.xml
    │   │   └── ServiceManifest.xml
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── RestockRequest.Actor.csproj
    │   ├── RestockRequestActor.cs
    │   ├── RestockRequestActorState.cs
    │   ├── RestockRequestReminderNames.cs
    │   ├── ServiceHost.cs
    │   └── packages.config
    ├── RestockRequest.Domain/
    │   ├── IRestockRequestActor.cs
    │   ├── IRestockRequestEvents.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── RestockRequest.Domain.csproj
    │   ├── RestockRequest.cs
    │   ├── RestockRequestStatus.cs
    │   ├── app.config
    │   └── packages.config
    ├── RestockRequestManager.Domain/
    │   ├── IRestockRequestManager.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── RestockRequestManager.Domain.csproj
    │   ├── app.config
    │   └── packages.config
    ├── RestockRequestManager.Service/
    │   ├── App.config
    │   ├── PackageRoot/
    │   │   ├── Config/
    │   │   │   └── Settings.xml
    │   │   └── ServiceManifest.xml
    │   ├── Program.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── RestockRequestManager.Service.csproj
    │   ├── RestockRequestManagerService.cs
    │   ├── ServiceEventSource.cs
    │   └── packages.config
    ├── Web.Service/
    │   ├── .bowerrc
    │   ├── App.config
    │   ├── Controllers/
    │   │   ├── HomeController.cs
    │   │   ├── InventoryController.cs
    │   │   ├── OrdersController.cs
    │   │   └── StoreController.cs
    │   ├── PackageRoot/
    │   │   ├── Config/
    │   │   │   └── Settings.xml
    │   │   └── ServiceManifest.xml
    │   ├── Program.cs
    │   ├── Properties/
    │   │   └── launchSettings.json
    │   ├── ServiceEventSource.cs
    │   ├── Startup.cs
    │   ├── Views/
    │   │   ├── Home/
    │   │   │   ├── Admin.cshtml
    │   │   │   ├── Index.cshtml
    │   │   │   └── OrderConfirmation.cshtml
    │   │   ├── Shared/
    │   │   │   ├── Error.cshtml
    │   │   │   ├── _Layout.cshtml
    │   │   │   └── _ValidationScriptsPartial.cshtml
    │   │   ├── _ViewImports.cshtml
    │   │   └── _ViewStart.cshtml
    │   ├── Web.Service.csproj
    │   ├── WebService.cs
    │   ├── appsettings.Development.json
    │   ├── appsettings.json
    │   ├── bower.json
    │   ├── bundleconfig.json
    │   └── wwwroot/
    │       ├── css/
    │       │   └── site.css
    │       └── js/
    │           └── angular-index.js
    ├── WebReferenceApp.sln
    └── WebReferenceApplication/
        ├── ApplicationPackageRoot/
        │   └── ApplicationManifest.xml
        ├── ApplicationParameters/
        │   ├── Cloud.xml
        │   ├── Local.1Node.xml
        │   └── Local.5Node.xml
        ├── PublishProfiles/
        │   ├── Cloud.xml
        │   ├── Local.1Node.xml
        │   └── Local.5Node.xml
        ├── Scripts/
        │   └── Deploy-FabricApplication.ps1
        ├── WebReferenceApplication.sfproj
        ├── app.config
        └── packages.config

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
[Bb]ackup*/
[Oo]bj/
[Bb]in/
pkg/
objd/
TestResults/
.nuget/
*.sln.ide/
_ReSharper.*/
packages/
.vs/
*.user
*.suo
*.cache
*.docstates
_ReSharper.*
nuget.exe
.settings
*.sln.ide



================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to Azure samples

Thank you for your interest in contributing to Azure samples!

## Ways to contribute

You can contribute to [Azure samples](https://azure.microsoft.com/documentation/samples/) in a few different ways:

- Submit feedback on [this sample page](https://azure.microsoft.com/documentation/samples/service-fabric-dotnet-web-reference-app/) whether it was helpful or not.  
- Submit issues through [issue tracker](https://github.com/Azure-Samples/service-fabric-dotnet-web-reference-app/issues) on GitHub. We are actively monitoring the issues and improving our samples.
- If you wish to make code changes to samples, or contribute something new, please follow the [GitHub Forks / Pull requests model](https://help.github.com/articles/fork-a-repo/): Fork the sample repo, make the change and propose it back by submitting a pull request.

================================================
FILE: Docs/architecture.md
================================================
# Application architecture

The application is composed of individual services to perform the major functions of the application:

- Web Service
	- A stateless front-end service that hosts the web UI and HTTP API for interacting with the store.
- Customer Order Actor
	- An actor-based service that handles customer orders. A stateful actor is activated for each new order that's placed. The actor represents the lifetime of the customer order, from placement to fulfillment.
- Inventory Service
	- A stateful service that maintains the store's inventory. This service is partitioned, where each partition of the service holds a subset of the store's entire inventory. With a large number of partitions, this service can scale out to meet data capacity and inventory request throughput.
- RestockRequest Actor
	- A stateful actor that manages the lifetime of a restock request from the inventory service. Each time the inventory runs low on stock for an item, makes a request to refill the inventory. The restock request actor itself would send a request to a supplier for more items, however this is simply simulated within the actor.
- RestockRequest Manager
	- This is a stateful service that manages requests from the inventory service for item restocking. It logs restock requests made by the Inventory Service and activates a RestockRequest Actor to fulfill the requst. It then receives notifications from the actors when a restock request has been fulfilled. These notifications are placed in a ReliableQueue as they come in. The notifications are periodically dequeued and sent back to the Inventory Service.

# Data flow

When a user makes a purchase, data flows the through the system as follows:

![Data flow](./media/dataflow.png)




1. Client sends HTTP POST to /api/orders with order in JSON payload: 

	[{"ItemId":"1d6abc91-ebe7-41ff-b868-4086501903fc","Quantity":1},{"ItemId":"a833f7d0-2f76-4c9f-9353-8c728252da4a","Quantity":2}]
	
	Response from service is a tracking ID: 
	68bf3f53-dc74-4ef9-8f60-89d68508247b
 
2. Web Service creates a new Actor (by specifying a new ActorId) to track the order by calling SubmitOrderAsync() on the Customer Order Actor service.

3. Customer Order Actor saves the order in its state, registers a reminder for itself to complete the order, and returns to the caller. Order processing has a number of steps and may need to retry in case of failure, thus the reminder serves as a queued work item within the Actor in order to prioritize saving the order reliably and returning to the caller as quickly as possible.

4. Customer Order Actor processes the order by requesting stock for the order to be removed from the Inventory Service. If there is not enough stock available to fulfill the order, the actor adds the back ordered items to its list of backordered state and registers another reminder on itself to try fulfilling the order again later. If this process completes successfully (either by completing the order or by tracking backorder items), the reminder for this method is removed, which has the effect of removing the queue work item. If at any point the method throws or the service crashes, the reminder will remain and will be executed again automatically to retry fulfilling the order. NOTE: the retry mechanism is not fully implemented yet.

5. Inventory Service checks to see if available stock is below the restock threshold after removing stock as requested by a CustomerOrder Actor. If the stock for a certain item is below the restock threshold and it's not already being reordered, it calls AddRestockRequestAsync on the Restock Request Manager.

6. When the Restock Request Manager receives a restock request, it creates a new Actor to track the request and adds the Actor to its own Reliable Dictionary so that it may query the restock request Actors later. Upon adding the Actor, it subscribes to event notifications from the Actor. This will be used later to notify the Restock Request Manager when the restock request is complete.

7. The Restock Request Actor registers a reminder on itself to go through the restock processing pipeline. This pipeline is normally where restocking logic would live, but currently it is simply faked by progressing through each step of restocking every time the reminder fires. When it reaches the last step in the pipeline, it signals the completed event (for which the Restock Request Manager is listening), and unregisters the reminder when that completes.

8. When the Restock Request Actor completes the restock request, it signals the complete event which sends the completed RestockRequest back to the Restock Request Manager. The Manager queues the completed Restock Request in a Reliable Queue for later processing and unsubscribes from receiving events from the Actor, which is now complete and will eventually be garbage-collected.

9. Restock Request Manager's RunAsync method periodically drains the queue of Restock Requests and sends those Restock Requests to the Inventory Service for restocking.


================================================
FILE: LICENSE
================================================
The MIT License (MIT)

Copyright (c) 2015 Microsoft Corporation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

================================================
FILE: README.md
================================================
---
languages:
- csharp
products:
- azure
- azure-service-fabric
page_type: sample
description: "The web reference application shows how to build an end-to-end Service Fabric application with multiple types of services."
---

# Service Fabric Web Reference Application

The web reference application shows how to build an end-to-end Service Fabric application with multiple types of services, combining Reliable Services and Reliable Actors to construct a complete solution.

## Scenario

The context of this sample is a web-based store with a customer order and inventory management back-end. Logical parts of the management back-end are represented by individual services, allowing loose coupling of functionality and independently-upgradeable components:

- Customer Order Service
- Inventory Service
- Restocking Service
- Web front-end Service


The customer order and inventory management system tracks user orders, removes items from the inventory to fulfill orders, and requests restocking of inventory items when an item's stock goes below a certain threshold. If a user requests items that are out of stock, the order is placed on back-order until the inventory is replenished, at which point the order is completed.

Using Service Fabric's stateful services, each of these services can maintain its own data, rather than relying a shared monolithic data base. This allows each service to scale independently using Service Fabric's stateful partitioning to meet its unique requirements for data capacity and throughput.

## Running this sample
The majority of this application is self-contained. The only external dependency is to Azure storage for [backup & restore](https://azure.microsoft.com/en-us/documentation/articles/service-fabric-reliable-services-backup-restore/) purposes. There are no other dependencies on external services or databases to manage related to request processing or data persistence. This makes running the complete application pretty easy:

1. Open the .sln solution file in Visual Studio 2015.
2. Edit the Inventory.Service\PackageRoot\Config\Settings.xml file to contain the connection details for your Azure storage account.
2. Press F5 to run.

This deploys the entire web store application on your local machine.

There are two web endpoints to begin interacting with the application:

1. **http://localhost:8505/fabrikam/admin.html** - a very basic admin portal where you can add items into the inventory. When you first launch the application, the inventory is empty.
2. **http://localhost:8505/fabrikam/** - a basic store front-end. This shows the current inventory and your shopping cart where you can add and purchase items to see the flow of data through the system.

## Deploy this sample to Azure
The application can be deployed to Azure by right-clicking the application project in Visual Studio and selecting "Publish".

![Publish dialog](./Docs/media/publish.png)

In the publish dialog box, select the Cloud profile and a connection endpoint. Selecting a connection endpoint from this dialog requires an Azure subscription. If you want to publish to a known cluster without an Azure subscription, you can simply edit the Cloud publish profile XML under PublishProfiles in the application project and specify a cluster connection endpoint there:

``` XML

<?xml version="1.0" encoding="utf-8"?>
<PublishProfile xmlns="http://schemas.microsoft.com/2015/05/fabrictools">
  <!-- ClusterConnectionParameters allows you to specify the PowerShell parameters to use when connecting to the Service Fabric cluster.
       Valid parameters are any that are accepted by the Connect-ServiceFabricCluster cmdlet.

       For a remote cluster, you would need to specify the appropriate parameters for that specific cluster.
         For example: <ClusterConnectionParameters ConnectionEndpoint="mycluster.westus.cloudapp.azure.com:19000" /> -->

  <ClusterConnectionParameters ConnectionEndpoint="mycluster.westus.cloudapp.azure.com:19000" />
  <ApplicationParameterFile Path="..\ApplicationParameters\Cloud.xml" />
</PublishProfile>

```

## Unit Tests
This application also contains unit tests to show the recommended pattern  to create tests against a Service Fabric application.
  Below are the steps  to run or debug a test (using  Visual studio 2015 on a 64 bit windows):
  - Open the WebReferenceApp solution  in Visual studio 2015
  - Select menus "Test" / "Test Setting" / "Default processor architecture" -> x64
  - Rebuild the solution
  - Select menus "Test" / "Windows" / "Test Explorer" you should see now the text explorer window with the list of available tests
  - Choose one or more tests (for example "TestAddStock" under InventoryServiceTests)
  - Right click the test of your choice and select run the test, you will see after a while a green check mark of test passed
  - You can try also to debug the test  to  understand better  its logic


## Next steps

- [Learn about the application architecture and data flow.](https://github.com/Azure-Samples/service-fabric-dotnet-web-reference-app/blob/master/Docs/architecture.md "Learn about the application architecture and data flow.")


## MSFT OSS Code Of Conduct Notice
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.


================================================
FILE: ReferenceApp/Common/ActorMessageId.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace Common
{
    using System;
    using System.Runtime.Serialization;
    using Microsoft.ServiceFabric.Actors;

    [DataContract]
    public class CustomerOrderActorMessageId : IFormattable, IComparable, IComparable<CustomerOrderActorMessageId>, IEquatable<CustomerOrderActorMessageId>
    {
        public CustomerOrderActorMessageId(ActorId sendingActorId, long messageId)
        {
            this.sendingActorId = sendingActorId;
            this.messageId = messageId;
        }

        [DataMember]
        public ActorId sendingActorId { get; private set; }

        [DataMember]
        public long messageId { get; private set; }

        int IComparable.CompareTo(object obj)
        {
            return this.CompareTo((CustomerOrderActorMessageId) obj);
        }

        public int CompareTo(CustomerOrderActorMessageId other)
        {
            if (this.sendingActorId.ToString().CompareTo(other.sendingActorId.ToString()) > 1)
            {
                return 1;
            }
            else if (this.sendingActorId.ToString().CompareTo(other.sendingActorId.ToString()) < 1)
            {
                return -1;
            }
            else if (this.messageId > other.messageId)
            {
                return 1;
            }
            else if (this.messageId < other.messageId)
            {
                return -1;
            }

            return 0;
        }

        public bool Equals(CustomerOrderActorMessageId other)
        {
            return (this.sendingActorId.Equals(other.sendingActorId) && this.messageId == other.messageId);
        }

        public string ToString(string format, IFormatProvider formatProvider)
        {
            return string.Format("{0}|{1}", this.sendingActorId.ToString(), this.messageId);
        }

        public static CustomerOrderActorMessageId GetRandom()
        {
            ActorId id = new ActorId(Guid.NewGuid());
            Random r = new Random();
            return new CustomerOrderActorMessageId(id, r.Next());
        }

        public static bool operator ==(CustomerOrderActorMessageId item1, CustomerOrderActorMessageId item2)
        {
            return item1.Equals(item2);
        }

        public static bool operator !=(CustomerOrderActorMessageId item1, CustomerOrderActorMessageId item2)
        {
            return !item1.Equals(item2);
        }

        public static bool operator >(CustomerOrderActorMessageId item1, CustomerOrderActorMessageId item2)
        {
            int result = item1.CompareTo(item2);
            return (result == 0 | result == -1);
        }

        public static bool operator <(CustomerOrderActorMessageId item1, CustomerOrderActorMessageId item2)
        {
            int result = item1.CompareTo(item2);
            return (result == 0 | result == 1);
        }

        public override bool Equals(object obj)
        {
            return (this.CompareTo(obj as CustomerOrderActorMessageId) == 0);
        }

        public override int GetHashCode()
        {
            return this.ToString().GetHashCode();
        }
    }
}

================================================
FILE: ReferenceApp/Common/Common.csproj
================================================
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">x64</Platform>
    <ProjectGuid>{9EC0063F-489E-43FE-94B5-BF5F89977CD3}</ProjectGuid>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>Common</RootNamespace>
    <AssemblyName>Common</AssemblyName>
    <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <NuGetPackageImportStamp>
    </NuGetPackageImportStamp>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
    <DebugSymbols>true</DebugSymbols>
    <OutputPath>bin\x64\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <DebugType>full</DebugType>
    <PlatformTarget>x64</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
    <OutputPath>bin\x64\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <Optimize>true</Optimize>
    <DebugType>pdbonly</DebugType>
    <PlatformTarget>x64</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Microsoft.ServiceFabric.Actors, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Actors.2.6.204\lib\net45\Microsoft.ServiceFabric.Actors.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Data, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Data.2.6.204\lib\net45\Microsoft.ServiceFabric.Data.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Data.Interfaces, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Data.2.6.204\lib\net45\Microsoft.ServiceFabric.Data.Interfaces.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.FabricTransport, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.FabricTransport.Internal.2.6.204\lib\net45\Microsoft.ServiceFabric.FabricTransport.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Internal, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\Microsoft.ServiceFabric.Internal.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Internal.Strings, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\Microsoft.ServiceFabric.Internal.Strings.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Services, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Services.2.6.204\lib\net45\Microsoft.ServiceFabric.Services.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Services.Remoting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Services.Remoting.2.6.204\lib\net45\Microsoft.ServiceFabric.Services.Remoting.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Fabric, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="System.Fabric.Management.ServiceModel, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Management.ServiceModel.dll</HintPath>
    </Reference>
    <Reference Include="System.Fabric.Management.ServiceModel.XmlSerializers, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Management.ServiceModel.XmlSerializers.dll</HintPath>
    </Reference>
    <Reference Include="System.Fabric.Strings, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Strings.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="System.Runtime.Serialization" />
    <Reference Include="System.ServiceModel" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Data" />
    <Reference Include="System.Net.Http" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="ActorMessageId.cs" />
    <Compile Include="HashUtil.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
    <Compile Include="ServiceUriBuilder.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Include="packages.config" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <Import Project="..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets" Condition="Exists('..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets'))" />
  </Target>
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>

================================================
FILE: ReferenceApp/Common/HashUtil.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace Common
{
    using System;
    using System.Security.Cryptography;
    using System.Text;

    public class HashUtil
    {
        public static long getLongHashCode(string stringInput)
        {
            byte[] byteContents = Encoding.Unicode.GetBytes(stringInput);
            MD5CryptoServiceProvider hash = new MD5CryptoServiceProvider();
            byte[] hashText = hash.ComputeHash(byteContents);
            return BitConverter.ToInt64(hashText, 0) ^ BitConverter.ToInt64(hashText, 7);
        }

        public static int getIntHashCode(string stringInput)
        {
            return (int) getLongHashCode(stringInput);
        }
    }
}

================================================
FILE: ReferenceApp/Common/Properties/AssemblyInfo.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following 
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.

[assembly: AssemblyTitle("Common")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Common")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible 
// to COM components.  If you need to access a type in this assembly from 
// COM, set the ComVisible attribute to true on that type.

[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM

[assembly: Guid("9ec0063f-489e-43fe-94b5-bf5f89977cd3")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers 
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

================================================
FILE: ReferenceApp/Common/ServiceUriBuilder.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace Common
{
    using System;
    using System.Fabric;

    public class ServiceUriBuilder
    {
        public ServiceUriBuilder(string serviceInstance)
        {
            this.ActivationContext = FabricRuntime.GetActivationContext();
            this.ServiceInstance = serviceInstance;
        }

        public ServiceUriBuilder(ICodePackageActivationContext context, string serviceInstance)
        {
            this.ActivationContext = context;
            this.ServiceInstance = serviceInstance;
        }

        public ServiceUriBuilder(ICodePackageActivationContext context, string applicationInstance, string serviceInstance)
        {
            this.ActivationContext = context;
            this.ApplicationInstance = applicationInstance;
            this.ServiceInstance = serviceInstance;
        }

        /// <summary>
        /// The name of the application instance that contains he service.
        /// </summary>
        public string ApplicationInstance { get; set; }

        /// <summary>
        /// The name of the service instance.
        /// </summary>
        public string ServiceInstance { get; set; }

        /// <summary>
        /// The local activation context
        /// </summary>
        public ICodePackageActivationContext ActivationContext { get; set; }

        public Uri ToUri()
        {
            string applicationInstance = this.ApplicationInstance;

            if (String.IsNullOrEmpty(applicationInstance))
            {
                // the ApplicationName property here automatically prepends "fabric:/" for us
                applicationInstance = this.ActivationContext.ApplicationName.Replace("fabric:/", String.Empty);
            }

            return new Uri("fabric:/" + applicationInstance + "/" + this.ServiceInstance);
        }
    }
}

================================================
FILE: ReferenceApp/Common/packages.config
================================================
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.ServiceFabric" version="5.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Actors" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Data" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.FabricTransport.Internal" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Services" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Services.Remoting" version="2.6.204" targetFramework="net452" />
</packages>

================================================
FILE: ReferenceApp/CustomerOrder.Actor/ActorEventSource.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace CustomerOrder.Actor
{
    using System;
    using System.Diagnostics.Tracing;
    using System.Threading.Tasks;
    using Microsoft.ServiceFabric.Actors.Runtime;

    [EventSource(Name = "MyCompany-Web_UIApplication-CustomerOrder")]
    internal sealed class ActorEventSource : EventSource
    {
        private const int MessageEventId = 1;

        // For very high-frequency events it might be advantageous to raise events using WriteEventCore API.
        // This results in more efficient parameter handling, but requires explicit allocation of EventData structure and unsafe code.
        // To enable this code path, define UNSAFE conditional compilation symbol and turn on unsafe code support in project properties.
        private const int ActorMessageEventId = 2;

        private const int ActorHostInitializationFailedEventId = 3;
        public static readonly ActorEventSource Current = new ActorEventSource();

        static ActorEventSource()
        {
            // A workaround for the problem where ETW activities do not get tracked until Tasks infrastructure is initialized.
            // This problem will be fixed in .NET Framework 4.6.2.
            Task.Run(() => { }).Wait();
        }

        // Instance constructor is private to enforce singleton semantics
        private ActorEventSource() : base()
        {
        }

        // Define an instance method for each event you want to record and apply an [Event] attribute to it.
        // The method name is the name of the event.
        // Pass any parameters you want to record with the event (only primitive integer types, DateTime, Guid & string are allowed).
        // Each event method implementation should check whether the event source is enabled, and if it is, call WriteEvent() method to raise the event.
        // The number and types of arguments passed to every event method must exactly match what is passed to WriteEvent().
        // Put [NonEvent] attribute on all methods that do not define an event.
        // For more information see https://msdn.microsoft.com/en-us/library/system.diagnostics.tracing.eventsource.aspx

        [NonEvent]
        public void Message(string message, params object[] args)
        {
            if (this.IsEnabled())
            {
                string finalMessage = string.Format(message, args);
                this.Message(finalMessage);
            }
        }

        [Event(MessageEventId, Level = EventLevel.Informational, Message = "{0}")]
        public void Message(string message)
        {
            if (this.IsEnabled())
            {
                this.WriteEvent(MessageEventId, message);
            }
        }

        [NonEvent]
        public void ActorMessage(Actor actor, string message, params object[] args)
        {
            if (this.IsEnabled()
                && actor.Id != null
                && actor.ActorService != null
                && actor.ActorService.Context != null
                && actor.ActorService.Context.CodePackageActivationContext != null)
            {
                string finalMessage = string.Format(message, args);
                this.ActorMessage(
                    actor.GetType().ToString(),
                    actor.Id.ToString(),
                    actor.ActorService.Context.CodePackageActivationContext.ApplicationTypeName,
                    actor.ActorService.Context.CodePackageActivationContext.ApplicationName,
                    actor.ActorService.Context.ServiceTypeName,
                    actor.ActorService.Context.ServiceName.ToString(),
                    actor.ActorService.Context.PartitionId,
                    actor.ActorService.Context.ReplicaId,
                    actor.ActorService.Context.NodeContext.NodeName,
                    finalMessage);
            }
        }

        [Event(ActorHostInitializationFailedEventId, Level = EventLevel.Error, Message = "Actor host initialization failed",
            Keywords = Keywords.HostInitialization)]
        public void ActorHostInitializationFailed(string exception)
        {
            this.WriteEvent(ActorHostInitializationFailedEventId, exception);
        }

        [Event(ActorMessageEventId, Level = EventLevel.Informational, Message = "{9}")]
        private
        void ActorMessage(
            string actorType,
            string actorId,
            string applicationTypeName,
            string applicationName,
            string serviceTypeName,
            string serviceName,
            Guid partitionId,
            long replicaOrInstanceId,
            string nodeName,
            string message)
        {
            this.WriteEvent(
                ActorMessageEventId,
                actorType,
                actorId,
                applicationTypeName,
                applicationName,
                serviceTypeName,
                serviceName,
                partitionId,
                replicaOrInstanceId,
                nodeName,
                message);
        }

        // Event keywords can be used to categorize events. 
        // Each keyword is a bit flag. A single event can be associated with multiple keywords (via EventAttribute.Keywords property).
        // Keywords must be defined as a public class named 'Keywords' inside EventSource that uses them.
        public static class Keywords
        {
            public const EventKeywords HostInitialization = (EventKeywords) 0x1L;
        }
    }
}

================================================
FILE: ReferenceApp/CustomerOrder.Actor/App.config
================================================
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Fabric" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

================================================
FILE: ReferenceApp/CustomerOrder.Actor/CustomerOrder.Actor.csproj
================================================
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">x64</Platform>
    <ProjectGuid>{5F0C7805-C91D-47E9-AEDE-946CADEA1C8F}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>CustomerOrder.Actor</RootNamespace>
    <AssemblyName>CustomerOrder.Actor</AssemblyName>
    <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <NuGetPackageImportStamp>
    </NuGetPackageImportStamp>
    <IsServiceFabricServiceProject>True</IsServiceFabricServiceProject>
  </PropertyGroup>
  <PropertyGroup>
    <UpdateServiceFabricManifestEnabled>true</UpdateServiceFabricManifestEnabled>
    <ServicePackagePath>PackageRoot</ServicePackagePath>
    <ServicePackagePrefix>$(MSBuildProjectName)</ServicePackagePrefix>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
    <PlatformTarget>x64</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
    <PlatformTarget>x64</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Microsoft.ServiceFabric.Actors, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Actors.2.6.204\lib\net45\Microsoft.ServiceFabric.Actors.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Data, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Data.2.6.204\lib\net45\Microsoft.ServiceFabric.Data.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Data.Interfaces, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Data.2.6.204\lib\net45\Microsoft.ServiceFabric.Data.Interfaces.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.FabricTransport, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.FabricTransport.Internal.2.6.204\lib\net45\Microsoft.ServiceFabric.FabricTransport.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Internal, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\Microsoft.ServiceFabric.Internal.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Internal.Strings, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\Microsoft.ServiceFabric.Internal.Strings.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Services, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Services.2.6.204\lib\net45\Microsoft.ServiceFabric.Services.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Services.Remoting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Services.Remoting.2.6.204\lib\net45\Microsoft.ServiceFabric.Services.Remoting.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Fabric, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="System.Fabric.Management.ServiceModel, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Management.ServiceModel.dll</HintPath>
    </Reference>
    <Reference Include="System.Fabric.Management.ServiceModel.XmlSerializers, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Management.ServiceModel.XmlSerializers.dll</HintPath>
    </Reference>
    <Reference Include="System.Fabric.Strings, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Strings.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="System.Runtime.Serialization" />
    <Reference Include="System.ServiceModel" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="CustomerOrderReminderNames.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
    <Compile Include="CustomerOrderActor.cs" />
    <Compile Include="Program.cs" />
    <Compile Include="ActorEventSource.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Include="PackageRoot\ServiceManifest.xml" />
    <None Include="PackageRoot\Config\Settings.xml" />
    <None Include="App.config">
      <SubType>Designer</SubType>
    </None>
    <None Include="packages.config" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\CustomerOrder.Domain\CustomerOrder.Domain.csproj">
      <Project>{1E7E813F-43D3-4D0B-8546-5E1023873F28}</Project>
      <Name>CustomerOrder.Domain</Name>
    </ProjectReference>
    <ProjectReference Include="..\Common\Common.csproj">
      <Project>{9ec0063f-489e-43fe-94b5-bf5f89977cd3}</Project>
      <Name>Common</Name>
    </ProjectReference>
    <ProjectReference Include="..\Inventory.Domain\Inventory.Domain.csproj">
      <Project>{7e9c2dfd-71a5-496d-aa4d-5ec53eaeb9ae}</Project>
      <Name>Inventory.Domain</Name>
    </ProjectReference>
    <ProjectReference Include="..\Mocks\Mocks.csproj">
      <Project>{00E00484-BD00-40CD-B2CC-1CFA8E893972}</Project>
      <Name>Mocks</Name>
    </ProjectReference>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <Import Project="..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets" Condition="Exists('..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets'))" />
  </Target>
</Project>

================================================
FILE: ReferenceApp/CustomerOrder.Actor/CustomerOrderActor.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace CustomerOrder.Actor
{
    using Common;
    using CustomerOrder.Domain;
    using Inventory.Domain;
    using Microsoft.ServiceFabric.Actors;
    using Microsoft.ServiceFabric.Actors.Runtime;
    using Microsoft.ServiceFabric.Data;
    using Microsoft.ServiceFabric.Services.Remoting.Client;
    using Mocks;
    using System;
    using System.Collections.Generic;
    using System.Fabric;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;

    internal class CustomerOrderActor : Actor, ICustomerOrderActor, IRemindable
    {
        private const string InventoryServiceName = "InventoryService";
        private const string OrderItemListPropertyName = "OrderList";
        private const string OrderStatusPropertyName = "CustomerOrderStatus";
        private const string RequestIdPropertyName = "RequestId";
        private IServiceProxyFactory ServiceProxyFactory;
        private ServiceUriBuilder builder;
        private CancellationTokenSource tokenSource = null;

        public CustomerOrderActor(ActorService actorService, ActorId actorId)
            : base (actorService, actorId)
        { }

        /// <summary>
        /// This method accepts a list of CustomerOrderItems, representing a customer order, and sets the actor's state
        /// to reflect the status and contents of the order. Then, the order is fulfilled with a private FulfillOrder call
        /// that abstracts away the entire backorder process from the user. 
        /// </summary>
        /// <param name="orderList"></param>
        /// <returns></returns>
        public async Task SubmitOrderAsync(IEnumerable<CustomerOrderItem> orderList)
        {
            try
            {
                await this.StateManager.SetStateAsync<List<CustomerOrderItem>>(OrderItemListPropertyName, new List<CustomerOrderItem>(orderList));
                await this.StateManager.SetStateAsync<CustomerOrderStatus>(OrderStatusPropertyName, CustomerOrderStatus.Submitted);

                await this.RegisterReminderAsync(
                    CustomerOrderReminderNames.FulfillOrderReminder,
                    null,
                    TimeSpan.FromSeconds(10),
                    TimeSpan.FromSeconds(10));
            }
            catch (Exception e)
            {
                ActorEventSource.Current.Message(e.ToString());
            }

            ActorEventSource.Current.Message("Order submitted with {0} items", orderList.Count());

            return;
        }

        /// <summary>
        /// Returns the status of the Customer Order. 
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetOrderStatusAsStringAsync()
        {
            return (await this.GetOrderStatusAsync()).ToString();
        }

        public async Task ReceiveReminderAsync(string reminderName, byte[] context, TimeSpan dueTime, TimeSpan period)
        {
            switch (reminderName)
            {
                case CustomerOrderReminderNames.FulfillOrderReminder:

                    await this.FulfillOrderAsync();

                    CustomerOrderStatus orderStatus = await this.GetOrderStatusAsync();

                    if (orderStatus == CustomerOrderStatus.Shipped || orderStatus == CustomerOrderStatus.Canceled)
                    {
                        //Remove fulfill order reminder so Actor can be gargabe collected.
                        IActorReminder orderReminder = this.GetReminder(CustomerOrderReminderNames.FulfillOrderReminder);
                        await this.UnregisterReminderAsync(orderReminder);
                    }

                    break;

                default:
                    // We should never arrive here normally. The system won't call reminders that don't exist. 
                    // But for our own sake in case we add a new reminder somewhere and forget to handle it, this will remind us.
                    throw new InvalidOperationException("Unknown reminder: " + reminderName);
            }
        }

        /// <summary>
        /// Initializes CustomerOrderActor state. Because an order actor will only be activated
        /// once in this scenario and never used again, when we initiate the actor's state we
        /// change the order's status to "Confirmed," and do not need to check if the actor's 
        /// state was already set to this. 
        /// </summary>
        /// 
        protected override async Task OnActivateAsync()
        {
            await InternalActivateAsync(this.ActorService.Context.CodePackageActivationContext, new ServiceProxyFactory());

            CustomerOrderStatus orderStatusResult = await this.GetOrderStatusAsync();

            if (orderStatusResult == CustomerOrderStatus.Unknown)
            {
                await this.StateManager.SetStateAsync<List<CustomerOrderItem>>(OrderItemListPropertyName, new List<CustomerOrderItem>());
                await this.StateManager.SetStateAsync<long>(RequestIdPropertyName, 0);
                await this.SetOrderStatusAsync(CustomerOrderStatus.New);
            }

            return;
        }

        /// <summary>
        /// Adding this method to support DI/Testing 
        /// We need to do some work to create the actor object and make sure it is constructed completely
        /// In local testing we can inject the components we need, but in a real cluster
        /// those items are not established until the actor object is activated. Thus we need to 
        /// have this method so that the tests can have the same init path as the actor would in prod
        /// </summary>
        /// <returns></returns>
        public async Task InternalActivateAsync(ICodePackageActivationContext context, IServiceProxyFactory proxyFactory)
        {
            this.tokenSource = new CancellationTokenSource();
            this.builder = new ServiceUriBuilder(context, InventoryServiceName);
            this.ServiceProxyFactory = proxyFactory;
        }

        /// <summary>
        /// Deactivates the actor object
        /// </summary>
        /// <returns></returns>
        protected override Task OnDeactivateAsync()
        {
            this.tokenSource.Cancel();
            this.tokenSource.Dispose();
            return Task.FromResult(true);
        }

        /// <summary>
        /// This method takes in a list of CustomerOrderItem objects. Using a Service Proxy to access the Inventory Service,
        /// the method iterates onces through the order and tries to remove the quantity specified in the order from inventory. 
        /// If the inventory has insufficient stock to remove the requested amount for a particular item, the entire order is 
        /// marked as backordered and the item in question is added to a "backordered" item list, which is fulfilled in a separate 
        /// method. 
        /// 
        /// In its current form, this application addresses the question of race conditions to remove the same item by making a rule
        /// that no order ever fails. While an item that is displayed in the store may not be available any longer by the time an order is placed,
        /// the automatic restock policy instituted in the Inventory Service means that our FulfillOrder method and its sub-methods can continue to 
        /// query the Inventory Service on repeat (with a timer in between each cycle) until the order is fulfilled. 
        /// 
        /// </summary>
        /// <returns>The number of items put on backorder after fulfilling the order.</returns>
        internal async Task FulfillOrderAsync()
        {

            await this.SetOrderStatusAsync(CustomerOrderStatus.InProcess);

            IList<CustomerOrderItem> orderedItems = await this.StateManager.GetStateAsync<IList<CustomerOrderItem>>(OrderItemListPropertyName);

            ActorEventSource.Current.ActorMessage(this, "Fullfilling customer order. ID: {0}. Items: {1}", this.Id.GetGuidId(), orderedItems.Count);

            foreach (CustomerOrderItem tempitem in orderedItems)
            {
                ActorEventSource.Current.Message("OrderContains:{0}", tempitem);
            }

            //We loop through the customer order list. 
            //For every item that cannot be fulfilled, we add to backordered. 
            foreach (CustomerOrderItem item in orderedItems.Where(x => x.FulfillmentRemaining > 0))
            {
                IInventoryService inventoryService = this.ServiceProxyFactory.CreateServiceProxy<IInventoryService>(this.builder.ToUri(), item.ItemId.GetPartitionKey());

                //First, check the item is listed in inventory.  
                //This will avoid infinite backorder status.
                if ((await inventoryService.IsItemInInventoryAsync(item.ItemId, this.tokenSource.Token)) == false)
                {
                    await this.SetOrderStatusAsync(CustomerOrderStatus.Canceled);
                    return;
                }

                int numberItemsRemoved =
                    await
                        inventoryService.RemoveStockAsync(
                            item.ItemId,
                            item.Quantity,
                            new CustomerOrderActorMessageId(
                                new ActorId(this.Id.GetGuidId()),
                                await this.StateManager.GetStateAsync<long>(RequestIdPropertyName)));

                item.FulfillmentRemaining -= numberItemsRemoved;
            }

            IList<CustomerOrderItem> items = await this.StateManager.GetStateAsync<IList<CustomerOrderItem>>(OrderItemListPropertyName);
            bool backordered = false;

            // Set the status appropriately
            foreach (CustomerOrderItem item in items)
            {
                if (item.FulfillmentRemaining > 0)
                {
                    backordered = true;
                    break;
                }
            }

            if (backordered)
            {
                await this.SetOrderStatusAsync(CustomerOrderStatus.Backordered);
            }
            else
            {
                await this.SetOrderStatusAsync(CustomerOrderStatus.Shipped);
            }

            ActorEventSource.Current.ActorMessage(
                this,
                "{0}; Fulfilled: {1}. Backordered: {2}",
                await this.GetOrderStatusAsStringAsync(),
                items.Count(x => x.FulfillmentRemaining == 0),
                items.Count(x => x.FulfillmentRemaining > 0));

            long messageRequestId = await this.StateManager.GetStateAsync<long>(RequestIdPropertyName);
            await this.StateManager.SetStateAsync<long>(RequestIdPropertyName, ++messageRequestId);
        }

        private async Task<CustomerOrderStatus> GetOrderStatusAsync()
        {
            ConditionalValue<CustomerOrderStatus> orderStatusResult = await this.StateManager.TryGetStateAsync<CustomerOrderStatus>(OrderStatusPropertyName);
            if (orderStatusResult.HasValue)
            {
                return orderStatusResult.Value;
            }
            else
            {
                return CustomerOrderStatus.Unknown;
            }
        }

        private async Task SetOrderStatusAsync(CustomerOrderStatus orderStatus)
        {
            await this.StateManager.SetStateAsync<CustomerOrderStatus>(OrderStatusPropertyName, orderStatus);
        }
    }
}

================================================
FILE: ReferenceApp/CustomerOrder.Actor/CustomerOrderReminderNames.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace CustomerOrder.Actor
{
    internal static class CustomerOrderReminderNames
    {
        public const string FulfillOrderReminder = "FulfillOrderReminder";
    }
}

================================================
FILE: ReferenceApp/CustomerOrder.Actor/PackageRoot/Config/Settings.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<Settings xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2011/01/fabric">
  <Section Name="CustomerOrderActorServiceReplicatorConfig">
    <Parameter Name="ReplicatorEndpoint" Value="CustomerOrderActorServiceReplicatorEndpoint" />
    <Parameter Name="BatchAcknowledgementInterval" Value="0.005" />
  </Section>
  <Section Name="CustomerOrderActorServiceReplicatorSecurityConfig">
    <Parameter Name="CredentialType" Value="None" />
  </Section>
</Settings>

================================================
FILE: ReferenceApp/CustomerOrder.Actor/PackageRoot/ServiceManifest.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<ServiceManifest xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="CustomerOrder.ActorPkg" Version="1.0.0" xmlns="http://schemas.microsoft.com/2011/01/fabric">
  <ServiceTypes>
    <StatefulServiceType ServiceTypeName="CustomerOrderActorServiceType">
      <Extensions>
        <Extension Name="__GeneratedServiceType__" GeneratedId="36545b1e-9aa7-417b-a8aa-b7e28fd47353|None">
          <GeneratedNames xmlns="http://schemas.microsoft.com/2015/03/fabact-no-schema">
            <DefaultService Name="CustomerOrderActorService" />
            <ServiceEndpoint Name="CustomerOrderActorServiceEndpoint" />
            <ReplicatorEndpoint Name="CustomerOrderActorServiceReplicatorEndpoint" />
            <ReplicatorConfigSection Name="CustomerOrderActorServiceReplicatorConfig" />
            <ReplicatorSecurityConfigSection Name="CustomerOrderActorServiceReplicatorSecurityConfig" />
            <StoreConfigSection Name="CustomerOrderActorServiceLocalStoreConfig" />
          </GeneratedNames>
        </Extension>
      </Extensions>
    </StatefulServiceType>
  </ServiceTypes>
  <CodePackage Name="Code" Version="1.0.0">
    <EntryPoint>
      <ExeHost>
        <Program>CustomerOrder.Actor.exe</Program>
      </ExeHost>
    </EntryPoint>
  </CodePackage>
  <ConfigPackage Name="Config" Version="1.0.0" />
  <Resources>
    <Endpoints>
      <Endpoint Name="CustomerOrderActorServiceEndpoint" />
      <Endpoint Name="CustomerOrderActorServiceReplicatorEndpoint" />
    </Endpoints>
  </Resources>
</ServiceManifest>

================================================
FILE: ReferenceApp/CustomerOrder.Actor/Program.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace CustomerOrder.Actor
{
    using System;
    using System.Threading;
    using Microsoft.ServiceFabric.Actors.Runtime;

    public class Program
    {
        public static void Main(string[] args)
        {
            try
            {
                ActorRuntime.RegisterActorAsync<CustomerOrderActor>();
                Thread.Sleep(Timeout.Infinite);
            }
            catch (Exception e)
            {
                ActorEventSource.Current.ActorHostInitializationFailed(e.ToString());
                throw;
            }
        }
    }
}

================================================
FILE: ReferenceApp/CustomerOrder.Actor/Properties/AssemblyInfo.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following 
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.

[assembly: AssemblyTitle("CustomerOrder")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CustomerOrder")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible 
// to COM components.  If you need to access a type in this assembly from 
// COM, set the ComVisible attribute to true on that type.

[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM

[assembly: Guid("5f0c7805-c91d-47e9-aede-946cadea1c8f")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers 
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("CustomerOrder.UnitTests")]

================================================
FILE: ReferenceApp/CustomerOrder.Actor/packages.config
================================================
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.ServiceFabric" version="5.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Actors" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Data" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.FabricTransport.Internal" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Services" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Services.Remoting" version="2.6.204" targetFramework="net452" />
</packages>

================================================
FILE: ReferenceApp/CustomerOrder.Domain/CustomerOrder.Domain.csproj
================================================
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">x64</Platform>
    <ProjectGuid>{1E7E813F-43D3-4D0B-8546-5E1023873F28}</ProjectGuid>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>CustomerOrder.Domain</RootNamespace>
    <AssemblyName>CustomerOrder.Domain</AssemblyName>
    <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <NuGetPackageImportStamp>
    </NuGetPackageImportStamp>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
    <DebugSymbols>true</DebugSymbols>
    <OutputPath>bin\x64\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <DebugType>full</DebugType>
    <PlatformTarget>x64</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
    <OutputPath>bin\x64\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <Optimize>true</Optimize>
    <DebugType>pdbonly</DebugType>
    <PlatformTarget>x64</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Microsoft.ServiceFabric.Actors, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Actors.2.6.204\lib\net45\Microsoft.ServiceFabric.Actors.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Data, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Data.2.6.204\lib\net45\Microsoft.ServiceFabric.Data.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Data.Interfaces, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Data.2.6.204\lib\net45\Microsoft.ServiceFabric.Data.Interfaces.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.FabricTransport, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.FabricTransport.Internal.2.6.204\lib\net45\Microsoft.ServiceFabric.FabricTransport.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Internal, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\Microsoft.ServiceFabric.Internal.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Internal.Strings, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\Microsoft.ServiceFabric.Internal.Strings.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Services, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Services.2.6.204\lib\net45\Microsoft.ServiceFabric.Services.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Services.Remoting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Services.Remoting.2.6.204\lib\net45\Microsoft.ServiceFabric.Services.Remoting.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Fabric, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="System.Fabric.Management.ServiceModel, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Management.ServiceModel.dll</HintPath>
    </Reference>
    <Reference Include="System.Fabric.Management.ServiceModel.XmlSerializers, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Management.ServiceModel.XmlSerializers.dll</HintPath>
    </Reference>
    <Reference Include="System.Fabric.Strings, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Strings.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="System.Runtime.Serialization" />
    <Reference Include="System.ServiceModel" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="CustomerOrderItem.cs" />
    <Compile Include="CustomerOrderStatus.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
    <Compile Include="ICustomerOrderActor.cs" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\Common\Common.csproj">
      <Project>{9ec0063f-489e-43fe-94b5-bf5f89977cd3}</Project>
      <Name>Common</Name>
    </ProjectReference>
    <ProjectReference Include="..\Inventory.Domain\Inventory.Domain.csproj">
      <Project>{7e9c2dfd-71a5-496d-aa4d-5ec53eaeb9ae}</Project>
      <Name>Inventory.Domain</Name>
    </ProjectReference>
  </ItemGroup>
  <ItemGroup>
    <None Include="app.config" />
    <None Include="packages.config" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <Import Project="..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets" Condition="Exists('..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets'))" />
  </Target>
</Project>

================================================
FILE: ReferenceApp/CustomerOrder.Domain/CustomerOrderItem.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace CustomerOrder.Domain
{
    using System;
    using System.Runtime.Serialization;
    using Inventory.Domain;

    [DataContract]
    public sealed class CustomerOrderItem
    {
        public CustomerOrderItem(InventoryItemId itemId, int quantity)
        {
            this.ItemId = itemId;
            this.Quantity = quantity;
            this.FulfillmentRemaining = quantity;
        }

        [DataMember]
        public InventoryItemId ItemId { get; set; }

        [DataMember]
        public int Quantity { get; set; }

        [DataMember]
        public int FulfillmentRemaining { get; set; }

        public override string ToString()
        {
            return String.Format("ID: {0}, Quantity: {1}, Fulfillment Remaing: {2}", this.ItemId, this.Quantity, this.FulfillmentRemaining);
        }
    }
}

================================================
FILE: ReferenceApp/CustomerOrder.Domain/CustomerOrderStatus.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace CustomerOrder.Domain
{
    public enum CustomerOrderStatus
    {
        Unknown,
        New,
        Submitted,
        InProcess,
        Backordered,
        Shipped,
        Canceled,
    }
}

================================================
FILE: ReferenceApp/CustomerOrder.Domain/ICustomerOrderActor.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace CustomerOrder.Domain
{
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Microsoft.ServiceFabric.Actors;

    public interface ICustomerOrderActor : IActor
    {
        Task<string> GetOrderStatusAsStringAsync();

        Task SubmitOrderAsync(IEnumerable<CustomerOrderItem> orderList);
    }
}

================================================
FILE: ReferenceApp/CustomerOrder.Domain/Properties/AssemblyInfo.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following 
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.

[assembly: AssemblyTitle("CustomerOrder.Interfaces")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CustomerOrder.Interfaces")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible 
// to COM components.  If you need to access a type in this assembly from 
// COM, set the ComVisible attribute to true on that type.

[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM

[assembly: Guid("1e7e813f-43d3-4d0b-8546-5e1023873f28")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers 
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

================================================
FILE: ReferenceApp/CustomerOrder.Domain/app.config
================================================
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Fabric" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

================================================
FILE: ReferenceApp/CustomerOrder.Domain/packages.config
================================================
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.ServiceFabric" version="5.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Actors" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Data" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.FabricTransport.Internal" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Services" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Services.Remoting" version="2.6.204" targetFramework="net452" />
</packages>

================================================
FILE: ReferenceApp/CustomerOrder.UnitTests/CustomerOrder.UnitTests.csproj
================================================
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{226B8D34-99CF-4172-87DC-E20B39030CC0}</ProjectGuid>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>CustomerOrder.UnitTests</RootNamespace>
    <AssemblyName>CustomerOrder.UnitTests</AssemblyName>
    <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
    <ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
    <IsCodedUITest>False</IsCodedUITest>
    <TestProjectType>UnitTest</TestProjectType>
    <NuGetPackageImportStamp>
    </NuGetPackageImportStamp>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
    <DebugSymbols>true</DebugSymbols>
    <OutputPath>bin\x64\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <DebugType>full</DebugType>
    <PlatformTarget>x64</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
    <OutputPath>bin\x64\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <Optimize>true</Optimize>
    <DebugType>pdbonly</DebugType>
    <PlatformTarget>x64</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <Choose>
    <When Condition="('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'">
      <ItemGroup>
        <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
      </ItemGroup>
    </When>
    <Otherwise />
  </Choose>
  <ItemGroup>
    <Compile Include="CustomerOrderActorTests.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\Common\Common.csproj">
      <Project>{9ec0063f-489e-43fe-94b5-bf5f89977cd3}</Project>
      <Name>Common</Name>
    </ProjectReference>
    <ProjectReference Include="..\CustomerOrder.Actor\CustomerOrder.Actor.csproj">
      <Project>{5f0c7805-c91d-47e9-aede-946cadea1c8f}</Project>
      <Name>CustomerOrder.Actor</Name>
    </ProjectReference>
    <ProjectReference Include="..\CustomerOrder.Domain\CustomerOrder.Domain.csproj">
      <Project>{1e7e813f-43d3-4d0b-8546-5e1023873f28}</Project>
      <Name>CustomerOrder.Domain</Name>
    </ProjectReference>
    <ProjectReference Include="..\Inventory.Domain\Inventory.Domain.csproj">
      <Project>{7e9c2dfd-71a5-496d-aa4d-5ec53eaeb9ae}</Project>
      <Name>Inventory.Domain</Name>
    </ProjectReference>
    <ProjectReference Include="..\Mocks\Mocks.csproj">
      <Project>{00e00484-bd00-40cd-b2cc-1cfa8e893972}</Project>
      <Name>Mocks</Name>
    </ProjectReference>
  </ItemGroup>
  <ItemGroup>
    <None Include="app.config" />
    <None Include="packages.config" />
  </ItemGroup>
  <ItemGroup>
    <Reference Include="Microsoft.ServiceFabric.Actors, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Actors.2.6.204\lib\net45\Microsoft.ServiceFabric.Actors.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Data, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Data.2.6.204\lib\net45\Microsoft.ServiceFabric.Data.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Data.Interfaces, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Data.2.6.204\lib\net45\Microsoft.ServiceFabric.Data.Interfaces.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.FabricTransport, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.FabricTransport.Internal.2.6.204\lib\net45\Microsoft.ServiceFabric.FabricTransport.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Internal, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\Microsoft.ServiceFabric.Internal.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Internal.Strings, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\Microsoft.ServiceFabric.Internal.Strings.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Services, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Services.2.6.204\lib\net45\Microsoft.ServiceFabric.Services.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Services.Remoting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Services.Remoting.2.6.204\lib\net45\Microsoft.ServiceFabric.Services.Remoting.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <Private>False</Private>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Fabric, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="System.Fabric.Management.ServiceModel, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Management.ServiceModel.dll</HintPath>
    </Reference>
    <Reference Include="System.Fabric.Management.ServiceModel.XmlSerializers, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Management.ServiceModel.XmlSerializers.dll</HintPath>
    </Reference>
    <Reference Include="System.Fabric.Strings, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Strings.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="System.Numerics" />
    <Reference Include="System.Runtime.Serialization" />
    <Reference Include="System.ServiceModel" />
  </ItemGroup>
  <Choose>
    <When Condition="'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'">
      <ItemGroup>
        <Reference Include="Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
          <Private>False</Private>
        </Reference>
        <Reference Include="Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
          <Private>False</Private>
        </Reference>
        <Reference Include="Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
          <Private>False</Private>
        </Reference>
        <Reference Include="Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
          <Private>False</Private>
        </Reference>
      </ItemGroup>
    </When>
  </Choose>
  <Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <Import Project="..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets" Condition="Exists('..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets'))" />
  </Target>
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>

================================================
FILE: ReferenceApp/CustomerOrder.UnitTests/CustomerOrderActorTests.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace CustomerOrder.UnitTests
{
    using CustomerOrder.Actor;
    using CustomerOrder.Domain;
    using Inventory.Domain;
    using Microsoft.ServiceFabric.Actors;
    using Microsoft.ServiceFabric.Actors.Runtime;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Mocks;
    using System;
    using System.Collections.Generic;
    using System.Fabric;
    using System.Numerics;
    using System.Reflection;
    using System.Threading.Tasks;

    [TestClass]
    public class CustomerOrderActorTests
    {
        private const string OrderItemListPropertyName = "OrderList";
        private const string OrderStatusPropertyName = "CustomerOrderStatus";
        private const string RequestIdPropertyName = "RequestId";
        private const string InventoryServiceName = "InventoryService";

        private static ICodePackageActivationContext codePackageContext = new MockCodePackageActivationContext(
            "fabric:/someapp",
            "SomeAppType",
            "Code",
            "1.0.0.0",
            Guid.NewGuid().ToString(),
            @"C:\Log",
            @"C:\Temp",
            @"C:\Work",
            "ServiceManifest",
            "1.0.0.0"
            );

        private static StatefulServiceContext statefulServiceContext = new StatefulServiceContext(
            new NodeContext("Test", new NodeId(new BigInteger(0), new BigInteger(0)), new BigInteger(0), "TestType", "localhost"),
            codePackageContext,
            "",
            new Uri("fabric:/testapp/testservice"),
            new byte[0],
            Guid.NewGuid(),
            0);

        /// <summary>
        /// Tests FulfillOrder ships an order when all items are available from the InventoryService.
        /// </summary>
        /// <returns></returns>
        [TestMethod]
        public async Task TestFulfillOrderSimple()
        {
            // The default mock inventory service behavior is to always complete an order.

            MockInventoryService inventoryService = new MockInventoryService();

            MockServiceProxyFactory serviceProxyFactory = new MockServiceProxyFactory();
            serviceProxyFactory.AssociateMockServiceAndName(new Uri("fabric:/someapp/" + InventoryServiceName), inventoryService);

            CustomerOrderActor target = await CreateCustomerOrderActor(serviceProxyFactory);

            await target.StateManager.SetStateAsync<CustomerOrderStatus>(RequestIdPropertyName, CustomerOrderStatus.Submitted);
            await target.StateManager.SetStateAsync<long>(RequestIdPropertyName, 0);
            await target.StateManager.SetStateAsync<List<CustomerOrderItem>>(OrderItemListPropertyName, new List<CustomerOrderItem>()
            {
                new CustomerOrderItem(new InventoryItemId(), 4)
            });

            await target.FulfillOrderAsync();

            Assert.AreEqual<CustomerOrderStatus>(CustomerOrderStatus.Shipped, await target.StateManager.GetStateAsync<CustomerOrderStatus>(OrderStatusPropertyName));
        }

        /// <summary>
        /// Tests FulfillOrder does not ship when not all items could be fulfilled by InventoryService.
        /// </summary>
        /// <returns></returns>
        [TestMethod]
        public async Task TestFulfillOrderWithBackorder()
        {
            // instruct the mock inventory service to always return less quantity than requested 
            // so that FulfillOrder always ends up in backordered status.            

            MockInventoryService inventoryService = new MockInventoryService()
            {
                RemoveStockAsyncFunc = (itemId, quantity, cmid) => Task.FromResult(quantity - 1)
            };

            MockServiceProxy serviceProxy = new MockServiceProxy();
            serviceProxy.Supports<IInventoryService>(serviceUri => inventoryService);

            MockServiceProxyFactory serviceProxyFactory = new MockServiceProxyFactory();
            serviceProxyFactory.AssociateMockServiceAndName(new Uri("fabric:/someapp/" + InventoryServiceName), inventoryService);

            CustomerOrderActor target = await CreateCustomerOrderActor(serviceProxyFactory);

            await target.StateManager.SetStateAsync<CustomerOrderStatus>(RequestIdPropertyName, CustomerOrderStatus.Submitted);
            await target.StateManager.SetStateAsync<long>(RequestIdPropertyName, 0);
            await target.StateManager.SetStateAsync<List<CustomerOrderItem>>(OrderItemListPropertyName, new List<CustomerOrderItem>()
            {
                new CustomerOrderItem(new InventoryItemId(), 4)
            });

            await target.FulfillOrderAsync();

            Assert.AreEqual<CustomerOrderStatus>(CustomerOrderStatus.Backordered, await target.StateManager.GetStateAsync<CustomerOrderStatus>(OrderStatusPropertyName));
        }

        /// <summary>
        /// Tests FulfillOrder completes a shipment after multiple iterations when a limited quantity is available from InventoryService.
        /// </summary>
        /// <returns></returns>
        [TestMethod]
        public async Task TestFulfillOrderToCompletion()
        {
            int itemCount = 5;

            // instruct the mock inventory service to only fulfill one item each time
            // so that FulfillOrder has to make multiple iterations to complete an order
            MockInventoryService inventoryService = new MockInventoryService()
            {
                RemoveStockAsyncFunc = (itemId, quantity, cmid) => Task.FromResult(1)
            };

            MockServiceProxy serviceProxy = new MockServiceProxy();
            serviceProxy.Supports<IInventoryService>(serviceUri => inventoryService);

            MockServiceProxyFactory serviceProxyFactory = new MockServiceProxyFactory();
            serviceProxyFactory.AssociateMockServiceAndName(new Uri("fabric:/someapp/" + InventoryServiceName), inventoryService);

            CustomerOrderActor target = await CreateCustomerOrderActor(serviceProxyFactory);

            await target.StateManager.SetStateAsync<CustomerOrderStatus>(RequestIdPropertyName, CustomerOrderStatus.Submitted);
            await target.StateManager.SetStateAsync<long>(RequestIdPropertyName, 0);
            await target.StateManager.SetStateAsync<List<CustomerOrderItem>>(OrderItemListPropertyName, new List<CustomerOrderItem>()
            {
                new CustomerOrderItem(new InventoryItemId(), 5)
            });

            for (int i = 0; i < itemCount - 1; ++i)
            {
                await target.FulfillOrderAsync();
                Assert.AreEqual<CustomerOrderStatus>(CustomerOrderStatus.Backordered, await target.StateManager.GetStateAsync<CustomerOrderStatus>(OrderStatusPropertyName));
            }

            await target.FulfillOrderAsync();
            Assert.AreEqual<CustomerOrderStatus>(CustomerOrderStatus.Shipped, await target.StateManager.GetStateAsync<CustomerOrderStatus>(OrderStatusPropertyName));
        }

        [TestMethod]
        public async Task TestFulfillOrderCancelled()
        {
            // instruct the mock inventory service to return 0 for all items to simulate items that don't exist.
            // and have it return false when asked if an item exists to make sure FulfillOrder doesn't get into
            // an infinite backorder loop.
            MockInventoryService inventoryService = new MockInventoryService()
            {
                IsItemInInventoryAsyncFunc = itemId => Task.FromResult(false),
                RemoveStockAsyncFunc = (itemId, quantity, cmid) => Task.FromResult(0)
            };

            MockServiceProxy serviceProxy = new MockServiceProxy();
            serviceProxy.Supports<IInventoryService>(serviceUri => inventoryService);

            MockServiceProxyFactory serviceProxyFactory = new MockServiceProxyFactory();
            serviceProxyFactory.AssociateMockServiceAndName(new Uri("fabric:/someapp/" + InventoryServiceName), inventoryService);

            CustomerOrderActor target = await CreateCustomerOrderActor(serviceProxyFactory);

            await target.StateManager.SetStateAsync<CustomerOrderStatus>(RequestIdPropertyName, CustomerOrderStatus.Submitted);
            await target.StateManager.SetStateAsync<long>(RequestIdPropertyName, 0);
            await target.StateManager.SetStateAsync<List<CustomerOrderItem>>(OrderItemListPropertyName, new List<CustomerOrderItem>()
            {
                new CustomerOrderItem(new InventoryItemId(), 5)
            });

            await target.FulfillOrderAsync();

            CustomerOrderStatus status = await target.StateManager.GetStateAsync<CustomerOrderStatus>(OrderStatusPropertyName);

            Assert.AreEqual<CustomerOrderStatus>(CustomerOrderStatus.Canceled, status);
        }

        private static async Task<CustomerOrderActor> CreateCustomerOrderActor(MockServiceProxyFactory serviceProxyFactory)
        {
            try
            {
                CustomerOrderActor target = new CustomerOrderActor(
                    new ActorService(
                        context: statefulServiceContext,
                        actorTypeInfo: ActorTypeInformation.Get(typeof(CustomerOrderActor)),
                        stateManagerFactory: (actorBase, stateProvider) => new MockActorStateManager()),
                    new ActorId(Guid.NewGuid()));

                await target.InternalActivateAsync(codePackageContext, serviceProxyFactory);

                return target;
            }
            catch (Exception e)
            {
                throw;
            }
        }
    }
}

================================================
FILE: ReferenceApp/CustomerOrder.UnitTests/Properties/AssemblyInfo.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following 
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.

[assembly: AssemblyTitle("CustomerOrder.UnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CustomerOrder.UnitTests")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible 
// to COM components.  If you need to access a type in this assembly from 
// COM, set the ComVisible attribute to true on that type.

[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM

[assembly: Guid("226b8d34-99cf-4172-87dc-e20b39030cc0")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers 
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

================================================
FILE: ReferenceApp/CustomerOrder.UnitTests/app.config
================================================
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Fabric" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

================================================
FILE: ReferenceApp/CustomerOrder.UnitTests/packages.config
================================================
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.ServiceFabric" version="5.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Actors" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Data" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.FabricTransport.Internal" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Services" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Services.Remoting" version="2.6.204" targetFramework="net452" />
</packages>

================================================
FILE: ReferenceApp/Inventory.Domain/IInventoryService.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace Inventory.Domain
{
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;
    using Common;
    using Microsoft.ServiceFabric.Services.Remoting;

    public interface IInventoryService : IService
    {
        Task<int> AddStockAsync(InventoryItemId itemId, int quantity);
        Task<int> RemoveStockAsync(InventoryItemId itemId, int quantity, CustomerOrderActorMessageId messageId);
        Task<bool> IsItemInInventoryAsync(InventoryItemId itemId, CancellationToken cancellationToken);
        Task<IEnumerable<InventoryItemView>> GetCustomerInventoryAsync(CancellationToken cancellationToken);
        Task<bool> CreateInventoryItemAsync(InventoryItem item);
    }
}

================================================
FILE: ReferenceApp/Inventory.Domain/Inventory.Domain.csproj
================================================
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">x64</Platform>
    <ProjectGuid>{7E9C2DFD-71A5-496D-AA4D-5EC53EAEB9AE}</ProjectGuid>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>Inventory.Domain</RootNamespace>
    <AssemblyName>Inventory.Domain</AssemblyName>
    <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <NuGetPackageImportStamp>
    </NuGetPackageImportStamp>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
    <DebugSymbols>true</DebugSymbols>
    <OutputPath>bin\x64\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <DebugType>full</DebugType>
    <PlatformTarget>x64</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
    <OutputPath>bin\x64\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <Optimize>true</Optimize>
    <DebugType>pdbonly</DebugType>
    <PlatformTarget>x64</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Microsoft.ServiceFabric.Actors, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Actors.2.6.204\lib\net45\Microsoft.ServiceFabric.Actors.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Data, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Data.2.6.204\lib\net45\Microsoft.ServiceFabric.Data.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Data.Interfaces, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Data.2.6.204\lib\net45\Microsoft.ServiceFabric.Data.Interfaces.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.FabricTransport, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.FabricTransport.Internal.2.6.204\lib\net45\Microsoft.ServiceFabric.FabricTransport.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Internal, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\Microsoft.ServiceFabric.Internal.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Internal.Strings, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\Microsoft.ServiceFabric.Internal.Strings.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Services, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Services.2.6.204\lib\net45\Microsoft.ServiceFabric.Services.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Services.Remoting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Services.Remoting.2.6.204\lib\net45\Microsoft.ServiceFabric.Services.Remoting.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Fabric, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="System.Fabric.Management.ServiceModel, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Management.ServiceModel.dll</HintPath>
    </Reference>
    <Reference Include="System.Fabric.Management.ServiceModel.XmlSerializers, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Management.ServiceModel.XmlSerializers.dll</HintPath>
    </Reference>
    <Reference Include="System.Fabric.Strings, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Strings.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="System.Runtime.Serialization" />
    <Reference Include="System.ServiceModel" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Data" />
    <Reference Include="System.Net.Http" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="IInventoryService.cs" />
    <Compile Include="InventoryItem.cs" />
    <Compile Include="InventoryItemId.cs" />
    <Compile Include="InventoryItemView.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\Common\Common.csproj">
      <Project>{9ec0063f-489e-43fe-94b5-bf5f89977cd3}</Project>
      <Name>Common</Name>
    </ProjectReference>
  </ItemGroup>
  <ItemGroup>
    <None Include="packages.config" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <Import Project="..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets" Condition="Exists('..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.ServiceFabric.Actors.2.6.204\build\Microsoft.ServiceFabric.Actors.targets'))" />
  </Target>
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>

================================================
FILE: ReferenceApp/Inventory.Domain/InventoryItem.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace Inventory.Domain
{
    using System;

    [Serializable]
    public sealed class InventoryItem
    {
        public InventoryItem(
            string description, decimal price, int availableStock, int restockThreshold, int maxStockThreshold, InventoryItemId id = null,
            bool onReorder = false)
        {
            this.Id = id ?? new InventoryItemId();
            this.Description = description;
            this.Price = price;
            this.AvailableStock = availableStock;
            this.RestockThreshold = restockThreshold;
            this.MaxStockThreshold = maxStockThreshold;
            this.OnReorder = onReorder;
        }

        /// <summary>
        /// Unique identifier for each item style
        /// </summary>
        public InventoryItemId Id { get; }

        /// <summary>
        /// Quantity in stock
        /// </summary>
        public int AvailableStock { get; private set; }

        /// <summary>
        /// Price
        /// </summary>
        public decimal Price { get; }

        /// <summary>
        /// Brief description of product for display on website
        /// </summary>
        public string Description { get; }

        /// <summary>
        /// Available stock at which we should reorder
        /// </summary>
        public int RestockThreshold { get; }

        /// <summary>
        /// Maximum number of units that can be in-stock at any time (due to physicial/logistical constraints in warehouses)
        /// </summary>
        public int MaxStockThreshold { get; }

        /// <summary>
        /// True if item is on reorder
        /// </summary>
        public bool OnReorder { get; set; }

        /// <summary>
        /// Returns an InventoryItemView object, which contains only external, customer-facing data about an item in inventory.
        /// </summary>
        /// <param name="item"></param>
        public static implicit operator InventoryItemView(InventoryItem item)
        {
            return new InventoryItemView
            {
                Id = item.Id,
                Price = item.Price,
                Description = item.Description,
                CustomerAvailableStock = item.AvailableStock - item.RestockThreshold //Business logic: constraint to reduce overordering.
            };
        }

        public override string ToString()
        {
            return string.Format(
                "Item {0}: {1} at a price of {2} with {3} available items at a restock threshold of {4} and with max stocking threshold of {5}.",
                this.Id,
                this.Description,
                this.Price,
                this.AvailableStock.ToString(),
                this.RestockThreshold.ToString(),
                this.MaxStockThreshold.ToString());
        }

        /// <summary>
        /// Increments the quantity of a particular item in inventory.
        /// <param name="quantity"></param>
        /// <returns>int: Returns the quantity that has been added to stock</returns>
        /// </summary>
        public int AddStock(int quantity)
        {
            int original = this.AvailableStock;

            // The quantity that the client is trying to add to stock is greater than what can be physically accommodated in a Fabrikam Warehouse
            if ((this.AvailableStock + quantity) > this.MaxStockThreshold)
            {
                // For now, this method only adds new units up maximum stock threshold. In an expanded version of this application, we
                //could include tracking for the remaining units and store information about overstock elsewhere. 
                this.AvailableStock += (this.MaxStockThreshold - this.AvailableStock);
            }
            else
            {
                this.AvailableStock += quantity;
            }

            this.OnReorder = false;

            return this.AvailableStock - original;
        }

        /// <summary>
        /// Decrements the quantity of a particular item in inventory and ensures the restockThreshold hasn't
        /// been breached. If so, a RestockRequest is generated in CheckThreshold. 
        /// 
        /// If there is sufficient stock of an item, then the integer returned at the end of this call should be the same as quantityDesired. 
        /// In the event that there is not sufficient stock available, the method will remove whatever stock is available and return that quantity to the client.
        /// In this case, it is the responsibility of the client to determine if the amount that is returned is the same as quantityDesired.
        /// It is invalid to pass in a negative number. 
        /// </summary>
        /// <param name="quantityDesired"></param>
        /// <returns>int: Returns the number actually removed from stock. </returns>
        /// 
        public int RemoveStock(int quantityDesired)
        {
            int removed = Math.Min(quantityDesired, this.AvailableStock); //Assumes quantityDesired is a positive integer

            this.AvailableStock -= removed;

            return removed;
        }
    }
}

================================================
FILE: ReferenceApp/Inventory.Domain/InventoryItemId.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace Inventory.Domain
{
    using System;
    using System.Runtime.Serialization;
    using Common;
    using Microsoft.ServiceFabric.Services.Client;

    [DataContract]
    public class InventoryItemId : IFormattable, IComparable, IComparable<InventoryItemId>, IEquatable<InventoryItemId>
    {
        [DataMember] private Guid id;

        public InventoryItemId()
        {
            this.id = Guid.NewGuid();
        }

        public int CompareTo(object obj)
        {
            return this.id.CompareTo(((InventoryItemId) obj).id);
        }

        public int CompareTo(InventoryItemId other)
        {
            return this.id.CompareTo(other.id);
        }

        public bool Equals(InventoryItemId other)
        {
            return this.id.Equals(other.id);
        }

        public string ToString(string format, IFormatProvider formatProvider)
        {
            return this.id.ToString(format, formatProvider);
        }

        public ServicePartitionKey GetPartitionKey()
        {
            return new ServicePartitionKey(HashUtil.getLongHashCode(this.id.ToString()));
        }

        public static bool operator ==(InventoryItemId item1, InventoryItemId item2)
        {
            return item1.Equals(item2);
        }

        public static bool operator !=(InventoryItemId item1, InventoryItemId item2)
        {
            return !item1.Equals(item2);
        }

        public override bool Equals(object obj)
        {
            return (obj is InventoryItemId) ? this.id.Equals(((InventoryItemId) obj).id) : false;
        }

        public override int GetHashCode()
        {
            return this.id.GetHashCode();
        }

        public override string ToString()
        {
            return this.id.ToString();
        }

        public string ToString(string format)
        {
            return this.id.ToString(format);
        }
    }
}

================================================
FILE: ReferenceApp/Inventory.Domain/InventoryItemView.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace Inventory.Domain
{
    using System.Runtime.Serialization;

    //Guid will always be key to this value pair
    [DataContract]
    public sealed class InventoryItemView
    {
        [DataMember]
        public InventoryItemId Id { get; set; }

        [DataMember]
        public string Description { get; set; }

        [DataMember]
        public decimal Price { get; set; }

        [DataMember]
        public int CustomerAvailableStock { get; set; }
    }
}

================================================
FILE: ReferenceApp/Inventory.Domain/Properties/AssemblyInfo.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following 
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.

[assembly: AssemblyTitle("InventoryService.Domain")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("InventoryService.Domain")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible 
// to COM components.  If you need to access a type in this assembly from 
// COM, set the ComVisible attribute to true on that type.

[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM

[assembly: Guid("7e9c2dfd-71a5-496d-aa4d-5ec53eaeb9ae")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers 
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

================================================
FILE: ReferenceApp/Inventory.Domain/packages.config
================================================
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.ServiceFabric" version="5.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Actors" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Data" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.FabricTransport.Internal" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Services" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Services.Remoting" version="2.6.204" targetFramework="net452" />
</packages>

================================================
FILE: ReferenceApp/Inventory.Service/App.config
================================================
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Fabric" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.ServiceFabric.Services" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.ServiceFabric.Internal" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.ServiceFabric.Data" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Azure.KeyVault.Core" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>


================================================
FILE: ReferenceApp/Inventory.Service/AzureBackupStore.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace Inventory.Service
{
    using System;
    using System.Collections.Generic;
    using System.Fabric.Description;
    using System.IO;
    using System.IO.Compression;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.ServiceFabric.Data;
    using Microsoft.WindowsAzure.Storage.Auth;
    using Microsoft.WindowsAzure.Storage.Blob;

    public class AzureBlobBackupManager : IBackupStore
    {
        private readonly CloudBlobClient cloudBlobClient;
        private CloudBlobContainer backupBlobContainer;
        private int MaxBackupsToKeep;

        private string PartitionTempDirectory;
        private string partitionId;

        private long backupFrequencyInSeconds;
        private long keyMin;
        private long keyMax;

        public AzureBlobBackupManager(ConfigurationSection configSection, string partitionId, long keymin, long keymax, string codePackageTempDirectory)
        {
            this.keyMin = keymin;
            this.keyMax = keymax;

            string backupAccountName = configSection.Parameters["BackupAccountName"].Value;
            string backupAccountKey = configSection.Parameters["PrimaryKeyForBackupTestAccount"].Value;
            string blobEndpointAddress = configSection.Parameters["BlobServiceEndpointAddress"].Value;

            this.backupFrequencyInSeconds = long.Parse(configSection.Parameters["BackupFrequencyInSeconds"].Value);
            this.MaxBackupsToKeep = int.Parse(configSection.Parameters["MaxBackupsToKeep"].Value);
            this.partitionId = partitionId;
            this.PartitionTempDirectory = Path.Combine(codePackageTempDirectory, partitionId);

            StorageCredentials storageCredentials = new StorageCredentials(backupAccountName, backupAccountKey);
            this.cloudBlobClient = new CloudBlobClient(new Uri(blobEndpointAddress), storageCredentials);
            this.backupBlobContainer = this.cloudBlobClient.GetContainerReference(this.partitionId);
            this.backupBlobContainer.CreateIfNotExists();
        }

        long IBackupStore.backupFrequencyInSeconds
        {
            get { return this.backupFrequencyInSeconds; }
        }

        public async Task ArchiveBackupAsync(BackupInfo backupInfo, CancellationToken cancellationToken)
        {
            ServiceEventSource.Current.Message("AzureBlobBackupManager: Archive Called.");

            string fullArchiveDirectory = Path.Combine(this.PartitionTempDirectory, Guid.NewGuid().ToString("N"));

            DirectoryInfo fullArchiveDirectoryInfo = new DirectoryInfo(fullArchiveDirectory);
            fullArchiveDirectoryInfo.Create();

            string blobName = string.Format("{0}_{1}_{2}_{3}", Guid.NewGuid().ToString("N"), this.keyMin, this.keyMax, "Backup.zip");
            string fullArchivePath = Path.Combine(fullArchiveDirectory, "Backup.zip");

            ZipFile.CreateFromDirectory(backupInfo.Directory, fullArchivePath, CompressionLevel.Fastest, false);

            DirectoryInfo backupDirectory = new DirectoryInfo(backupInfo.Directory);
            backupDirectory.Delete(true);

            CloudBlockBlob blob = this.backupBlobContainer.GetBlockBlobReference(blobName);
            await blob.UploadFromFileAsync(fullArchivePath,  CancellationToken.None);

            DirectoryInfo tempDirectory = new DirectoryInfo(fullArchiveDirectory);
            tempDirectory.Delete(true);

            ServiceEventSource.Current.Message("AzureBlobBackupManager: UploadBackupFolderAsync: success.");
        }

        public async Task<string> RestoreLatestBackupToTempLocation(CancellationToken cancellationToken)
        {
            ServiceEventSource.Current.Message("AzureBlobBackupManager: Download backup async called.");

            CloudBlockBlob lastBackupBlob = (await this.GetBackupBlobs(true)).First();

            ServiceEventSource.Current.Message("AzureBlobBackupManager: Downloading {0}", lastBackupBlob.Name);

            string downloadId = Guid.NewGuid().ToString("N");

            string zipPath = Path.Combine(this.PartitionTempDirectory, string.Format("{0}_Backup.zip", downloadId));

            lastBackupBlob.DownloadToFile(zipPath, FileMode.CreateNew);

            string restorePath = Path.Combine(this.PartitionTempDirectory, downloadId);

            ZipFile.ExtractToDirectory(zipPath, restorePath);

            FileInfo zipInfo = new FileInfo(zipPath);
            zipInfo.Delete();

            ServiceEventSource.Current.Message("AzureBlobBackupManager: Downloaded {0} in to {1}", lastBackupBlob.Name, restorePath);

            return restorePath;
        }

        public async Task DeleteBackupsAsync(CancellationToken cancellationToken)
        {
            if (this.backupBlobContainer.Exists())
            {
                ServiceEventSource.Current.Message("AzureBlobBackupManager: Deleting old backups");

                IEnumerable<CloudBlockBlob> oldBackups = (await this.GetBackupBlobs(true)).Skip(this.MaxBackupsToKeep);

                foreach (CloudBlockBlob backup in oldBackups)
                {
                    ServiceEventSource.Current.Message("AzureBlobBackupManager: Deleting {0}", backup.Name);
                    await backup.DeleteAsync(cancellationToken);
                }
            }
        }

        private async Task<IEnumerable<CloudBlockBlob>> GetBackupBlobs(bool sorted)
        {
            IEnumerable<IListBlobItem> blobs = this.backupBlobContainer.ListBlobs();

            ServiceEventSource.Current.Message("AzureBlobBackupManager: Got {0} blobs", blobs.Count());

            List<CloudBlockBlob> itemizedBlobs = new List<CloudBlockBlob>();

            foreach (CloudBlockBlob cbb in blobs)
            {
                await cbb.FetchAttributesAsync();
                itemizedBlobs.Add(cbb);
            }

            if (sorted)
            {
                return itemizedBlobs.OrderByDescending(x => x.Properties.LastModified);
            }
            else
            {
                return itemizedBlobs;
            }
        }
    }
}

================================================
FILE: ReferenceApp/Inventory.Service/IBackupStore.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace Inventory.Service
{
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.ServiceFabric.Data;

    public interface IBackupStore
    {
        long backupFrequencyInSeconds { get; }

        Task ArchiveBackupAsync(BackupInfo backupInfo, CancellationToken cancellationToken);

        Task<string> RestoreLatestBackupToTempLocation(CancellationToken cancellationToken);

        Task DeleteBackupsAsync(CancellationToken cancellationToken);
    }
}

================================================
FILE: ReferenceApp/Inventory.Service/Inventory.Service.csproj
================================================
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">x64</Platform>
    <ProjectGuid>{714B1C61-FFA8-4A5E-8DD2-D0A290677293}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>Inventory.Service</RootNamespace>
    <AssemblyName>Inventory.Service</AssemblyName>
    <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <TargetFrameworkProfile />
    <NuGetPackageImportStamp>
    </NuGetPackageImportStamp>
    <IsServiceFabricServiceProject>True</IsServiceFabricServiceProject>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
    <PlatformTarget>x64</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
    <PlatformTarget>x64</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup>
    <AdditionalFileItemNames>$(AdditionalFileItemNames);None</AdditionalFileItemNames>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Microsoft.Azure.KeyVault.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Azure.KeyVault.Core.2.0.4\lib\net45\Microsoft.Azure.KeyVault.Core.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="Microsoft.Data.Edm, Version=5.8.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Data.Edm.5.8.2\lib\net40\Microsoft.Data.Edm.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="Microsoft.Data.OData, Version=5.8.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Data.OData.5.8.2\lib\net40\Microsoft.Data.OData.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="Microsoft.Data.Services.Client, Version=5.8.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Data.Services.Client.5.8.2\lib\net40\Microsoft.Data.Services.Client.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Data, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Data.2.6.204\lib\net45\Microsoft.ServiceFabric.Data.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Data.Interfaces, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Data.2.6.204\lib\net45\Microsoft.ServiceFabric.Data.Interfaces.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.FabricTransport, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.FabricTransport.Internal.2.6.204\lib\net45\Microsoft.ServiceFabric.FabricTransport.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Internal, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\Microsoft.ServiceFabric.Internal.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Internal.Strings, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\Microsoft.ServiceFabric.Internal.Strings.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Services, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Services.2.6.204\lib\net45\Microsoft.ServiceFabric.Services.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.ServiceFabric.Services.Remoting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.Services.Remoting.2.6.204\lib\net45\Microsoft.ServiceFabric.Services.Remoting.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.WindowsAzure.Storage, Version=8.1.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\WindowsAzure.Storage.8.1.1\lib\net45\Microsoft.WindowsAzure.Storage.dll</HintPath>
    </Reference>
    <Reference Include="Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
      <HintPath>..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.configuration" />
    <Reference Include="System.Core" />
    <Reference Include="System.Data" />
    <Reference Include="System.Fabric, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="System.Fabric.Management.ServiceModel, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Management.ServiceModel.dll</HintPath>
    </Reference>
    <Reference Include="System.Fabric.Management.ServiceModel.XmlSerializers, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Management.ServiceModel.XmlSerializers.dll</HintPath>
    </Reference>
    <Reference Include="System.Fabric.Strings, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=AMD64">
      <HintPath>..\packages\Microsoft.ServiceFabric.5.6.204\lib\net45\System.Fabric.Strings.dll</HintPath>
      <Private>True</Private>
    </Reference>
    <Reference Include="System.IO.Compression" />
    <Reference Include="System.IO.Compression.FileSystem" />
    <Reference Include="System.Runtime.Serialization" />
    <Reference Include="System.ServiceModel" />
    <Reference Include="System.Spatial, Version=5.8.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\System.Spatial.5.8.2\lib\net40\System.Spatial.dll</HintPath>
      <Private>True</Private>
    </Reference>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="LocalBackupStore.cs" />
    <Compile Include="AzureBackupStore.cs" />
    <Compile Include="IBackupStore.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
    <Compile Include="InventoryService.cs" />
    <Compile Include="Program.cs" />
    <Compile Include="ServiceEventSource.cs" />
    <Compile Include="StatefulServiceParameters.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Include="PackageRoot\Config\Settings.xml" />
    <None Include="PackageRoot\ServiceManifest.xml" />
    <None Include="App.config">
      <SubType>Designer</SubType>
    </None>
    <None Include="packages.config" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\Common\Common.csproj">
      <Project>{9ec0063f-489e-43fe-94b5-bf5f89977cd3}</Project>
      <Name>Common</Name>
    </ProjectReference>
    <ProjectReference Include="..\Inventory.Domain\Inventory.Domain.csproj">
      <Project>{7e9c2dfd-71a5-496d-aa4d-5ec53eaeb9ae}</Project>
      <Name>Inventory.Domain</Name>
    </ProjectReference>
    <ProjectReference Include="..\RestockRequest.Domain\RestockRequest.Domain.csproj">
      <Project>{a44fc2c5-6781-447e-80f5-7265b960b36a}</Project>
      <Name>RestockRequest.Domain</Name>
    </ProjectReference>
    <ProjectReference Include="..\RestockRequestManager.Domain\RestockRequestManager.Domain.csproj">
      <Project>{4162f266-d657-4143-aa62-626c10d23561}</Project>
      <Name>RestockRequestManager.Domain</Name>
    </ProjectReference>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>

================================================
FILE: ReferenceApp/Inventory.Service/InventoryService.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace Inventory.Service
{
    using System;
    using System.Collections.Generic;
    using System.Fabric;
    using System.Fabric.Description;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;
    using Common;
    using Inventory.Domain;
    using Microsoft.ServiceFabric.Data;
    using Microsoft.ServiceFabric.Data.Collections;
    using Microsoft.ServiceFabric.Services.Client;
    using Microsoft.ServiceFabric.Services.Communication.Runtime;
    using Microsoft.ServiceFabric.Services.Remoting.Client;
    using Microsoft.ServiceFabric.Services.Remoting.Runtime;
    using Microsoft.ServiceFabric.Services.Runtime;
    using RestockRequest.Domain;
    using RestockRequestManager.Domain;

    internal class InventoryService : StatefulService, IInventoryService
    {
        internal const string InventoryServiceType = "InventoryServiceType";
        private const string InventoryItemDictionaryName = "inventoryItems";
        private const string ActorMessageDictionaryName = "incomingMessages";
        private const string RestockRequestManagerServiceName = "RestockRequestManager";
        private const string RequestHistoryDictionaryName = "RequestHistory";
        private const string BackupCountDictionaryName = "BackupCountingDictionary";

        //private IReliableStateManager stateManager;
        private IBackupStore backupManager;

        //Set local or cloud backup, or none. Disabled is the default. Overridden by config.
        private BackupManagerType backupStorageType;


        /// <summary>
        /// This constructor is used in unit tests to inject a different state manager for unit testing.
        /// </summary>
        /// <param name="stateManager"></param>
        public InventoryService(StatefulServiceContext serviceContext) : this(serviceContext, (new ReliableStateManager(serviceContext)))
        {
        }

        public InventoryService(StatefulServiceContext context, IReliableStateManagerReplica stateManagerReplica) : base(context, stateManagerReplica)
        {
        }

        /// <summary>
        /// Used internally to generate inventory items and adds them to the ReliableDict we have.
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task<bool> CreateInventoryItemAsync(InventoryItem item)
        {
            IReliableDictionary<InventoryItemId, InventoryItem> inventoryItems =
                await this.StateManager.GetOrAddAsync<IReliableDictionary<InventoryItemId, InventoryItem>>(InventoryItemDictionaryName);

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                await inventoryItems.AddAsync(tx, item.Id, item);
                await tx.CommitAsync();
                ServiceEventSource.Current.ServiceMessage(this, "Created inventory item: {0}", item);
            }

            return true;
        }

        /// <summary>
        /// Tries to add the given quantity to the inventory item with the given ID without going over the maximum quantity allowed for an item.
        /// </summary>
        /// <param name="itemId"></param>
        /// <param name="quantity"></param>
        /// <returns>The quantity actually added to the item.</returns>
        public async Task<int> AddStockAsync(InventoryItemId itemId, int quantity)
        {
            IReliableDictionary<InventoryItemId, InventoryItem> inventoryItems =
                await this.StateManager.GetOrAddAsync<IReliableDictionary<InventoryItemId, InventoryItem>>(InventoryItemDictionaryName);

            int quantityAdded = 0;

            ServiceEventSource.Current.ServiceMessage(this, "Received add stock request. Item: {0}. Quantity: {1}.", itemId, quantity);

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                // Try to get the InventoryItem for the ID in the request.
                ConditionalValue<InventoryItem> item = await inventoryItems.TryGetValueAsync(tx, itemId);

                // We can only update the stock for InventoryItems in the system - we are not adding new items here.
                if (item.HasValue)
                {
                    // Update the stock quantity of the item.
                    // This only updates the copy of the Inventory Item that's in local memory here;
                    // It's not yet saved in the dictionary.
                    quantityAdded = item.Value.AddStock(quantity);

                    // We have to store the item back in the dictionary in order to actually save it.
                    // This will then replicate the updated item for
                    await inventoryItems.SetAsync(tx, item.Value.Id, item.Value);
                }

                // nothing will happen unless we commit the transaction!
                await tx.CommitAsync();

                ServiceEventSource.Current.ServiceMessage(
                    this,
                    "Add stock complete. Item: {0}. Added: {1}. Total: {2}",
                    item.Value.Id,
                    quantityAdded,
                    item.Value.AvailableStock);
            }


            return quantityAdded;
        }

        /// <summary>
        /// Removes the given quantity of stock from an in item in the inventory.
        /// </summary>
        /// <param name="request"></param>
        /// <returns>int: Returns the quantity removed from stock.</returns>
        public async Task<int> RemoveStockAsync(InventoryItemId itemId, int quantity, CustomerOrderActorMessageId amId)
        {
            ServiceEventSource.Current.ServiceMessage(this, "inside remove stock {0}|{1}", amId.GetHashCode(), amId.GetHashCode());

            IReliableDictionary<InventoryItemId, InventoryItem> inventoryItems =
                await this.StateManager.GetOrAddAsync<IReliableDictionary<InventoryItemId, InventoryItem>>(InventoryItemDictionaryName);

            IReliableDictionary<CustomerOrderActorMessageId, DateTime> recentRequests =
                await this.StateManager.GetOrAddAsync<IReliableDictionary<CustomerOrderActorMessageId, DateTime>>(ActorMessageDictionaryName);

            IReliableDictionary<CustomerOrderActorMessageId, Tuple<InventoryItemId, int>> requestHistory =
                await
                    this.StateManager.GetOrAddAsync<IReliableDictionary<CustomerOrderActorMessageId, Tuple<InventoryItemId, int>>>(RequestHistoryDictionaryName);

            int removed = 0;

            ServiceEventSource.Current.ServiceMessage(this, "Received remove stock request. Item: {0}. Quantity: {1}.", itemId, quantity);

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                //first let's see if this is a duplicate request
                ConditionalValue<DateTime> previousRequest = await recentRequests.TryGetValueAsync(tx, amId);
                if (!previousRequest.HasValue)
                {
                    //first time we've seen the request or it was a dupe from so long ago we have forgotten

                    // Try to get the InventoryItem for the ID in the request.
                    ConditionalValue<InventoryItem> item = await inventoryItems.TryGetValueAsync(tx, itemId);

                    // We can only remove stock for InventoryItems in the system.
                    if (item.HasValue)
                    {
                        // Update the stock quantity of the item.
                        // This only updates the copy of the Inventory Item that's in local memory here;
                        // It's not yet saved in the dictionary.
                        removed = item.Value.RemoveStock(quantity);

                        // We have to store the item back in the dictionary in order to actually save it.
                        // This will then replicate the updated item
                        await inventoryItems.SetAsync(tx, itemId, item.Value);

                        //we also have to make a note that we have returned this result, so that we can protect
                        //ourselves from stale or duplicate requests that come back later
                        await requestHistory.SetAsync(tx, amId, new Tuple<InventoryItemId, int>(itemId, removed));

                        ServiceEventSource.Current.ServiceMessage(
                            this,
                            "Removed stock complete. Item: {0}. Removed: {1}. Remaining: {2}",
                            item.Value.Id,
                            removed,
                            item.Value.AvailableStock);
                    }
                }
                else
                {
                    //this is a duplicate request. We need to send back the result we already came up with and hope they get it this time
                    //find the previous result and send it back
                    ConditionalValue<Tuple<InventoryItemId, int>> previousResponse = await requestHistory.TryGetValueAsync(tx, amId);

                    if (previousResponse.HasValue)
                    {
                        removed = previousResponse.Value.Item2;
                        ServiceEventSource.Current.ServiceMessage(
                            this,
                            "Retrieved previous response for request {0}, from {1}, for Item {2} and quantity {3}",
                            amId,
                            previousRequest.Value,
                            previousResponse.Value.Item1,
                            previousResponse.Value.Item2);
                    }
                    else
                    {
                        //we've seen the request before but we don't have a record for what we responded, inconsistent state
                        ServiceEventSource.Current.ServiceMessage(
                            this,
                            "Inconsistent State: recieved duplicate request {0} but don't have matching response in history",
                            amId);
                        this.Partition.ReportFault(System.Fabric.FaultType.Transient);
                    }


                    //note about duplicate Requests: technically if a duplicate request comes in and we have 
                    //sufficient invintory to return more now that we did previously, we could return more of the order and decrement 
                    //the difference to reduce the total number of round trips. This optimization is not currently implemented
                }


                //always update the datetime for the given request
                await recentRequests.SetAsync(tx, amId, DateTime.UtcNow);

                // nothing will happen unless we commit the transaction!
                ServiceEventSource.Current.Message("Committing Changes in Inventory Service");
                await tx.CommitAsync();
                ServiceEventSource.Current.Message("Inventory Service Changes Committed");
            }

            ServiceEventSource.Current.Message("Removed {0} of item {1}", removed, itemId);
            return removed;
        }

        public async Task<bool> IsItemInInventoryAsync(InventoryItemId itemId, CancellationToken ct)
        {
            ServiceEventSource.Current.Message("checking item {0} to see if it is in inventory", itemId);
            IReliableDictionary<InventoryItemId, InventoryItem> inventoryItems =
                await this.StateManager.GetOrAddAsync<IReliableDictionary<InventoryItemId, InventoryItem>>(InventoryItemDictionaryName);

            await this.PrintInventoryItemsAsync(inventoryItems, ct);

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                ConditionalValue<InventoryItem> item = await inventoryItems.TryGetValueAsync(tx, itemId);
                return item.HasValue;
            }
        }

        /// <summary>
        /// Retrieves a customer-specific view (defined in the InventoryItemView class in the Fabrikam Common namespace)
        /// of all items in the IReliableDictionary in InventoryService. Only items with a CustomerAvailableStock greater than
        /// zero are returned as a business logic constraint to reduce overordering. 
        /// </summary>
        /// <returns>IEnumerable of InventoryItemView</returns>
        public async Task<IEnumerable<InventoryItemView>> GetCustomerInventoryAsync(CancellationToken ct)
        {
            IReliableDictionary<InventoryItemId, InventoryItem> inventoryItems =
                await this.StateManager.GetOrAddAsync<IReliableDictionary<InventoryItemId, InventoryItem>>(InventoryItemDictionaryName);

            ServiceEventSource.Current.Message("Called GetCustomerInventory to return InventoryItemView");

            await this.PrintInventoryItemsAsync(inventoryItems, ct);

            IList<InventoryItemView> results = new List<InventoryItemView>();

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                ServiceEventSource.Current.Message("Generating item views for {0} items", await inventoryItems.GetCountAsync(tx));

                IAsyncEnumerator<KeyValuePair<InventoryItemId, InventoryItem>> enumerator =
                    (await inventoryItems.CreateEnumerableAsync(tx)).GetAsyncEnumerator();

                while (await enumerator.MoveNextAsync(ct))
                {
                    if (enumerator.Current.Value.AvailableStock > 0)
                    {
                        results.Add(enumerator.Current.Value);
                    }
                }
            }


            return results;
        }

        /// <summary>
        /// NOTE: This should not be used in published MVP code. 
        /// This function allows us to remove inventory items from inventory.
        /// </summary>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public async Task DeleteInventoryItemAsync(InventoryItemId itemId)
        {
            IReliableDictionary<InventoryItemId, InventoryItem> inventoryItems =
                await this.StateManager.GetOrAddAsync<IReliableDictionary<InventoryItemId, InventoryItem>>(InventoryItemDictionaryName);

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                await inventoryItems.TryRemoveAsync(tx, itemId);
                await tx.CommitAsync();
            }
        }

        /// <summary>
        /// Creates a new communication listener
        /// </summary>
        /// <returns></returns>
        protected override IEnumerable<ServiceReplicaListener> CreateServiceReplicaListeners()
        {
            return new[]
            {
                new ServiceReplicaListener(context => this.CreateServiceRemotingListener(context))
            };
        }

        //Dataloss testing can be triggered via powershell. To do so, run the following commands as a script
        //Connect-ServiceFabricCluster
        //$s = "fabric:/WebReferenceApplication/InventoryService"
        //$p = Get-ServiceFabricApplication | Get-ServiceFabricService -ServiceName $s | Get-ServiceFabricPartition | Select -First 1
        //$p | Invoke-ServiceFabricPartitionDataLoss -DataLossMode FullDataLoss -ServiceName $s

        protected override async Task<bool> OnDataLossAsync(RestoreContext restoreCtx, CancellationToken cancellationToken)
        {
            ServiceEventSource.Current.ServiceMessage(this, "OnDataLoss Invoked!");
            this.SetupBackupManager();

            try
            {
                string backupFolder;

                if (this.backupStorageType == BackupManagerType.None)
                {
                    //since we have no backup configured, we return false to indicate
                    //that state has not changed. This replica will become the basis
                    //for future replica builds
                    return false;
                }
                else
                {
                    backupFolder = await this.backupManager.RestoreLatestBackupToTempLocation(cancellationToken);
                }

                ServiceEventSource.Current.ServiceMessage(this, "Restoration Folder Path " + backupFolder);

                RestoreDescription restoreRescription = new RestoreDescription(backupFolder, RestorePolicy.Force);

                await restoreCtx.RestoreAsync(restoreRescription, cancellationToken);

                ServiceEventSource.Current.ServiceMessage(this, "Restore completed");

                DirectoryInfo tempRestoreDirectory = new DirectoryInfo(backupFolder);
                tempRestoreDirectory.Delete(true);

                return true;
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.ServiceMessage(this, "Restoration failed: " + "{0} {1}" + e.GetType() + e.Message);

                throw;
            }
        }


        protected override Task RunAsync(CancellationToken cancellationToken)
        {
            try
            {
                ServiceEventSource.Current.ServiceMessage(this, "inside RunAsync for Inventory Service");

                return Task.WhenAll(
                    this.PeriodicInventoryCheck(cancellationToken),
                    this.PeriodicOldMessageTrimming(cancellationToken),
                    this.PeriodicTakeBackupAsync(cancellationToken));
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.ServiceMessage(this, "RunAsync Failed, {0}", e);
                throw;
            }
        }


        private async Task<bool> BackupCallbackAsync(BackupInfo backupInfo, CancellationToken cancellationToken)
        {
            ServiceEventSource.Current.ServiceMessage(this, "Inside backup callback for replica {0}|{1}", this.Context.PartitionId, this.Context.ReplicaId);
            long totalBackupCount;

            IReliableDictionary<string, long> backupCountDictionary =
                await this.StateManager.GetOrAddAsync<IReliableDictionary<string, long>>(BackupCountDictionaryName);
            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                ConditionalValue<long> value = await backupCountDictionary.TryGetValueAsync(tx, "backupCount");

                if (!value.HasValue)
                {
                    totalBackupCount = 0;
                }
                else
                {
                    totalBackupCount = value.Value;
                }

                await backupCountDictionary.SetAsync(tx, "backupCount", ++totalBackupCount);

                await tx.CommitAsync();
            }

            ServiceEventSource.Current.Message("Backup count dictionary updated, total backup count is {0}", totalBackupCount);

            try
            {
                ServiceEventSource.Current.ServiceMessage(this, "Archiving backup");
                await this.backupManager.ArchiveBackupAsync(backupInfo, cancellationToken);
                ServiceEventSource.Current.ServiceMessage(this, "Backup archived");
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.ServiceMessage(this, "Archive of backup failed: Source: {0} Exception: {1}", backupInfo.Directory, e.Message);
            }

            await this.backupManager.DeleteBackupsAsync(cancellationToken);

            ServiceEventSource.Current.Message("Backups deleted");

            return true;
        }

        private async Task PrintInventoryItemsAsync(IReliableDictionary<InventoryItemId, InventoryItem> inventoryItems, CancellationToken cancellationToken)
        {
            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                ServiceEventSource.Current.Message("Printing Inventory for {0} items:", await inventoryItems.GetCountAsync(tx));

                IAsyncEnumerator<KeyValuePair<InventoryItemId, InventoryItem>> enumerator =
                    (await inventoryItems.CreateEnumerableAsync(tx)).GetAsyncEnumerator();

                while (await enumerator.MoveNextAsync(cancellationToken))
                {
                    ServiceEventSource.Current.Message("ID:{0}|Item:{1}", enumerator.Current.Key, enumerator.Current.Value);
                }
            }
        }

        private async Task PeriodicOldMessageTrimming(CancellationToken cancellationToken)
        {
            IReliableDictionary<CustomerOrderActorMessageId, DateTime> recentRequests =
                await this.StateManager.GetOrAddAsync<IReliableDictionary<CustomerOrderActorMessageId, DateTime>>(ActorMessageDictionaryName);

            IReliableDictionary<CustomerOrderActorMessageId, Tuple<InventoryItemId, int>> requestHistory =
                await
                    this.StateManager.GetOrAddAsync<IReliableDictionary<CustomerOrderActorMessageId, Tuple<InventoryItemId, int>>>(RequestHistoryDictionaryName);

            while (!cancellationToken.IsCancellationRequested)
            {
                using (ITransaction tx = this.StateManager.CreateTransaction())
                {
                    IAsyncEnumerator<KeyValuePair<CustomerOrderActorMessageId, DateTime>> enumerator =
                        (await recentRequests.CreateEnumerableAsync(tx)).GetAsyncEnumerator();

                    while (await enumerator.MoveNextAsync(cancellationToken))
                    {
                        //if we have a record of a message that is older than 2 hours from current time, then remove that record
                        //from both of the stale message tracking dictionaries.
                        if (enumerator.Current.Value < (DateTime.UtcNow.AddHours(-2)))
                        {
                            await recentRequests.TryRemoveAsync(tx, enumerator.Current.Key);
                            await requestHistory.TryRemoveAsync(tx, enumerator.Current.Key);
                        }
                    }

                    await tx.CommitAsync();
                }

                //sleep for 5 minutes then scan again
                await Task.Delay(TimeSpan.FromMinutes(5), cancellationToken);
            }
        }

        private async Task PeriodicInventoryCheck(CancellationToken cancellationToken)
        {
            IReliableDictionary<InventoryItemId, InventoryItem> inventoryItems =
                await this.StateManager.GetOrAddAsync<IReliableDictionary<InventoryItemId, InventoryItem>>(InventoryItemDictionaryName);

            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();

                IList<InventoryItem> items = new List<InventoryItem>();

                using (ITransaction tx = this.StateManager.CreateTransaction())
                {
                    ServiceEventSource.Current.ServiceMessage(this, "Checking inventory stock for {0} items.", await inventoryItems.GetCountAsync(tx));

                    IAsyncEnumerator<KeyValuePair<InventoryItemId, InventoryItem>> enumerator =
                        (await inventoryItems.CreateEnumerableAsync(tx)).GetAsyncEnumerator();

                    while (await enumerator.MoveNextAsync(cancellationToken))
                    {
                        InventoryItem item = enumerator.Current.Value;

                        //Check if stock is below restockThreshold and if the item is not already on reorder
                        if ((item.AvailableStock <= item.RestockThreshold) && !item.OnReorder)
                        {
                            items.Add(enumerator.Current.Value);
                        }
                    }
                }

                foreach (InventoryItem item in items)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    try
                    {
                        ServiceUriBuilder builder = new ServiceUriBuilder(RestockRequestManagerServiceName);

                        IRestockRequestManager restockRequestManagerClient = ServiceProxy.Create<IRestockRequestManager>(
                            builder.ToUri(),
                            new ServicePartitionKey());

                        // we reduce the quantity passed in to RestockRequest to ensure we don't overorder   
                        RestockRequest newRequest = new RestockRequest(item.Id, (item.MaxStockThreshold - item.AvailableStock));

                        InventoryItem updatedItem = new InventoryItem(
                            item.Description,
                            item.Price,
                            item.AvailableStock,
                            item.RestockThreshold,
                            item.MaxStockThreshold,
                            item.Id,
                            true);

                        // TODO: this call needs to be idempotent in case we fail to update the InventoryItem after this completes.
                        await restockRequestManagerClient.AddRestockRequestAsync(newRequest);

                        // Write operations take an exclusive lock on an item, which means we can't do anything else with that item while the transaction is open.
                        // If something blocks before the transaction is committed, the open transaction on the item will prevent all operations on it, including reads.
                        // Once the transaction commits, the lock is released and other operations on the item can proceed.
                        // Operations on the transaction all have timeouts to prevent deadlocking an item, 
                        // but we should do as little work inside the transaction as possible that is not related to the transaction itself.
                        using (ITransaction tx = this.StateManager.CreateTransaction())
                        {
                            await inventoryItems.TryUpdateAsync(tx, item.Id, updatedItem, item);

                            await tx.CommitAsync();
                        }

                        ServiceEventSource.Current.ServiceMessage(
                            this,
                            "Restock order placed. Item ID: {0}. Quantity: {1}",
                            newRequest.ItemId,
                            newRequest.Quantity);
                    }
                    catch (Exception e)
                    {
                        ServiceEventSource.Current.ServiceMessage(this, "Failed to place restock order for item {0}. {1}", item.Id, e.ToString());
                    }
                }

                await Task.Delay(TimeSpan.FromSeconds(30), cancellationToken);
            }
        }

        private async Task PeriodicTakeBackupAsync(CancellationToken cancellationToken)
        {
            long backupsTaken = 0;
            this.SetupBackupManager();

            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();
                if (this.backupStorageType == BackupManagerType.None)
                {
                    break;
                }
                else
                {
                    await Task.Delay(TimeSpan.FromSeconds(this.backupManager.backupFrequencyInSeconds));


                    BackupDescription backupDescription = new BackupDescription(BackupOption.Full, this.BackupCallbackAsync);

                    await this.BackupAsync(backupDescription, TimeSpan.FromHours(1), cancellationToken);

                    backupsTaken++;

                    ServiceEventSource.Current.ServiceMessage(this, "Backup {0} taken", backupsTaken);
                }
            }
        }

        private void SetupBackupManager()
        {
            string partitionId = this.Context.PartitionId.ToString("N");
            long minKey = ((Int64RangePartitionInformation) this.Partition.PartitionInfo).LowKey;
            long maxKey = ((Int64RangePartitionInformation) this.Partition.PartitionInfo).HighKey;

            if (this.Context.CodePackageActivationContext != null)
            {
                ICodePackageActivationContext codePackageContext = this.Context.CodePackageActivationContext;
                ConfigurationPackage configPackage = codePackageContext.GetConfigurationPackageObject("Config");
                ConfigurationSection configSection = configPackage.Settings.Sections["Inventory.Service.Settings"];

                string backupSettingValue = configSection.Parameters["BackupMode"].Value;

                if (string.Equals(backupSettingValue, "none", StringComparison.InvariantCultureIgnoreCase))
                {
                    this.backupStorageType = BackupManagerType.None;
                }
                else if (string.Equals(backupSettingValue, "azure", StringComparison.InvariantCultureIgnoreCase))
                {
                    this.backupStorageType = BackupManagerType.Azure;

                    ConfigurationSection azureBackupConfigSection = configPackage.Settings.Sections["Inventory.Service.BackupSettings.Azure"];

                    this.backupManager = new AzureBlobBackupManager(azureBackupConfigSection, partitionId, minKey, maxKey, codePackageContext.TempDirectory);
                }
                else if (string.Equals(backupSettingValue, "local", StringComparison.InvariantCultureIgnoreCase))
                {
                    this.backupStorageType = BackupManagerType.Local;

                    ConfigurationSection localBackupConfigSection = configPackage.Settings.Sections["Inventory.Service.BackupSettings.Local"];

                    this.backupManager = new DiskBackupManager(localBackupConfigSection, partitionId, minKey, maxKey, codePackageContext.TempDirectory);
                }
                else
                {
                    throw new ArgumentException("Unknown backup type");
                }

                ServiceEventSource.Current.ServiceMessage(this, "Backup Manager Set Up");
            }
        }

        private enum BackupManagerType
        {
            Azure,
            Local,
            None
        };
    }
}


================================================
FILE: ReferenceApp/Inventory.Service/LocalBackupStore.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace Inventory.Service
{
    using System;
    using System.Collections.Generic;
    using System.Fabric.Description;
    using System.IO;
    using System.IO.Compression;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.ServiceFabric.Data;

    public class DiskBackupManager : IBackupStore
    {
        private string PartitionArchiveFolder;
        private string PartitionTempDirectory;
        private long backupFrequencyInSeconds;
        private int MaxBackupsToKeep;
        private long keyMin;
        private long keyMax;

        public DiskBackupManager(ConfigurationSection configSection, string partitionId, long keymin, long keymax, string codePackageTempDirectory)
        {
            this.keyMin = keymin;
            this.keyMax = keymax;

            string BackupArchivalPath = configSection.Parameters["BackupArchivalPath"].Value;
            this.backupFrequencyInSeconds = long.Parse(configSection.Parameters["BackupFrequencyInSeconds"].Value);
            this.MaxBackupsToKeep = int.Parse(configSection.Parameters["MaxBackupsToKeep"].Value);

            this.PartitionArchiveFolder = Path.Combine(BackupArchivalPath, "Backups", partitionId);
            this.PartitionTempDirectory = Path.Combine(codePackageTempDirectory, partitionId);

            ServiceEventSource.Current.Message(
                "DiskBackupManager constructed IntervalinSec:{0}, archivePath:{1}, tempPath:{2}, backupsToKeep:{3}",
                this.backupFrequencyInSeconds,
                this.PartitionArchiveFolder,
                this.PartitionTempDirectory,
                this.MaxBackupsToKeep);
        }

        long IBackupStore.backupFrequencyInSeconds
        {
            get { return this.backupFrequencyInSeconds; }
        }

        public Task ArchiveBackupAsync(BackupInfo backupInfo, CancellationToken cancellationToken)
        {
            string fullArchiveDirectory = Path.Combine(
                this.PartitionArchiveFolder,
                string.Format("{0}_{1}_{2}", Guid.NewGuid().ToString("N"), this.keyMin, this.keyMax));

            DirectoryInfo dirInfo = new DirectoryInfo(fullArchiveDirectory);
            dirInfo.Create();

            string fullArchivePath = Path.Combine(fullArchiveDirectory, "Backup.zip");

            ZipFile.CreateFromDirectory(backupInfo.Directory, fullArchivePath, CompressionLevel.Fastest, false);

            DirectoryInfo backupDirectory = new DirectoryInfo(backupInfo.Directory);
            backupDirectory.Delete(true);

            return Task.FromResult(true);
        }

        public Task<string> RestoreLatestBackupToTempLocation(CancellationToken cancellationToken)
        {
            ServiceEventSource.Current.Message("Restoring backup to temp source:{0} destination:{1}", this.PartitionArchiveFolder, this.PartitionTempDirectory);

            DirectoryInfo dirInfo = new DirectoryInfo(this.PartitionArchiveFolder);

            string backupZip = dirInfo.GetDirectories().OrderByDescending(x => x.LastWriteTime).First().FullName;

            string zipPath = Path.Combine(backupZip, "Backup.zip");

            ServiceEventSource.Current.Message("latest zip backup is {0}", zipPath);

            DirectoryInfo directoryInfo = new DirectoryInfo(this.PartitionTempDirectory);
            if (directoryInfo.Exists)
            {
                directoryInfo.Delete(true);
            }

            directoryInfo.Create();

            ZipFile.ExtractToDirectory(zipPath, this.PartitionTempDirectory);

            ServiceEventSource.Current.Message("Zip backup {0} extracted to {1}", zipPath, this.PartitionTempDirectory);

            return Task.FromResult<string>(this.PartitionTempDirectory);
        }

        public async Task DeleteBackupsAsync(CancellationToken cancellationToken)
        {
            await Task.Run(
                () =>
                {
                    ServiceEventSource.Current.Message("deleting old backups");

                    if (!Directory.Exists(this.PartitionArchiveFolder))
                    {
                        //Nothing to delete; Backups may not even have been created for the partition
                        return;
                    }

                    DirectoryInfo dirInfo = new DirectoryInfo(this.PartitionArchiveFolder);

                    IEnumerable<DirectoryInfo> oldBackups = dirInfo.GetDirectories().OrderByDescending(x => x.LastWriteTime).Skip(this.MaxBackupsToKeep);

                    foreach (DirectoryInfo oldBackup in oldBackups)
                    {
                        ServiceEventSource.Current.Message("Deleting old backup {0}", oldBackup.FullName);
                        oldBackup.Delete(true);
                    }

                    ServiceEventSource.Current.Message("Old backups deleted");

                    return;
                },
                cancellationToken);
        }
    }
}

================================================
FILE: ReferenceApp/Inventory.Service/PackageRoot/Config/Settings.xml
================================================
<?xml version="1.0" encoding="utf-8" ?>
<Settings xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2011/01/fabric">
  <!-- This is used by the StateManager's replicator. -->
  <Section Name="ReplicatorConfig">
    <Parameter Name="ReplicatorEndpoint" Value="ReplicatorEndpoint" />
  </Section>
  <Section Name="Inventory.Service.Settings">
    <Parameter Name="BackupMode" Value="none" />
  </Section>
  <Section Name="Inventory.Service.BackupSettings.Azure">
    <Parameter Name="BackupAccountName" Value="" />
    <Parameter Name="PrimaryKeyForBackupTestAccount" Value="" />
    <Parameter Name="BlobServiceEndpointAddress" Value="" />
    <Parameter Name="BackupFrequencyInSeconds" Value="30" />
    <Parameter Name="MaxBackupsToKeep" Value="5" />
  </Section>
  <Section Name="Inventory.Service.BackupSettings.Local">
    <Parameter Name="BackupArchivalPath" Value="C:\temp" />
    <Parameter Name="BackupFrequencyInSeconds" Value="10" />
    <Parameter Name="MaxBackupsToKeep" Value="5" />
  </Section>

</Settings>


================================================
FILE: ReferenceApp/Inventory.Service/PackageRoot/ServiceManifest.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<ServiceManifest Name="Inventory.ServicePkg"
                 Version="1.0.0"
                 xmlns="http://schemas.microsoft.com/2011/01/fabric"
                 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ServiceTypes>
    <!-- This is the name of your ServiceType. 
         This name must match the string used in RegisterServiceType call in Program.cs. -->
    <StatefulServiceType ServiceTypeName="InventoryServiceType" HasPersistedState="true" />
  </ServiceTypes>

  <!-- Code package is your service executable. -->
  <CodePackage Name="Code" Version="1.0.0">
    <EntryPoint>
      <ExeHost>
        <Program>Inventory.Service.exe</Program>
      </ExeHost>
    </EntryPoint>
  </CodePackage>

  <!-- Config package is the contents of the Config directoy under PackageRoot that contains an 
       independently-updateable and versioned set of custom configuration settings for your service. -->
  <ConfigPackage Name="Config" Version="1.0.0" />

  <Resources>
    <Endpoints>
      <!-- This endpoint is used by the communication listener to obtain the port on which to 
           listen. Please note that if your service is partitioned, this port is shared with 
           replicas of different partitions that are placed in your code. -->
      <Endpoint Name="ServiceEndpoint" />

      <!-- This endpoint is used by the replicator for replicating the state of your service.
           This endpoint is configured through a ReplicatorSettings config section in the Settings.xml
           file under the ConfigPackage. -->
      <Endpoint Name="ReplicatorEndpoint" />
    </Endpoints>
  </Resources>
</ServiceManifest>


================================================
FILE: ReferenceApp/Inventory.Service/Program.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace Inventory.Service
{
    using System;
    using System.Diagnostics;
    using System.Threading;
    using Microsoft.ServiceFabric.Services.Runtime;

    public class Program
    {
        public static void Main(string[] args)
        {
            try
            {
                ServiceRuntime.RegisterServiceAsync(InventoryService.InventoryServiceType, (context) => new InventoryService(context)).GetAwaiter().GetResult();

                ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(InventoryService).Name);

                Thread.Sleep(Timeout.Infinite);
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
                throw;
            }
        }
    }
}

================================================
FILE: ReferenceApp/Inventory.Service/Properties/AssemblyInfo.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following 
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.

[assembly: AssemblyTitle("InventoryService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("InventoryService")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible 
// to COM components.  If you need to access a type in this assembly from 
// COM, set the ComVisible attribute to true on that type.

[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM

[assembly: Guid("714b1c61-ffa8-4a5e-8dd2-d0a290677293")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers 
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("Inventory.UnitTests")]

================================================
FILE: ReferenceApp/Inventory.Service/ServiceEventSource.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace Inventory.Service
{
    using System;
    using System.Diagnostics.Tracing;
    using System.Threading.Tasks;
    using Microsoft.ServiceFabric.Services.Runtime;

    [EventSource(Name = "MyCompany-Web_UIApplication-InventoryService")]
    internal sealed class ServiceEventSource : EventSource
    {
        private const int MessageEventId = 1;

        // For very high-frequency events it might be advantageous to raise events using WriteEventCore API.
        // This results in more efficient parameter handling, but requires explicit allocation of EventData structure and unsafe code.
        // To enable this code path, define UNSAFE conditional compilation symbol and turn on unsafe code support in project properties.
        private const int ServiceMessageEventId = 2;

        private const int ServiceTypeRegisteredEventId = 3;

        private const int ServiceHostInitializationFailedEventId = 4;

        // A pair of events sharing the same name prefix with a "Start"/"Stop" suffix implicitly marks boundaries of an event tracing activity.
        // These activities can be automatically picked up by debugging and profiling tools, which can compute their execution time, child activities,
        // and other statistics.
        private const int ServiceRequestStartEventId = 5;

        private const int ServiceRequestStopEventId = 6;

        private const int ServiceRequestFailedEventId = 7;
        public static readonly ServiceEventSource Current = new ServiceEventSource();

        static ServiceEventSource()
        {
            // A workaround for the problem where ETW activities do not get tracked until Tasks infrastructure is initialized.
            // This problem will be fixed in .NET Framework 4.6.2.
            Task.Run(() => { }).Wait();
        }

        // Instance constructor is private to enforce singleton semantics
        private ServiceEventSource() : base()
        {
        }

        // Define an instance method for each event you want to record and apply an [Event] attribute to it.
        // The method name is the name of the event.
        // Pass any parameters you want to record with the event (only primitive integer types, DateTime, Guid & string are allowed).
        // Each event method implementation should check whether the event source is enabled, and if it is, call WriteEvent() method to raise the event.
        // The number and types of arguments passed to every event method must exactly match what is passed to WriteEvent().
        // Put [NonEvent] attribute on all methods that do not define an event.
        // For more information see https://msdn.microsoft.com/en-us/library/system.diagnostics.tracing.eventsource.aspx

        [NonEvent]
        public void Message(string message, params object[] args)
        {
            if (this.IsEnabled())
            {
                string finalMessage = string.Format(message, args);
                this.Message(finalMessage);
            }
        }

        [Event(MessageEventId, Level = EventLevel.Informational, Message = "{0}")]
        public void Message(string message)
        {
            if (this.IsEnabled())
            {
                this.WriteEvent(MessageEventId, message);
            }
        }

        [NonEvent]
        public void ServiceMessage(StatefulService service, string message, params object[] args)
        {
            if (this.IsEnabled())
            {
                string finalMessage = string.Format(message, args);
                this.ServiceMessage(
                    service.Context.ServiceName.ToString(),
                    service.Context.ServiceTypeName,
                    service.Context.ReplicaId,
                    service.Context.PartitionId,
                    service.Context.CodePackageActivationContext.ApplicationName,
                    service.Context.CodePackageActivationContext.ApplicationTypeName,
                    service.Context.NodeContext.NodeName,
                    finalMessage);
            }
        }

        [Event(ServiceTypeRegisteredEventId, Level = EventLevel.Informational, Message = "Service host process {0} registered service type {1}",
            Keywords = Keywords.ServiceInitialization)]
        public void ServiceTypeRegistered(int hostProcessId, string serviceType)
        {
            this.WriteEvent(ServiceTypeRegisteredEventId, hostProcessId, serviceType);
        }

        [Event(ServiceHostInitializationFailedEventId, Level = EventLevel.Error, Message = "Service host initialization failed",
            Keywords = Keywords.ServiceInitialization)]
        public void ServiceHostInitializationFailed(string exception)
        {
            this.WriteEvent(ServiceHostInitializationFailedEventId, exception);
        }

        [Event(ServiceRequestStartEventId, Level = EventLevel.Informational, Message = "Service request '{0}' started", Keywords = Keywords.Requests)]
        public void ServiceRequestStart(string requestTypeName)
        {
            this.WriteEvent(ServiceRequestStartEventId, requestTypeName);
        }

        [Event(ServiceRequestStopEventId, Level = EventLevel.Informational, Message = "Service request '{0}' finished", Keywords = Keywords.Requests)]
        public void ServiceRequestStop(string requestTypeName)
        {
            this.WriteEvent(ServiceRequestStopEventId, requestTypeName);
        }

        [Event(ServiceRequestFailedEventId, Level = EventLevel.Error, Message = "Service request '{0}' failed", Keywords = Keywords.Requests)]
        public void ServiceRequestFailed(string requestTypeName, string exception)
        {
            this.WriteEvent(ServiceRequestFailedEventId, exception);
        }

        [Event(ServiceMessageEventId, Level = EventLevel.Informational, Message = "{7}")]
        private void ServiceMessage(
            string serviceName,
            string serviceTypeName,
            long replicaOrInstanceId,
            Guid partitionId,
            string applicationName,
            string applicationTypeName,
            string nodeName,
            string message)
        {
            this.WriteEvent(
                ServiceMessageEventId,
                serviceName,
                serviceTypeName,
                replicaOrInstanceId,
                partitionId,
                applicationName,
                applicationTypeName,
                nodeName,
                message);
        }

        // Event keywords can be used to categorize events. 
        // Each keyword is a bit flag. A single event can be associated with multiple keywords (via EventAttribute.Keywords property).
        // Keywords must be defined as a public class named 'Keywords' inside EventSource that uses them.
        public static class Keywords
        {
            public const EventKeywords Requests = (EventKeywords) 0x1L;
            public const EventKeywords ServiceInitialization = (EventKeywords) 0x2L;
        }
    }
}

================================================
FILE: ReferenceApp/Inventory.Service/StatefulServiceParameters.cs
================================================
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace Inventory.Service
{
    using System;
    using System.Fabric;

    internal class StatefulServiceParameters
    {
        public StatefulServiceParameters(
            CodePackageActivationContext codePackageActivationContext, byte[] initializationData, Guid partitionId, Uri serviceName, string serviceTypeName,
            long replicaId)
        {
            this.CodePackageActivationContext = codePackageActivationContext;
            this.InitializationData = initializationData;
            this.PartitionId = partitionId;
            this.ServiceName = serviceName;
            this.ServiceTypeName = serviceTypeName;
            this.ReplicaId = replicaId;
        }

        public CodePackageActivationContext CodePackageActivationContext { get; }

        public byte[] InitializationData { get; }

        public Guid PartitionId { get; }

        public long ReplicaId { get; }

        public Uri ServiceName { get; }

        public string ServiceTypeName { get; }
    }
}

================================================
FILE: ReferenceApp/Inventory.Service/packages.config
================================================
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.Azure.KeyVault.Core" version="2.0.4" targetFramework="net452" />
  <package id="Microsoft.Data.Edm" version="5.8.2" targetFramework="net452" />
  <package id="Microsoft.Data.OData" version="5.8.2" targetFramework="net452" />
  <package id="Microsoft.Data.Services.Client" version="5.8.2" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric" version="5.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Data" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.FabricTransport.Internal" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Services" version="2.6.204" targetFramework="net452" />
  <package id="Microsoft.ServiceFabric.Services.Remoting" version="2.6.204" targetFramework="net452" />
  <package id="Newtonsoft.Json" version="10.0.2" targetFramework="net452" />
  <package id="System.ComponentModel.EventBasedAsync" version="4.3.0" targetFramework="net452" />
  <package id="System.Dynamic.Runtime" version="4.3.0" targetFramework="net452" />
  <package id="System.Linq.Queryable" version="4.3.0" targetFramework="net452" />
  <package id="System.Net.Requests" version="4.3.0" targetFramework="net452" />
  <package id="System.Spatial" version="5.8.2" targetFramework="net452" />
  <package id="WindowsAzure.Storage" version="8.1.1" targetFramework="net452" />
</packages>

================================================
FILE: ReferenceApp/Inventory.UnitTests/Inventory.UnitTests.csproj
================================================
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{71E58E09-BEE4-4B19-BCF7-4C9BD71514FB}</ProjectGuid>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>Inventory.UnitTests</RootNamespace>
    <AssemblyName>Inventory.UnitTests</AssemblyName>
    <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
    <ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
    <IsCodedUITest>False</IsCodedUITest>
    <TestProjectType>UnitTest</TestProjectType>
    <NuGetPackageImportStamp>
    </NuGetPackageImportStamp>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
    <DebugSymbols>true</DebugSymbols>
    <OutputPath>bin\x64\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <DebugType>full</DebugType>
    <PlatformTarget>x64</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
    <OutputPath>bin\x64\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <Optimize>true</Optimize>
    <DebugType>pdbonly</DebugType>
    <PlatformTarget>x64</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <ItemGroup>
    <Reference Inc
Download .txt
gitextract_lulu55kd/

├── .gitignore
├── CONTRIBUTING.md
├── Docs/
│   └── architecture.md
├── LICENSE
├── README.md
└── ReferenceApp/
    ├── Common/
    │   ├── ActorMessageId.cs
    │   ├── Common.csproj
    │   ├── HashUtil.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── ServiceUriBuilder.cs
    │   └── packages.config
    ├── CustomerOrder.Actor/
    │   ├── ActorEventSource.cs
    │   ├── App.config
    │   ├── CustomerOrder.Actor.csproj
    │   ├── CustomerOrderActor.cs
    │   ├── CustomerOrderReminderNames.cs
    │   ├── PackageRoot/
    │   │   ├── Config/
    │   │   │   └── Settings.xml
    │   │   └── ServiceManifest.xml
    │   ├── Program.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   └── packages.config
    ├── CustomerOrder.Domain/
    │   ├── CustomerOrder.Domain.csproj
    │   ├── CustomerOrderItem.cs
    │   ├── CustomerOrderStatus.cs
    │   ├── ICustomerOrderActor.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── app.config
    │   └── packages.config
    ├── CustomerOrder.UnitTests/
    │   ├── CustomerOrder.UnitTests.csproj
    │   ├── CustomerOrderActorTests.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── app.config
    │   └── packages.config
    ├── Inventory.Domain/
    │   ├── IInventoryService.cs
    │   ├── Inventory.Domain.csproj
    │   ├── InventoryItem.cs
    │   ├── InventoryItemId.cs
    │   ├── InventoryItemView.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   └── packages.config
    ├── Inventory.Service/
    │   ├── App.config
    │   ├── AzureBackupStore.cs
    │   ├── IBackupStore.cs
    │   ├── Inventory.Service.csproj
    │   ├── InventoryService.cs
    │   ├── LocalBackupStore.cs
    │   ├── PackageRoot/
    │   │   ├── Config/
    │   │   │   └── Settings.xml
    │   │   └── ServiceManifest.xml
    │   ├── Program.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── ServiceEventSource.cs
    │   ├── StatefulServiceParameters.cs
    │   └── packages.config
    ├── Inventory.UnitTests/
    │   ├── Inventory.UnitTests.csproj
    │   ├── InventoryServiceTests.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── app.config
    │   └── packages.config
    ├── Mocks/
    │   ├── MockActorStateManager.cs
    │   ├── MockAsyncEnumerable.cs
    │   ├── MockCodePackageActivationContext.cs
    │   ├── MockInventoryService.cs
    │   ├── MockReliableDictionary.cs
    │   ├── MockReliableQueue.cs
    │   ├── MockReliableStateManager.cs
    │   ├── MockServiceProxy.cs
    │   ├── MockServiceProxyFactory.cs
    │   ├── MockTransaction.cs
    │   ├── Mocks.csproj
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── app.config
    │   └── packages.config
    ├── Nuget.Config
    ├── RestockRequest.Actor/
    │   ├── ActorEventSource.cs
    │   ├── App.config
    │   ├── PackageRoot/
    │   │   ├── Config/
    │   │   │   └── Settings.xml
    │   │   └── ServiceManifest.xml
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── RestockRequest.Actor.csproj
    │   ├── RestockRequestActor.cs
    │   ├── RestockRequestActorState.cs
    │   ├── RestockRequestReminderNames.cs
    │   ├── ServiceHost.cs
    │   └── packages.config
    ├── RestockRequest.Domain/
    │   ├── IRestockRequestActor.cs
    │   ├── IRestockRequestEvents.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── RestockRequest.Domain.csproj
    │   ├── RestockRequest.cs
    │   ├── RestockRequestStatus.cs
    │   ├── app.config
    │   └── packages.config
    ├── RestockRequestManager.Domain/
    │   ├── IRestockRequestManager.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── RestockRequestManager.Domain.csproj
    │   ├── app.config
    │   └── packages.config
    ├── RestockRequestManager.Service/
    │   ├── App.config
    │   ├── PackageRoot/
    │   │   ├── Config/
    │   │   │   └── Settings.xml
    │   │   └── ServiceManifest.xml
    │   ├── Program.cs
    │   ├── Properties/
    │   │   └── AssemblyInfo.cs
    │   ├── RestockRequestManager.Service.csproj
    │   ├── RestockRequestManagerService.cs
    │   ├── ServiceEventSource.cs
    │   └── packages.config
    ├── Web.Service/
    │   ├── .bowerrc
    │   ├── App.config
    │   ├── Controllers/
    │   │   ├── HomeController.cs
    │   │   ├── InventoryController.cs
    │   │   ├── OrdersController.cs
    │   │   └── StoreController.cs
    │   ├── PackageRoot/
    │   │   ├── Config/
    │   │   │   └── Settings.xml
    │   │   └── ServiceManifest.xml
    │   ├── Program.cs
    │   ├── Properties/
    │   │   └── launchSettings.json
    │   ├── ServiceEventSource.cs
    │   ├── Startup.cs
    │   ├── Views/
    │   │   ├── Home/
    │   │   │   ├── Admin.cshtml
    │   │   │   ├── Index.cshtml
    │   │   │   └── OrderConfirmation.cshtml
    │   │   ├── Shared/
    │   │   │   ├── Error.cshtml
    │   │   │   ├── _Layout.cshtml
    │   │   │   └── _ValidationScriptsPartial.cshtml
    │   │   ├── _ViewImports.cshtml
    │   │   └── _ViewStart.cshtml
    │   ├── Web.Service.csproj
    │   ├── WebService.cs
    │   ├── appsettings.Development.json
    │   ├── appsettings.json
    │   ├── bower.json
    │   ├── bundleconfig.json
    │   └── wwwroot/
    │       ├── css/
    │       │   └── site.css
    │       └── js/
    │           └── angular-index.js
    ├── WebReferenceApp.sln
    └── WebReferenceApplication/
        ├── ApplicationPackageRoot/
        │   └── ApplicationManifest.xml
        ├── ApplicationParameters/
        │   ├── Cloud.xml
        │   ├── Local.1Node.xml
        │   └── Local.5Node.xml
        ├── PublishProfiles/
        │   ├── Cloud.xml
        │   ├── Local.1Node.xml
        │   └── Local.5Node.xml
        ├── Scripts/
        │   └── Deploy-FabricApplication.ps1
        ├── WebReferenceApplication.sfproj
        ├── app.config
        └── packages.config
Download .txt
SYMBOL INDEX (367 symbols across 54 files)

FILE: ReferenceApp/Common/ActorMessageId.cs
  class CustomerOrderActorMessageId (line 12) | [DataContract]
    method CustomerOrderActorMessageId (line 15) | public CustomerOrderActorMessageId(ActorId sendingActorId, long messag...
    method CompareTo (line 27) | int IComparable.CompareTo(object obj)
    method CompareTo (line 32) | public int CompareTo(CustomerOrderActorMessageId other)
    method Equals (line 54) | public bool Equals(CustomerOrderActorMessageId other)
    method ToString (line 59) | public string ToString(string format, IFormatProvider formatProvider)
    method GetRandom (line 64) | public static CustomerOrderActorMessageId GetRandom()
    method Equals (line 93) | public override bool Equals(object obj)
    method GetHashCode (line 98) | public override int GetHashCode()

FILE: ReferenceApp/Common/HashUtil.cs
  class HashUtil (line 12) | public class HashUtil
    method getLongHashCode (line 14) | public static long getLongHashCode(string stringInput)
    method getIntHashCode (line 22) | public static int getIntHashCode(string stringInput)

FILE: ReferenceApp/Common/ServiceUriBuilder.cs
  class ServiceUriBuilder (line 11) | public class ServiceUriBuilder
    method ServiceUriBuilder (line 13) | public ServiceUriBuilder(string serviceInstance)
    method ServiceUriBuilder (line 19) | public ServiceUriBuilder(ICodePackageActivationContext context, string...
    method ServiceUriBuilder (line 25) | public ServiceUriBuilder(ICodePackageActivationContext context, string...
    method ToUri (line 47) | public Uri ToUri()

FILE: ReferenceApp/CustomerOrder.Actor/ActorEventSource.cs
  class ActorEventSource (line 13) | [EventSource(Name = "MyCompany-Web_UIApplication-CustomerOrder")]
    method ActorEventSource (line 26) | static ActorEventSource()
    method ActorEventSource (line 34) | private ActorEventSource() : base()
    method Message (line 46) | [NonEvent]
    method Message (line 56) | [Event(MessageEventId, Level = EventLevel.Informational, Message = "{0...
    method ActorMessage (line 65) | [NonEvent]
    method ActorHostInitializationFailed (line 89) | [Event(ActorHostInitializationFailedEventId, Level = EventLevel.Error,...
    method ActorMessage (line 96) | [Event(ActorMessageEventId, Level = EventLevel.Informational, Message ...
    class Keywords (line 127) | public static class Keywords

FILE: ReferenceApp/CustomerOrder.Actor/CustomerOrderActor.cs
  class CustomerOrderActor (line 23) | internal class CustomerOrderActor : Actor, ICustomerOrderActor, IRemindable
    method CustomerOrderActor (line 33) | public CustomerOrderActor(ActorService actorService, ActorId actorId)
    method SubmitOrderAsync (line 44) | public async Task SubmitOrderAsync(IEnumerable<CustomerOrderItem> orde...
    method GetOrderStatusAsStringAsync (line 71) | public async Task<string> GetOrderStatusAsStringAsync()
    method ReceiveReminderAsync (line 76) | public async Task ReceiveReminderAsync(string reminderName, byte[] con...
    method OnActivateAsync (line 109) | protected override async Task OnActivateAsync()
    method InternalActivateAsync (line 133) | public async Task InternalActivateAsync(ICodePackageActivationContext ...
    method OnDeactivateAsync (line 144) | protected override Task OnDeactivateAsync()
    method FulfillOrderAsync (line 165) | internal async Task FulfillOrderAsync()
    method GetOrderStatusAsync (line 238) | private async Task<CustomerOrderStatus> GetOrderStatusAsync()
    method SetOrderStatusAsync (line 251) | private async Task SetOrderStatusAsync(CustomerOrderStatus orderStatus)

FILE: ReferenceApp/CustomerOrder.Actor/CustomerOrderReminderNames.cs
  class CustomerOrderReminderNames (line 8) | internal static class CustomerOrderReminderNames

FILE: ReferenceApp/CustomerOrder.Actor/Program.cs
  class Program (line 12) | public class Program
    method Main (line 14) | public static void Main(string[] args)

FILE: ReferenceApp/CustomerOrder.Domain/CustomerOrderItem.cs
  class CustomerOrderItem (line 12) | [DataContract]
    method CustomerOrderItem (line 15) | public CustomerOrderItem(InventoryItemId itemId, int quantity)
    method ToString (line 31) | public override string ToString()

FILE: ReferenceApp/CustomerOrder.Domain/CustomerOrderStatus.cs
  type CustomerOrderStatus (line 8) | public enum CustomerOrderStatus

FILE: ReferenceApp/CustomerOrder.Domain/ICustomerOrderActor.cs
  type ICustomerOrderActor (line 12) | public interface ICustomerOrderActor : IActor
    method GetOrderStatusAsStringAsync (line 14) | Task<string> GetOrderStatusAsStringAsync();
    method SubmitOrderAsync (line 16) | Task SubmitOrderAsync(IEnumerable<CustomerOrderItem> orderList);

FILE: ReferenceApp/CustomerOrder.UnitTests/CustomerOrderActorTests.cs
  class CustomerOrderActorTests (line 22) | [TestClass]
    method TestFulfillOrderSimple (line 56) | [TestMethod]
    method TestFulfillOrderWithBackorder (line 84) | [TestMethod]
    method TestFulfillOrderToCompletion (line 119) | [TestMethod]
    method TestFulfillOrderCancelled (line 156) | [TestMethod]
    method CreateCustomerOrderActor (line 190) | private static async Task<CustomerOrderActor> CreateCustomerOrderActor...

FILE: ReferenceApp/Inventory.Domain/IInventoryService.cs
  type IInventoryService (line 14) | public interface IInventoryService : IService
    method AddStockAsync (line 16) | Task<int> AddStockAsync(InventoryItemId itemId, int quantity);
    method RemoveStockAsync (line 17) | Task<int> RemoveStockAsync(InventoryItemId itemId, int quantity, Custo...
    method IsItemInInventoryAsync (line 18) | Task<bool> IsItemInInventoryAsync(InventoryItemId itemId, Cancellation...
    method GetCustomerInventoryAsync (line 19) | Task<IEnumerable<InventoryItemView>> GetCustomerInventoryAsync(Cancell...
    method CreateInventoryItemAsync (line 20) | Task<bool> CreateInventoryItemAsync(InventoryItem item);

FILE: ReferenceApp/Inventory.Domain/InventoryItem.cs
  class InventoryItem (line 10) | [Serializable]
    method InventoryItem (line 13) | public InventoryItem(
    method ToString (line 76) | public override string ToString()
    method AddStock (line 93) | public int AddStock(int quantity)
    method RemoveStock (line 126) | public int RemoveStock(int quantityDesired)

FILE: ReferenceApp/Inventory.Domain/InventoryItemId.cs
  class InventoryItemId (line 13) | [DataContract]
    method InventoryItemId (line 18) | public InventoryItemId()
    method CompareTo (line 23) | public int CompareTo(object obj)
    method CompareTo (line 28) | public int CompareTo(InventoryItemId other)
    method Equals (line 33) | public bool Equals(InventoryItemId other)
    method ToString (line 38) | public string ToString(string format, IFormatProvider formatProvider)
    method GetPartitionKey (line 43) | public ServicePartitionKey GetPartitionKey()
    method Equals (line 58) | public override bool Equals(object obj)
    method GetHashCode (line 63) | public override int GetHashCode()
    method ToString (line 68) | public override string ToString()
    method ToString (line 73) | public string ToString(string format)

FILE: ReferenceApp/Inventory.Domain/InventoryItemView.cs
  class InventoryItemView (line 11) | [DataContract]

FILE: ReferenceApp/Inventory.Service/AzureBackupStore.cs
  class AzureBlobBackupManager (line 20) | public class AzureBlobBackupManager : IBackupStore
    method AzureBlobBackupManager (line 33) | public AzureBlobBackupManager(ConfigurationSection configSection, stri...
    method ArchiveBackupAsync (line 58) | public async Task ArchiveBackupAsync(BackupInfo backupInfo, Cancellati...
    method RestoreLatestBackupToTempLocation (line 84) | public async Task<string> RestoreLatestBackupToTempLocation(Cancellati...
    method DeleteBackupsAsync (line 110) | public async Task DeleteBackupsAsync(CancellationToken cancellationToken)
    method GetBackupBlobs (line 126) | private async Task<IEnumerable<CloudBlockBlob>> GetBackupBlobs(bool so...

FILE: ReferenceApp/Inventory.Service/IBackupStore.cs
  type IBackupStore (line 12) | public interface IBackupStore
    method ArchiveBackupAsync (line 16) | Task ArchiveBackupAsync(BackupInfo backupInfo, CancellationToken cance...
    method RestoreLatestBackupToTempLocation (line 18) | Task<string> RestoreLatestBackupToTempLocation(CancellationToken cance...
    method DeleteBackupsAsync (line 20) | Task DeleteBackupsAsync(CancellationToken cancellationToken);

FILE: ReferenceApp/Inventory.Service/InventoryService.cs
  class InventoryService (line 27) | internal class InventoryService : StatefulService, IInventoryService
    method InventoryService (line 47) | public InventoryService(StatefulServiceContext serviceContext) : this(...
    method InventoryService (line 51) | public InventoryService(StatefulServiceContext context, IReliableState...
    method CreateInventoryItemAsync (line 60) | public async Task<bool> CreateInventoryItemAsync(InventoryItem item)
    method AddStockAsync (line 81) | public async Task<int> AddStockAsync(InventoryItemId itemId, int quant...
    method RemoveStockAsync (line 128) | public async Task<int> RemoveStockAsync(InventoryItemId itemId, int qu...
    method IsItemInInventoryAsync (line 228) | public async Task<bool> IsItemInInventoryAsync(InventoryItemId itemId,...
    method GetCustomerInventoryAsync (line 249) | public async Task<IEnumerable<InventoryItemView>> GetCustomerInventory...
    method DeleteInventoryItemAsync (line 286) | public async Task DeleteInventoryItemAsync(InventoryItemId itemId)
    method CreateServiceReplicaListeners (line 302) | protected override IEnumerable<ServiceReplicaListener> CreateServiceRe...
    method OnDataLossAsync (line 316) | protected override async Task<bool> OnDataLossAsync(RestoreContext res...
    method RunAsync (line 359) | protected override Task RunAsync(CancellationToken cancellationToken)
    method BackupCallbackAsync (line 378) | private async Task<bool> BackupCallbackAsync(BackupInfo backupInfo, Ca...
    method PrintInventoryItemsAsync (line 423) | private async Task PrintInventoryItemsAsync(IReliableDictionary<Invent...
    method PeriodicOldMessageTrimming (line 439) | private async Task PeriodicOldMessageTrimming(CancellationToken cancel...
    method PeriodicInventoryCheck (line 474) | private async Task PeriodicInventoryCheck(CancellationToken cancellati...
    method PeriodicTakeBackupAsync (line 559) | private async Task PeriodicTakeBackupAsync(CancellationToken cancellat...
    method SetupBackupManager (line 587) | private void SetupBackupManager()
    type BackupManagerType (line 630) | private enum BackupManagerType

FILE: ReferenceApp/Inventory.Service/LocalBackupStore.cs
  class DiskBackupManager (line 18) | public class DiskBackupManager : IBackupStore
    method DiskBackupManager (line 27) | public DiskBackupManager(ConfigurationSection configSection, string pa...
    method ArchiveBackupAsync (line 52) | public Task ArchiveBackupAsync(BackupInfo backupInfo, CancellationToke...
    method RestoreLatestBackupToTempLocation (line 71) | public Task<string> RestoreLatestBackupToTempLocation(CancellationToke...
    method DeleteBackupsAsync (line 98) | public async Task DeleteBackupsAsync(CancellationToken cancellationToken)

FILE: ReferenceApp/Inventory.Service/Program.cs
  class Program (line 13) | public class Program
    method Main (line 15) | public static void Main(string[] args)

FILE: ReferenceApp/Inventory.Service/ServiceEventSource.cs
  class ServiceEventSource (line 13) | [EventSource(Name = "MyCompany-Web_UIApplication-InventoryService")]
    method ServiceEventSource (line 37) | static ServiceEventSource()
    method ServiceEventSource (line 45) | private ServiceEventSource() : base()
    method Message (line 57) | [NonEvent]
    method Message (line 67) | [Event(MessageEventId, Level = EventLevel.Informational, Message = "{0...
    method ServiceMessage (line 76) | [NonEvent]
    method ServiceTypeRegistered (line 94) | [Event(ServiceTypeRegisteredEventId, Level = EventLevel.Informational,...
    method ServiceHostInitializationFailed (line 101) | [Event(ServiceHostInitializationFailedEventId, Level = EventLevel.Erro...
    method ServiceRequestStart (line 108) | [Event(ServiceRequestStartEventId, Level = EventLevel.Informational, M...
    method ServiceRequestStop (line 114) | [Event(ServiceRequestStopEventId, Level = EventLevel.Informational, Me...
    method ServiceRequestFailed (line 120) | [Event(ServiceRequestFailedEventId, Level = EventLevel.Error, Message ...
    method ServiceMessage (line 126) | [Event(ServiceMessageEventId, Level = EventLevel.Informational, Messag...
    class Keywords (line 152) | public static class Keywords

FILE: ReferenceApp/Inventory.Service/StatefulServiceParameters.cs
  class StatefulServiceParameters (line 11) | internal class StatefulServiceParameters
    method StatefulServiceParameters (line 13) | public StatefulServiceParameters(

FILE: ReferenceApp/Inventory.UnitTests/InventoryServiceTests.cs
  class InventoryServiceTests (line 18) | [TestClass]
    method TestCreateAndIsItemInInventoryAsync (line 48) | [TestMethod]
    method TestAddStock (line 65) | [TestMethod]
    method TestRemoveStock (line 84) | [TestMethod]
    method TestRemoveStockWithDuplicateRequest (line 101) | [TestMethod]

FILE: ReferenceApp/Mocks/MockActorStateManager.cs
  class MockActorStateManager (line 19) | public class MockActorStateManager : IActorStateManager
    method AddOrUpdateStateAsync (line 23) | public Task<T> AddOrUpdateStateAsync<T>(string stateName, T addValue, ...
    method AddStateAsync (line 28) | public Task AddStateAsync<T>(string stateName, T value, CancellationTo...
    method ContainsStateAsync (line 33) | public Task<bool> ContainsStateAsync(string stateName, CancellationTok...
    method GetOrAddStateAsync (line 38) | public Task<T> GetOrAddStateAsync<T>(string stateName, T value, Cancel...
    method GetStateAsync (line 43) | public Task<T> GetStateAsync<T>(string stateName, CancellationToken ca...
    method GetStateNamesAsync (line 50) | public Task<IEnumerable<string>> GetStateNamesAsync(CancellationToken ...
    method RemoveStateAsync (line 55) | public Task RemoveStateAsync(string stateName, CancellationToken cance...
    method SetStateAsync (line 60) | public Task SetStateAsync<T>(string stateName, T value, CancellationTo...
    method TryAddStateAsync (line 66) | public Task<bool> TryAddStateAsync<T>(string stateName, T value, Cance...
    method TryGetStateAsync (line 71) | public Task<ConditionalValue<T>> TryGetStateAsync<T>(string stateName,...
    method TryRemoveStateAsync (line 78) | public Task<bool> TryRemoveStateAsync(string stateName, CancellationTo...
    method ClearCacheAsync (line 83) | public Task ClearCacheAsync(CancellationToken cancellationToken = defa...
    method SaveStateAsync (line 88) | public Task SaveStateAsync(CancellationToken cancellationToken = defau...

FILE: ReferenceApp/Mocks/MockAsyncEnumerable.cs
  class MockAsyncEnumerable (line 12) | internal class MockAsyncEnumerable<T> : IAsyncEnumerable<T>
    method MockAsyncEnumerable (line 16) | public MockAsyncEnumerable(IEnumerable<T> enumerable)
    method GetAsyncEnumerator (line 21) | public IAsyncEnumerator<T> GetAsyncEnumerator()
  class MockAsyncEnumerator (line 31) | internal class MockAsyncEnumerator<T> : IAsyncEnumerator<T>
    method MockAsyncEnumerator (line 35) | public MockAsyncEnumerator(IEnumerator<T> enumerator)
    method Dispose (line 49) | public void Dispose()
    method MoveNextAsync (line 54) | public Task<bool> MoveNextAsync(CancellationToken cancellationToken)
    method Reset (line 59) | public void Reset()

FILE: ReferenceApp/Mocks/MockCodePackageActivationContext.cs
  class MockCodePackageActivationContext (line 10) | public class MockCodePackageActivationContext : ICodePackageActivationCo...
    method GetApplicationPrincipals (line 42) | public ApplicationPrincipalsDescription GetApplicationPrincipals()
    method GetCodePackageNames (line 47) | public IList<string> GetCodePackageNames()
    method GetCodePackageObject (line 52) | public CodePackage GetCodePackageObject(string packageName)
    method GetConfigurationPackageNames (line 57) | public IList<string> GetConfigurationPackageNames()
    method GetConfigurationPackageObject (line 62) | public ConfigurationPackage GetConfigurationPackageObject(string packa...
    method GetDataPackageNames (line 67) | public IList<string> GetDataPackageNames()
    method GetDataPackageObject (line 72) | public DataPackage GetDataPackageObject(string packageName)
    method GetEndpoint (line 77) | public EndpointResourceDescription GetEndpoint(string endpointName)
    method GetEndpoints (line 82) | public KeyedCollection<string, EndpointResourceDescription> GetEndpoin...
    method GetServiceGroupTypes (line 87) | public KeyedCollection<string, ServiceGroupTypeDescription> GetService...
    method GetServiceManifestName (line 92) | public string GetServiceManifestName()
    method GetServiceManifestVersion (line 97) | public string GetServiceManifestVersion()
    method GetServiceTypes (line 102) | public KeyedCollection<string, ServiceTypeDescription> GetServiceTypes()
    method ReportApplicationHealth (line 107) | public void ReportApplicationHealth(HealthInformation healthInformation)
    method ReportDeployedServicePackageHealth (line 112) | public void ReportDeployedServicePackageHealth(HealthInformation healt...
    method ReportDeployedApplicationHealth (line 117) | public void ReportDeployedApplicationHealth(HealthInformation healthIn...
    method MockCodePackageActivationContext (line 124) | public MockCodePackageActivationContext(
    method Dispose (line 151) | protected virtual void Dispose(bool disposing)
    method Dispose (line 168) | public void Dispose()

FILE: ReferenceApp/Mocks/MockInventoryService.cs
  class MockInventoryService (line 15) | public class MockInventoryService : IInventoryService
    method MockInventoryService (line 17) | public MockInventoryService()
    method AddStockAsync (line 36) | public Task<int> AddStockAsync(InventoryItemId itemId, int quantity)
    method CreateInventoryItemAsync (line 41) | public Task<bool> CreateInventoryItemAsync(InventoryItem item)
    method GetCustomerInventoryAsync (line 46) | public Task<IEnumerable<InventoryItemView>> GetCustomerInventoryAsync()
    method GetCustomerInventoryAsync (line 51) | public Task<IEnumerable<InventoryItemView>> GetCustomerInventoryAsync(...
    method IsItemInInventoryAsync (line 56) | public Task<bool> IsItemInInventoryAsync(InventoryItemId itemId)
    method IsItemInInventoryAsync (line 61) | public Task<bool> IsItemInInventoryAsync(InventoryItemId itemId, Cance...
    method RemoveStockAsync (line 66) | public Task<int> RemoveStockAsync(InventoryItemId itemId, int quantity...

FILE: ReferenceApp/Mocks/MockReliableDictionary.cs
  class MockReliableDictionary (line 18) | public class MockReliableDictionary<TKey, TValue> : IReliableDictionary<...
    method AddAsync (line 35) | public Task AddAsync(ITransaction tx, TKey key, TValue value)
    method AddAsync (line 46) | public Task AddAsync(ITransaction tx, TKey key, TValue value, TimeSpan...
    method AddOrUpdateAsync (line 56) | public Task<TValue> AddOrUpdateAsync(ITransaction tx, TKey key, Func<T...
    method AddOrUpdateAsync (line 61) | public Task<TValue> AddOrUpdateAsync(ITransaction tx, TKey key, TValue...
    method AddOrUpdateAsync (line 66) | public Task<TValue> AddOrUpdateAsync(
    method AddOrUpdateAsync (line 73) | public Task<TValue> AddOrUpdateAsync(
    method ClearAsync (line 79) | public Task ClearAsync()
    method ClearAsync (line 86) | public Task ClearAsync(TimeSpan timeout, CancellationToken cancellatio...
    method ContainsKeyAsync (line 93) | public Task<bool> ContainsKeyAsync(ITransaction tx, TKey key)
    method ContainsKeyAsync (line 98) | public Task<bool> ContainsKeyAsync(ITransaction tx, TKey key, LockMode...
    method ContainsKeyAsync (line 103) | public Task<bool> ContainsKeyAsync(ITransaction tx, TKey key, TimeSpan...
    method ContainsKeyAsync (line 108) | public Task<bool> ContainsKeyAsync(ITransaction tx, TKey key, LockMode...
    method TryGetValueAsync (line 113) | public Task<ConditionalValue<TValue>> TryGetValueAsync(ITransaction tx...
    method TryGetValueAsync (line 121) | public Task<ConditionalValue<TValue>> TryGetValueAsync(ITransaction tx...
    method TryGetValueAsync (line 129) | public Task<ConditionalValue<TValue>> TryGetValueAsync(ITransaction tx...
    method TryGetValueAsync (line 137) | public Task<ConditionalValue<TValue>> TryGetValueAsync(
    method SetAsync (line 146) | public Task SetAsync(ITransaction tx, TKey key, TValue value)
    method SetAsync (line 153) | public Task SetAsync(ITransaction tx, TKey key, TValue value, TimeSpan...
    method GetOrAddAsync (line 160) | public Task<TValue> GetOrAddAsync(ITransaction tx, TKey key, Func<TKey...
    method GetOrAddAsync (line 165) | public Task<TValue> GetOrAddAsync(ITransaction tx, TKey key, TValue va...
    method GetOrAddAsync (line 170) | public Task<TValue> GetOrAddAsync(ITransaction tx, TKey key, Func<TKey...
    method GetOrAddAsync (line 175) | public Task<TValue> GetOrAddAsync(ITransaction tx, TKey key, TValue va...
    method TryAddAsync (line 180) | public Task<bool> TryAddAsync(ITransaction tx, TKey key, TValue value)
    method TryAddAsync (line 185) | public Task<bool> TryAddAsync(ITransaction tx, TKey key, TValue value,...
    method TryRemoveAsync (line 190) | public Task<ConditionalValue<TValue>> TryRemoveAsync(ITransaction tx, ...
    method TryRemoveAsync (line 196) | public Task<ConditionalValue<TValue>> TryRemoveAsync(ITransaction tx, ...
    method TryUpdateAsync (line 201) | public Task<bool> TryUpdateAsync(ITransaction tx, TKey key, TValue new...
    method TryUpdateAsync (line 206) | public Task<bool> TryUpdateAsync(
    method GetCountAsync (line 212) | public Task<long> GetCountAsync()
    method CreateEnumerableAsync (line 217) | public Task<IAsyncEnumerable<KeyValuePair<TKey, TValue>>> CreateEnumer...
    method CreateEnumerableAsync (line 222) | public Task<IAsyncEnumerable<KeyValuePair<TKey, TValue>>> CreateEnumer...
    method CreateEnumerableAsync (line 230) | public Task<IAsyncEnumerable<KeyValuePair<TKey, TValue>>> CreateEnumer...
    method GetCountAsync (line 238) | public Task<long> GetCountAsync(ITransaction tx)

FILE: ReferenceApp/Mocks/MockReliableQueue.cs
  class MockReliableQueue (line 15) | public class MockReliableQueue<T> : IReliableQueue<T>
    method EnqueueAsync (line 19) | public Task EnqueueAsync(ITransaction tx, T item, TimeSpan timeout, Ca...
    method EnqueueAsync (line 26) | public Task EnqueueAsync(ITransaction tx, T item)
    method TryDequeueAsync (line 33) | public Task<ConditionalValue<T>> TryDequeueAsync(ITransaction tx, Time...
    method TryDequeueAsync (line 41) | public Task<ConditionalValue<T>> TryDequeueAsync(ITransaction tx)
    method TryPeekAsync (line 49) | public Task<ConditionalValue<T>> TryPeekAsync(ITransaction tx, LockMod...
    method TryPeekAsync (line 57) | public Task<ConditionalValue<T>> TryPeekAsync(ITransaction tx, LockMod...
    method TryPeekAsync (line 65) | public Task<ConditionalValue<T>> TryPeekAsync(ITransaction tx, TimeSpa...
    method TryPeekAsync (line 73) | public Task<ConditionalValue<T>> TryPeekAsync(ITransaction tx)
    method ClearAsync (line 81) | public Task ClearAsync()
    method GetCountAsync (line 92) | public Task<long> GetCountAsync()
    method CreateEnumerableAsync (line 97) | public Task<IAsyncEnumerable<T>> CreateEnumerableAsync(ITransaction tx)
    method GetCountAsync (line 102) | public Task<long> GetCountAsync(ITransaction tx)

FILE: ReferenceApp/Mocks/MockReliableStateManager.cs
  class MockReliableStateManager (line 18) | public class MockReliableStateManager : IReliableStateManagerReplica
    method ClearAsync (line 45) | public Task ClearAsync(ITransaction tx)
    method ClearAsync (line 51) | public Task ClearAsync()
    method CreateTransaction (line 57) | public ITransaction CreateTransaction()
    method RemoveAsync (line 62) | public Task RemoveAsync(string name)
    method RemoveAsync (line 70) | public Task RemoveAsync(ITransaction tx, string name)
    method RemoveAsync (line 78) | public Task RemoveAsync(string name, TimeSpan timeout)
    method RemoveAsync (line 86) | public Task RemoveAsync(ITransaction tx, string name, TimeSpan timeout)
    method RemoveAsync (line 94) | public Task RemoveAsync(Uri name)
    method RemoveAsync (line 102) | public Task RemoveAsync(Uri name, TimeSpan timeout)
    method RemoveAsync (line 110) | public Task RemoveAsync(ITransaction tx, Uri name)
    method RemoveAsync (line 118) | public Task RemoveAsync(ITransaction tx, Uri name, TimeSpan timeout)
    method TryGetAsync (line 126) | public Task<ConditionalValue<T>> TryGetAsync<T>(string name) where T :...
    method TryGetAsync (line 134) | public Task<ConditionalValue<T>> TryGetAsync<T>(Uri name) where T : IR...
    method GetOrAddAsync (line 142) | public Task<T> GetOrAddAsync<T>(string name) where T : IReliableState
    method GetOrAddAsync (line 147) | public Task<T> GetOrAddAsync<T>(ITransaction tx, string name) where T ...
    method GetOrAddAsync (line 152) | public Task<T> GetOrAddAsync<T>(string name, TimeSpan timeout) where T...
    method GetOrAddAsync (line 157) | public Task<T> GetOrAddAsync<T>(ITransaction tx, string name, TimeSpan...
    method GetOrAddAsync (line 162) | public Task<T> GetOrAddAsync<T>(Uri name) where T : IReliableState
    method GetOrAddAsync (line 167) | public Task<T> GetOrAddAsync<T>(Uri name, TimeSpan timeout) where T : ...
    method GetOrAddAsync (line 172) | public Task<T> GetOrAddAsync<T>(ITransaction tx, Uri name) where T : I...
    method GetOrAddAsync (line 177) | public Task<T> GetOrAddAsync<T>(ITransaction tx, Uri name, TimeSpan ti...
    method TryAddStateSerializer (line 182) | public bool TryAddStateSerializer<T>(IStateSerializer<T> stateSerializer)
    method GetDependency (line 187) | private IReliableState GetDependency(Type t)
    method ToUri (line 194) | private Uri ToUri(string name)
    method GetAsyncEnumerator (line 199) | public IAsyncEnumerator<IReliableState> GetAsyncEnumerator()
    method Initialize (line 204) | public void Initialize(StatefulServiceInitializationParameters initial...
    method OpenAsync (line 209) | public Task<IReplicator> OpenAsync(ReplicaOpenMode openMode, IStateful...
    method ChangeRoleAsync (line 214) | public Task ChangeRoleAsync(ReplicaRole newRole, CancellationToken can...
    method CloseAsync (line 219) | public Task CloseAsync(CancellationToken cancellationToken)
    method Abort (line 224) | public void Abort()
    method BackupAsync (line 228) | public Task BackupAsync(Func<BackupInfo, CancellationToken, Task<bool>...
    method BackupAsync (line 233) | public Task BackupAsync(BackupOption option, TimeSpan timeout, Cancell...
    method RestoreAsync (line 238) | public Task RestoreAsync(string backupFolderPath)
    method RestoreAsync (line 243) | public Task RestoreAsync(string backupFolderPath, RestorePolicy restor...

FILE: ReferenceApp/Mocks/MockServiceProxy.cs
  class MockServiceProxy (line 15) | public class MockServiceProxy : IServiceProxy
    method Create (line 23) | public TServiceInterface Create<TServiceInterface>(Uri serviceName) wh...
    method Create (line 34) | public TServiceInterface Create<TServiceInterface>(Uri serviceUri, Ser...
    method Supports (line 39) | public void Supports<TServiceInterface>(Func<Uri, object> Create)

FILE: ReferenceApp/Mocks/MockServiceProxyFactory.cs
  class MockServiceProxyFactory (line 18) | public class MockServiceProxyFactory : IServiceProxyFactory
    method CreateServiceProxy (line 22) | public TServiceInterface CreateServiceProxy<TServiceInterface>(Uri ser...
    method AssociateMockServiceAndName (line 32) | public void AssociateMockServiceAndName(Uri mockServiceUri, IService m...

FILE: ReferenceApp/Mocks/MockTransaction.cs
  class MockTransaction (line 12) | public class MockTransaction : ITransaction
    method CommitAsync (line 14) | public Task CommitAsync()
    method Abort (line 19) | public void Abort()
    method Dispose (line 36) | public void Dispose()
    method GetVisibilitySequenceNumberAsync (line 40) | public Task<long> GetVisibilitySequenceNumberAsync()

FILE: ReferenceApp/RestockRequest.Actor/ActorEventSource.cs
  class ActorEventSource (line 13) | [EventSource(Name = "MyCompany-Web_UIApplication-RestockRequestActor")]
    method ActorEventSource (line 26) | static ActorEventSource()
    method ActorEventSource (line 34) | private ActorEventSource() : base()
    method Message (line 46) | [NonEvent]
    method Message (line 56) | [Event(MessageEventId, Level = EventLevel.Informational, Message = "{0...
    method ActorMessage (line 65) | [NonEvent]
    method ActorHostInitializationFailed (line 89) | [Event(ActorHostInitializationFailedEventId, Level = EventLevel.Error,...
    method ActorMessage (line 96) | [Event(ActorMessageEventId, Level = EventLevel.Informational, Message ...
    class Keywords (line 127) | public static class Keywords

FILE: ReferenceApp/RestockRequest.Actor/RestockRequestActor.cs
  class RestockRequestActor (line 17) | internal class RestockRequestActor : Actor, IRestockRequestActor, IRemin...
    method RestockRequestActor (line 26) | public RestockRequestActor(ActorService actorService, ActorId actorId)
    method ReceiveReminderAsync (line 30) | public Task ReceiveReminderAsync(string reminderName, byte[] context, ...
    method AddRestockRequestAsync (line 50) | public async Task AddRestockRequestAsync(RestockRequest request)
    method OnActivateAsync (line 80) | protected override async Task OnActivateAsync()
    method RestockPipeline (line 98) | internal async Task RestockPipeline()
    method SignalRequestStatusChange (line 132) | private void SignalRequestStatusChange(RestockRequestActorState state)
    method UnregisterRestockPipelineChangeReminderAsync (line 140) | private Task UnregisterRestockPipelineChangeReminderAsync()

FILE: ReferenceApp/RestockRequest.Actor/RestockRequestActorState.cs
  class RestockRequestActorState (line 12) | [DataContract]
    method IsStarted (line 21) | public bool IsStarted()
    method ToString (line 27) | public override string ToString()

FILE: ReferenceApp/RestockRequest.Actor/RestockRequestReminderNames.cs
  class RestockRequestReminderNames (line 8) | internal static class RestockRequestReminderNames

FILE: ReferenceApp/RestockRequest.Actor/ServiceHost.cs
  class ServiceHost (line 12) | public class ServiceHost
    method Main (line 14) | public static void Main(string[] args)

FILE: ReferenceApp/RestockRequest.Domain/IRestockRequestActor.cs
  type IRestockRequestActor (line 11) | public interface IRestockRequestActor : IActor, IActorEventPublisher<IRe...
    method AddRestockRequestAsync (line 13) | Task AddRestockRequestAsync(RestockRequest request);

FILE: ReferenceApp/RestockRequest.Domain/IRestockRequestEvents.cs
  type IRestockRequestEvents (line 10) | public interface IRestockRequestEvents : IActorEvents
    method RestockRequestCompleted (line 14) | void RestockRequestCompleted(ActorId actorId, RestockRequest request);

FILE: ReferenceApp/RestockRequest.Domain/RestockRequest.cs
  class RestockRequest (line 12) | [DataContract]
    method RestockRequest (line 15) | public RestockRequest(InventoryItemId itemId, int quantity)
    method ToString (line 27) | public override string ToString()

FILE: ReferenceApp/RestockRequest.Domain/RestockRequestStatus.cs
  type RestockRequestStatus (line 8) | public enum RestockRequestStatus

FILE: ReferenceApp/RestockRequestManager.Domain/IRestockRequestManager.cs
  type IRestockRequestManager (line 12) | public interface IRestockRequestManager : IService
    method AddRestockRequestAsync (line 14) | Task AddRestockRequestAsync(RestockRequest request);

FILE: ReferenceApp/RestockRequestManager.Service/Program.cs
  class Program (line 12) | public class Program
    method Main (line 14) | public static void Main(string[] args)

FILE: ReferenceApp/RestockRequestManager.Service/RestockRequestManagerService.cs
  class RestockRequestManagerService (line 26) | internal class RestockRequestManagerService : StatefulService, IRestockR...
    method RestockRequestManagerService (line 35) | public RestockRequestManagerService(StatefulServiceContext serviceCont...
    method RestockRequestManagerService (line 39) | public RestockRequestManagerService(StatefulServiceContext serviceCont...
    method RestockRequestCompleted (line 56) | public async void RestockRequestCompleted(ActorId actorId, RestockRequ...
    method AddRestockRequestAsync (line 75) | public async Task AddRestockRequestAsync(RestockRequest request)
    method CreateServiceReplicaListeners (line 122) | protected override IEnumerable<ServiceReplicaListener> CreateServiceRe...
    method RunAsync (line 135) | protected override async Task RunAsync(CancellationToken cancellationT...

FILE: ReferenceApp/RestockRequestManager.Service/ServiceEventSource.cs
  class ServiceEventSource (line 13) | [EventSource(Name = "MyCompany-Web_UIApplication-RestockRequestManagerSe...
    method ServiceEventSource (line 37) | static ServiceEventSource()
    method ServiceEventSource (line 45) | private ServiceEventSource() : base()
    method Message (line 57) | [NonEvent]
    method Message (line 67) | [Event(MessageEventId, Level = EventLevel.Informational, Message = "{0...
    method ServiceMessage (line 76) | [NonEvent]
    method ServiceTypeRegistered (line 94) | [Event(ServiceTypeRegisteredEventId, Level = EventLevel.Informational,...
    method ServiceHostInitializationFailed (line 101) | [Event(ServiceHostInitializationFailedEventId, Level = EventLevel.Erro...
    method ServiceRequestStart (line 108) | [Event(ServiceRequestStartEventId, Level = EventLevel.Informational, M...
    method ServiceRequestStop (line 114) | [Event(ServiceRequestStopEventId, Level = EventLevel.Informational, Me...
    method ServiceRequestFailed (line 120) | [Event(ServiceRequestFailedEventId, Level = EventLevel.Error, Message ...
    method ServiceMessage (line 126) | [Event(ServiceMessageEventId, Level = EventLevel.Informational, Messag...
    class Keywords (line 152) | public static class Keywords

FILE: ReferenceApp/Web.Service/Controllers/HomeController.cs
  class HomeController (line 9) | public class HomeController : Controller
    method Index (line 11) | public IActionResult Index()
    method Admin (line 16) | public IActionResult Admin()
    method OrderConfirmation (line 21) | public IActionResult OrderConfirmation()
    method Error (line 25) | public IActionResult Error()

FILE: ReferenceApp/Web.Service/Controllers/InventoryController.cs
  class InventoryController (line 15) | public class InventoryController : Controller
    method CreateInventoryItem (line 30) | [HttpPost]

FILE: ReferenceApp/Web.Service/Controllers/OrdersController.cs
  class OrdersController (line 17) | public class OrdersController : Controller
    method PostCheckout (line 38) | [HttpPost]
    method GetOrderStatus (line 78) | [HttpGet]

FILE: ReferenceApp/Web.Service/Controllers/StoreController.cs
  class StoreController (line 20) | public class StoreController : Controller
    method GetStore (line 32) | [HttpGet]

FILE: ReferenceApp/Web.Service/Program.cs
  class Program (line 9) | internal static class Program
    method Main (line 14) | private static void Main()

FILE: ReferenceApp/Web.Service/ServiceEventSource.cs
  class ServiceEventSource (line 12) | [EventSource(Name = "MyCompany-WebReferenceApplication-Service")]
    method ServiceEventSource (line 17) | static ServiceEventSource()
    method ServiceEventSource (line 25) | private ServiceEventSource() : base() { }
    class Keywords (line 31) | public static class Keywords
    method Message (line 47) | [NonEvent]
    method Message (line 58) | [Event(MessageEventId, Level = EventLevel.Informational, Message = "{0...
    method ServiceMessage (line 67) | [NonEvent]
    method ServiceMessage (line 90) | [Event(ServiceMessageEventId, Level = EventLevel.Informational, Messag...
    method ServiceTypeRegistered (line 127) | [Event(ServiceTypeRegisteredEventId, Level = EventLevel.Informational,...
    method ServiceHostInitializationFailed (line 134) | [Event(ServiceHostInitializationFailedEventId, Level = EventLevel.Erro...
    method ServiceRequestStart (line 144) | [Event(ServiceRequestStartEventId, Level = EventLevel.Informational, M...
    method ServiceRequestStop (line 151) | [Event(ServiceRequestStopEventId, Level = EventLevel.Informational, Me...
    method GetReplicaOrInstanceId (line 159) | private static long GetReplicaOrInstanceId(ServiceContext context)
    method SizeInBytes (line 176) | private int SizeInBytes(string s)

FILE: ReferenceApp/Web.Service/Startup.cs
  class Startup (line 13) | public class Startup
    method Startup (line 15) | public Startup(IHostingEnvironment env)
    method ConfigureServices (line 28) | public void ConfigureServices(IServiceCollection services)
    method Configure (line 35) | public void Configure(IApplicationBuilder app, IHostingEnvironment env...

FILE: ReferenceApp/Web.Service/WebService.cs
  class WebService (line 19) | internal sealed class WebService : StatelessService
    method WebService (line 21) | public WebService(StatelessServiceContext context)
    method CreateServiceInstanceListeners (line 29) | protected override IEnumerable<ServiceInstanceListener> CreateServiceI...
Condensed preview — 146 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (459K chars).
[
  {
    "path": ".gitignore",
    "chars": 177,
    "preview": "[Bb]ackup*/\n[Oo]bj/\n[Bb]in/\npkg/\nobjd/\nTestResults/\n.nuget/\n*.sln.ide/\n_ReSharper.*/\npackages/\n.vs/\n*.user\n*.suo\n*.cache"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 873,
    "preview": "# Contributing to Azure samples\r\n\r\nThank you for your interest in contributing to Azure samples!\r\n\r\n## Ways to contribut"
  },
  {
    "path": "Docs/architecture.md",
    "chars": 5026,
    "preview": "# Application architecture\n\nThe application is composed of individual services to perform the major functions of the app"
  },
  {
    "path": "LICENSE",
    "chars": 1087,
    "preview": "The MIT License (MIT)\n\nCopyright (c) 2015 Microsoft Corporation\n\nPermission is hereby granted, free of charge, to any pe"
  },
  {
    "path": "README.md",
    "chars": 5516,
    "preview": "---\nlanguages:\n- csharp\nproducts:\n- azure\n- azure-service-fabric\npage_type: sample\ndescription: \"The web reference appli"
  },
  {
    "path": "ReferenceApp/Common/ActorMessageId.cs",
    "chars": 3497,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Common/Common.csproj",
    "chars": 7542,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"14.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.micro"
  },
  {
    "path": "ReferenceApp/Common/HashUtil.cs",
    "chars": 981,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Common/Properties/AssemblyInfo.cs",
    "chars": 1684,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Common/ServiceUriBuilder.cs",
    "chars": 2171,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Common/packages.config",
    "chars": 650,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"Microsoft.ServiceFabric\" version=\"5.6.204\" targetFra"
  },
  {
    "path": "ReferenceApp/CustomerOrder.Actor/ActorEventSource.cs",
    "chars": 5897,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/CustomerOrder.Actor/App.config",
    "chars": 529,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<configuration>\r\n  <startup>\r\n    <supportedRuntime version=\"v4.0\" sku=\".NETFra"
  },
  {
    "path": "ReferenceApp/CustomerOrder.Actor/CustomerOrder.Actor.csproj",
    "chars": 8403,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"14.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.micro"
  },
  {
    "path": "ReferenceApp/CustomerOrder.Actor/CustomerOrderActor.cs",
    "chars": 11971,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/CustomerOrder.Actor/CustomerOrderReminderNames.cs",
    "chars": 477,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/CustomerOrder.Actor/PackageRoot/Config/Settings.xml",
    "chars": 595,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Settings xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3"
  },
  {
    "path": "ReferenceApp/CustomerOrder.Actor/PackageRoot/ServiceManifest.xml",
    "chars": 1649,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<ServiceManifest xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http:/"
  },
  {
    "path": "ReferenceApp/CustomerOrder.Actor/Program.cs",
    "chars": 886,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/CustomerOrder.Actor/Properties/AssemblyInfo.cs",
    "chars": 1797,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/CustomerOrder.Actor/packages.config",
    "chars": 650,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"Microsoft.ServiceFabric\" version=\"5.6.204\" targetFra"
  },
  {
    "path": "ReferenceApp/CustomerOrder.Domain/CustomerOrder.Domain.csproj",
    "chars": 7483,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"12.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.micro"
  },
  {
    "path": "ReferenceApp/CustomerOrder.Domain/CustomerOrderItem.cs",
    "chars": 1153,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/CustomerOrder.Domain/CustomerOrderStatus.cs",
    "chars": 516,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/CustomerOrder.Domain/ICustomerOrderActor.cs",
    "chars": 647,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/CustomerOrder.Domain/Properties/AssemblyInfo.cs",
    "chars": 1720,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/CustomerOrder.Domain/app.config",
    "chars": 426,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<configuration>\r\n  <runtime>\r\n    <assemblyBinding xmlns=\"urn:schemas-microsoft"
  },
  {
    "path": "ReferenceApp/CustomerOrder.Domain/packages.config",
    "chars": 650,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"Microsoft.ServiceFabric\" version=\"5.6.204\" targetFra"
  },
  {
    "path": "ReferenceApp/CustomerOrder.UnitTests/CustomerOrder.UnitTests.csproj",
    "chars": 10571,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"14.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.micro"
  },
  {
    "path": "ReferenceApp/CustomerOrder.UnitTests/CustomerOrderActorTests.cs",
    "chars": 10099,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/CustomerOrder.UnitTests/Properties/AssemblyInfo.cs",
    "chars": 1675,
    "preview": "// ------------------------------------------------------------\n//  Copyright (c) Microsoft Corporation.  All rights re"
  },
  {
    "path": "ReferenceApp/CustomerOrder.UnitTests/app.config",
    "chars": 426,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<configuration>\r\n  <runtime>\r\n    <assemblyBinding xmlns=\"urn:schemas-microsoft"
  },
  {
    "path": "ReferenceApp/CustomerOrder.UnitTests/packages.config",
    "chars": 650,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"Microsoft.ServiceFabric\" version=\"5.6.204\" targetFra"
  },
  {
    "path": "ReferenceApp/Inventory.Domain/IInventoryService.cs",
    "chars": 1040,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Inventory.Domain/Inventory.Domain.csproj",
    "chars": 7822,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"14.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.micro"
  },
  {
    "path": "ReferenceApp/Inventory.Domain/InventoryItem.cs",
    "chars": 5529,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Inventory.Domain/InventoryItemId.cs",
    "chars": 2277,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Inventory.Domain/InventoryItemView.cs",
    "chars": 793,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Inventory.Domain/Properties/AssemblyInfo.cs",
    "chars": 1718,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Inventory.Domain/packages.config",
    "chars": 650,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"Microsoft.ServiceFabric\" version=\"5.6.204\" targetFra"
  },
  {
    "path": "ReferenceApp/Inventory.Service/App.config",
    "chars": 1789,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<configuration>\r\n  <startup>\r\n    <supportedRuntime version=\"v4.0\" sku=\".NETFra"
  },
  {
    "path": "ReferenceApp/Inventory.Service/AzureBackupStore.cs",
    "chars": 6540,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Inventory.Service/IBackupStore.cs",
    "chars": 800,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Inventory.Service/Inventory.Service.csproj",
    "chars": 9817,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"14.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.micro"
  },
  {
    "path": "ReferenceApp/Inventory.Service/InventoryService.cs",
    "chars": 31125,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Inventory.Service/LocalBackupStore.cs",
    "chars": 5375,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Inventory.Service/PackageRoot/Config/Settings.xml",
    "chars": 1108,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<Settings xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3"
  },
  {
    "path": "ReferenceApp/Inventory.Service/PackageRoot/ServiceManifest.xml",
    "chars": 1752,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<ServiceManifest Name=\"Inventory.ServicePkg\"\n                 Version=\"1.0.0\"\n  "
  },
  {
    "path": "ReferenceApp/Inventory.Service/Program.cs",
    "chars": 1145,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Inventory.Service/Properties/AssemblyInfo.cs",
    "chars": 1799,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Inventory.Service/ServiceEventSource.cs",
    "chars": 7435,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Inventory.Service/StatefulServiceParameters.cs",
    "chars": 1329,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Inventory.Service/packages.config",
    "chars": 1484,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"Microsoft.Azure.KeyVault.Core\" version=\"2.0.4\" targe"
  },
  {
    "path": "ReferenceApp/Inventory.UnitTests/Inventory.UnitTests.csproj",
    "chars": 9269,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"14.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.micro"
  },
  {
    "path": "ReferenceApp/Inventory.UnitTests/InventoryServiceTests.cs",
    "chars": 5522,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Inventory.UnitTests/Properties/AssemblyInfo.cs",
    "chars": 1667,
    "preview": "// ------------------------------------------------------------\n//  Copyright (c) Microsoft Corporation.  All rights re"
  },
  {
    "path": "ReferenceApp/Inventory.UnitTests/app.config",
    "chars": 1684,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<configuration>\r\n  <runtime>\r\n    <assemblyBinding xmlns=\"urn:schemas-microsoft"
  },
  {
    "path": "ReferenceApp/Inventory.UnitTests/packages.config",
    "chars": 556,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"Microsoft.ServiceFabric\" version=\"5.6.204\" targetFra"
  },
  {
    "path": "ReferenceApp/Mocks/MockActorStateManager.cs",
    "chars": 3766,
    "preview": "// ------------------------------------------------------------\n//  Copyright (c) Microsoft Corporation.  All rights re"
  },
  {
    "path": "ReferenceApp/Mocks/MockAsyncEnumerable.cs",
    "chars": 1634,
    "preview": "namespace Mocks\r\n{\r\n    using Microsoft.ServiceFabric.Data;\r\n    using System.Collections.Generic;\r\n    using System.Th"
  },
  {
    "path": "ReferenceApp/Mocks/MockCodePackageActivationContext.cs",
    "chars": 6085,
    "preview": "namespace Mocks\r\n{\r\n\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Collections.ObjectMode"
  },
  {
    "path": "ReferenceApp/Mocks/MockInventoryService.cs",
    "chars": 2872,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Mocks/MockReliableDictionary.cs",
    "chars": 9933,
    "preview": "// ------------------------------------------------------------\n//  Copyright (c) Microsoft Corporation.  All rights re"
  },
  {
    "path": "ReferenceApp/Mocks/MockReliableQueue.cs",
    "chars": 3875,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Mocks/MockReliableStateManager.cs",
    "chars": 8432,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Mocks/MockServiceProxy.cs",
    "chars": 2079,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Mocks/MockServiceProxyFactory.cs",
    "chars": 1713,
    "preview": "// ------------------------------------------------------------\n//  Copyright (c) Microsoft Corporation.  All rights re"
  },
  {
    "path": "ReferenceApp/Mocks/MockTransaction.cs",
    "chars": 1072,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Mocks/Mocks.csproj",
    "chars": 9048,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"14.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.micro"
  },
  {
    "path": "ReferenceApp/Mocks/Properties/AssemblyInfo.cs",
    "chars": 1639,
    "preview": "// ------------------------------------------------------------\n//  Copyright (c) Microsoft Corporation.  All rights re"
  },
  {
    "path": "ReferenceApp/Mocks/app.config",
    "chars": 1190,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<configuration>\r\n  <runtime>\r\n    <assemblyBinding xmlns=\"urn:schemas-microsoft"
  },
  {
    "path": "ReferenceApp/Mocks/packages.config",
    "chars": 650,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"Microsoft.ServiceFabric\" version=\"5.6.204\" targetFra"
  },
  {
    "path": "ReferenceApp/Nuget.Config",
    "chars": 152,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<configuration>\r\n  <config>\r\n    <add key=\"repositorypath\" value=\"packages\" />\r"
  },
  {
    "path": "ReferenceApp/RestockRequest.Actor/ActorEventSource.cs",
    "chars": 5904,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/RestockRequest.Actor/App.config",
    "chars": 531,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<configuration>\r\n  <startup>\r\n    <supportedRuntime version=\"v4.0\" sku=\".NETFra"
  },
  {
    "path": "ReferenceApp/RestockRequest.Actor/PackageRoot/Config/Settings.xml",
    "chars": 598,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Settings xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3"
  },
  {
    "path": "ReferenceApp/RestockRequest.Actor/PackageRoot/ServiceManifest.xml",
    "chars": 1660,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<ServiceManifest xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http:/"
  },
  {
    "path": "ReferenceApp/RestockRequest.Actor/Properties/AssemblyInfo.cs",
    "chars": 1710,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/RestockRequest.Actor/RestockRequest.Actor.csproj",
    "chars": 8124,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"14.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.micro"
  },
  {
    "path": "ReferenceApp/RestockRequest.Actor/RestockRequestActor.cs",
    "chars": 7089,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/RestockRequest.Actor/RestockRequestActorState.cs",
    "chars": 1140,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/RestockRequest.Actor/RestockRequestReminderNames.cs",
    "chars": 493,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/RestockRequest.Actor/ServiceHost.cs",
    "chars": 919,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/RestockRequest.Actor/packages.config",
    "chars": 650,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"Microsoft.ServiceFabric\" version=\"5.6.204\" targetFra"
  },
  {
    "path": "ReferenceApp/RestockRequest.Domain/IRestockRequestActor.cs",
    "chars": 588,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/RestockRequest.Domain/IRestockRequestEvents.cs",
    "chars": 731,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/RestockRequest.Domain/Properties/AssemblyInfo.cs",
    "chars": 1732,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/RestockRequest.Domain/RestockRequest.Domain.csproj",
    "chars": 7536,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"12.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.micro"
  },
  {
    "path": "ReferenceApp/RestockRequest.Domain/RestockRequest.cs",
    "chars": 985,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/RestockRequest.Domain/RestockRequestStatus.cs",
    "chars": 467,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/RestockRequest.Domain/app.config",
    "chars": 426,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<configuration>\r\n  <runtime>\r\n    <assemblyBinding xmlns=\"urn:schemas-microsoft"
  },
  {
    "path": "ReferenceApp/RestockRequest.Domain/packages.config",
    "chars": 650,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"Microsoft.ServiceFabric\" version=\"5.6.204\" targetFra"
  },
  {
    "path": "ReferenceApp/RestockRequestManager.Domain/IRestockRequestManager.cs",
    "chars": 599,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/RestockRequestManager.Domain/Properties/AssemblyInfo.cs",
    "chars": 1728,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/RestockRequestManager.Domain/RestockRequestManager.Domain.csproj",
    "chars": 7793,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"14.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.micro"
  },
  {
    "path": "ReferenceApp/RestockRequestManager.Domain/app.config",
    "chars": 1190,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<configuration>\r\n  <runtime>\r\n    <assemblyBinding xmlns=\"urn:schemas-microsoft"
  },
  {
    "path": "ReferenceApp/RestockRequestManager.Domain/packages.config",
    "chars": 650,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"Microsoft.ServiceFabric\" version=\"5.6.204\" targetFra"
  },
  {
    "path": "ReferenceApp/RestockRequestManager.Service/App.config",
    "chars": 529,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<configuration>\r\n  <startup>\r\n    <supportedRuntime version=\"v4.0\" sku=\".NETFra"
  },
  {
    "path": "ReferenceApp/RestockRequestManager.Service/PackageRoot/Config/Settings.xml",
    "chars": 697,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<Settings xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3"
  },
  {
    "path": "ReferenceApp/RestockRequestManager.Service/PackageRoot/ServiceManifest.xml",
    "chars": 1788,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<ServiceManifest Name=\"RestockRequestManager.ServicePkg\"\n                 Versio"
  },
  {
    "path": "ReferenceApp/RestockRequestManager.Service/Program.cs",
    "chars": 1047,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/RestockRequestManager.Service/Properties/AssemblyInfo.cs",
    "chars": 1728,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/RestockRequestManager.Service/RestockRequestManager.Service.csproj",
    "chars": 8592,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"14.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.micro"
  },
  {
    "path": "ReferenceApp/RestockRequestManager.Service/RestockRequestManagerService.cs",
    "chars": 8268,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/RestockRequestManager.Service/ServiceEventSource.cs",
    "chars": 7459,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/RestockRequestManager.Service/packages.config",
    "chars": 650,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"Microsoft.ServiceFabric\" version=\"5.6.204\" targetFra"
  },
  {
    "path": "ReferenceApp/Web.Service/.bowerrc",
    "chars": 33,
    "preview": "{\n  \"directory\": \"wwwroot/lib\"\n}\n"
  },
  {
    "path": "ReferenceApp/Web.Service/App.config",
    "chars": 99,
    "preview": "<configuration>\r\n   <runtime>\r\n      <gcServer enabled=\"true\"/>\r\n   </runtime>\r\n</configuration>\r\n"
  },
  {
    "path": "ReferenceApp/Web.Service/Controllers/HomeController.cs",
    "chars": 584,
    "preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Microsoft.AspNet"
  },
  {
    "path": "ReferenceApp/Web.Service/Controllers/InventoryController.cs",
    "chars": 1883,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Web.Service/Controllers/OrdersController.cs",
    "chars": 4639,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Web.Service/Controllers/StoreController.cs",
    "chars": 2571,
    "preview": "// ------------------------------------------------------------\r\n//  Copyright (c) Microsoft Corporation.  All rights r"
  },
  {
    "path": "ReferenceApp/Web.Service/PackageRoot/Config/Settings.xml",
    "chars": 398,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<Settings xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3"
  },
  {
    "path": "ReferenceApp/Web.Service/PackageRoot/ServiceManifest.xml",
    "chars": 1513,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<ServiceManifest Name=\"Web.ServicePkg\"\n                 Version=\"1.0.0\"\n        "
  },
  {
    "path": "ReferenceApp/Web.Service/Program.cs",
    "chars": 1381,
    "preview": "using Microsoft.ServiceFabric.Services.Runtime;\r\nusing System;\r\nusing System.Diagnostics;\r\nusing System.Threading;\r\nusi"
  },
  {
    "path": "ReferenceApp/Web.Service/Properties/launchSettings.json",
    "chars": 622,
    "preview": "{\n  \"iisSettings\": {\n    \"windowsAuthentication\": false,\n    \"anonymousAuthentication\": true,\n    \"iisExpress\": {\n     "
  },
  {
    "path": "ReferenceApp/Web.Service/ServiceEventSource.cs",
    "chars": 9071,
    "preview": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Diagnostics.Tracing;\r\nusing System.Fabric;\r\nusing System"
  },
  {
    "path": "ReferenceApp/Web.Service/Startup.cs",
    "chars": 2423,
    "preview": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Threading.Tasks;\r\nusing Microsoft.As"
  },
  {
    "path": "ReferenceApp/Web.Service/Views/Home/Admin.cshtml",
    "chars": 926,
    "preview": "<body ng-controller=\"testController\">\n    <div class=\"masthead\">\n        <div class=\"container\">\n            <p style=\""
  },
  {
    "path": "ReferenceApp/Web.Service/Views/Home/Index.cshtml",
    "chars": 2525,
    "preview": "<body ng-controller=\"testController\" data-ng-init=\"initIndex()\">\n    <div class=\"masthead\">\n        <div class=\"contain"
  },
  {
    "path": "ReferenceApp/Web.Service/Views/Home/OrderConfirmation.cshtml",
    "chars": 1696,
    "preview": "<body ng-controller=\"testController\" data-ng-init=\"refreshStatus()\">\n    <div class=\"masthead\">\n        <div class=\"con"
  },
  {
    "path": "ReferenceApp/Web.Service/Views/Shared/Error.cshtml",
    "chars": 708,
    "preview": "@{\n    ViewData[\"Title\"] = \"Error\";\n}\n\n<h1 class=\"text-danger\">Error.</h1>\n<h2 class=\"text-danger\">An error occurred wh"
  },
  {
    "path": "ReferenceApp/Web.Service/Views/Shared/_Layout.cshtml",
    "chars": 763,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\" ng-app=\"fabrikam\">\n<head>\n    <meta charset=\"utf-8\">\n    <meta http-equiv=\"X-UA-Compati"
  },
  {
    "path": "ReferenceApp/Web.Service/Views/Shared/_ValidationScriptsPartial.cshtml",
    "chars": 1158,
    "preview": "<environment names=\"Development\">\n    <script src=\"~/lib/jquery-validation/dist/jquery.validate.js\"></script>\n    <scri"
  },
  {
    "path": "ReferenceApp/Web.Service/Views/_ViewImports.cshtml",
    "chars": 73,
    "preview": "@using Web.Service\n@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers\n"
  },
  {
    "path": "ReferenceApp/Web.Service/Views/_ViewStart.cshtml",
    "chars": 30,
    "preview": "@{\n    Layout = \"_Layout\";\n}\n"
  },
  {
    "path": "ReferenceApp/Web.Service/Web.Service.csproj",
    "chars": 2107,
    "preview": "<Project Sdk=\"Microsoft.NET.Sdk.Web\">\r\n\r\n  <PropertyGroup>\r\n    <TargetFramework>net452</TargetFramework>\r\n    <Runtime"
  },
  {
    "path": "ReferenceApp/Web.Service/WebService.cs",
    "chars": 2273,
    "preview": "using System;\r\nusing System.Collections.Generic;\r\nusing System.Fabric;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing Sys"
  },
  {
    "path": "ReferenceApp/Web.Service/appsettings.Development.json",
    "chars": 166,
    "preview": "{\n  \"Logging\": {\n    \"IncludeScopes\": false,\n    \"LogLevel\": {\n      \"Default\": \"Debug\",\n      \"System\": \"Information\","
  },
  {
    "path": "ReferenceApp/Web.Service/appsettings.json",
    "chars": 103,
    "preview": "{\n  \"Logging\": {\n    \"IncludeScopes\": false,\n    \"LogLevel\": {\n      \"Default\": \"Warning\"\n    }\n  }\n}\n"
  },
  {
    "path": "ReferenceApp/Web.Service/bower.json",
    "chars": 161,
    "preview": "{\n  \"name\": \"asp.net\",\n  \"private\": true,\n  \"dependencies\": {\n    \"bootstrap-css-only\": \"v3.3.7\",\n    \"angular\": \"v1.6.4"
  },
  {
    "path": "ReferenceApp/Web.Service/bundleconfig.json",
    "chars": 602,
    "preview": "// Configure bundling and minification for the project.\n// More info at https://go.microsoft.com/fwlink/?LinkId=808241\n"
  },
  {
    "path": "ReferenceApp/Web.Service/wwwroot/css/site.css",
    "chars": 716,
    "preview": "body {\n    padding-top: 50px;\n    padding-bottom: 20px;\n}\n\n/* Wrapping element */\n/* Set some basic padding to keep con"
  },
  {
    "path": "ReferenceApp/Web.Service/wwwroot/js/angular-index.js",
    "chars": 6769,
    "preview": "(function (angular) {\n    var app = angular.module(\"fabrikam\", ['ngCookies'])\n        .controller(\"testController\", fun"
  },
  {
    "path": "ReferenceApp/WebReferenceApp.sln",
    "chars": 7971,
    "preview": "\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio 15\r\nVisualStudioVersion = 15.0.26430.6\r\n"
  },
  {
    "path": "ReferenceApp/WebReferenceApplication/ApplicationPackageRoot/ApplicationManifest.xml",
    "chars": 4270,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<ApplicationManifest xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"ht"
  },
  {
    "path": "ReferenceApp/WebReferenceApplication/ApplicationParameters/Cloud.xml",
    "chars": 1108,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Application Name=\"fabric:/WebReferenceApplication\" xmlns=\"http://schemas.micros"
  },
  {
    "path": "ReferenceApp/WebReferenceApplication/ApplicationParameters/Local.1Node.xml",
    "chars": 1219,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Application xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www"
  },
  {
    "path": "ReferenceApp/WebReferenceApplication/ApplicationParameters/Local.5Node.xml",
    "chars": 1220,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Application xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www"
  },
  {
    "path": "ReferenceApp/WebReferenceApplication/PublishProfiles/Cloud.xml",
    "chars": 1382,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<PublishProfile xmlns=\"http://schemas.microsoft.com/2015/05/fabrictools\">\n  <!--"
  },
  {
    "path": "ReferenceApp/WebReferenceApplication/PublishProfiles/Local.1Node.xml",
    "chars": 615,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<PublishProfile xmlns=\"http://schemas.microsoft.com/2015/05/fabrictools\">\n  <!--"
  },
  {
    "path": "ReferenceApp/WebReferenceApplication/PublishProfiles/Local.5Node.xml",
    "chars": 615,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<PublishProfile xmlns=\"http://schemas.microsoft.com/2015/05/fabrictools\">\n  <!--"
  },
  {
    "path": "ReferenceApp/WebReferenceApplication/Scripts/Deploy-FabricApplication.ps1",
    "chars": 9135,
    "preview": "<#\r\n.SYNOPSIS \r\nDeploys a Service Fabric application type to a cluster.\r\n\r\n.DESCRIPTION\r\nThis script deploys a Service "
  },
  {
    "path": "ReferenceApp/WebReferenceApplication/WebReferenceApplication.sfproj",
    "chars": 3009,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"14.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.micro"
  },
  {
    "path": "ReferenceApp/WebReferenceApplication/app.config",
    "chars": 903,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n  <runtime>\n    <assemblyBinding xmlns=\"urn:schemas-microsoft-co"
  },
  {
    "path": "ReferenceApp/WebReferenceApplication/packages.config",
    "chars": 144,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"Microsoft.VisualStudio.Azure.Fabric.MSBuild\" version"
  }
]

About this extraction

This page contains the full source code of the Azure-Samples/service-fabric-dotnet-web-reference-app GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 146 files (414.5 KB), approximately 97.1k tokens, and a symbol index with 367 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!