Thursday, 16 February 2017

Querying data in Microsoft Dynamics CRM 2016 using Web API



Introduction:

With Microsoft Dynamics CRM 2016, Web API that was in Preview for CRM 2015 is now GA. Web API is really ODATA v4 which is the later version of ODATA v2 that was implemented in earlier versions of CRM until CRM 2015.
With CRM 2016, ODATA v2 is deprecated, this means that though the legacy code written using ODATA v2 will continue to function, it is not advised to continue to develop using this version of ODATA starting CRM 2016.
The earlier version of ODATA was strictly restricted to CRUD operations, how with Web API you can even perform operations that earlier required us to use SOAP requests.
In the earlier post, it was all about executing FetchXML queries using Web API, well that was to some extent because I didn’t have much success querying and applying some very common queries. After spending some more time with WEB API and trying to get things done exclusively using ODATA v4, I did get quite a few things figured out.
In this post, I am listing out some of the frequently used queries and how these could be generated using Web API.
ODATA v4 endpoints:
Under Developer Resources you can now find the endpoint for web api
Querying data in Microsoft Dynamics CRM 2016
Notice the change in the URL structure, it is now /api/data/v8.0/
Earlier it was /xrmservices/2011/organizationdata.svc/
Sample Queries:
  1. List accounts starting with A and C
    var qry = “accounts?$filter=startswith(name,’A’) or startswith(name,’C’)”;
    Since field names have not been specified all the columns are listed.
    The entitycollection does not include Set Prefix anymore besides its using the logical name throughout.
  2. List accounts owned by a particular user
    var qry = “accounts?$select=name,accountnumber,_primarycontactid_value,createdon,accountcategorycode,revenue&$filter=_ownerid_value%20eq%201ea6fc32-9b2d-47e6-b9ab-b5f23f69e34f “;
    Here we had to provide the guid of the user that you need to filter by. Also notice that the ownerid attribute has been mentioned as _ownerid_value
    All lookups are listed in the query result to follow the naming structure
    _<logicalname>_value.
  3. Read account details along with the primary contact phone.
    We need to use the $expand clause to request data of related entity. However it appears that the $expand clause only works when requesting data of a single record as shown in the below query.
    var qry = “accounts(4ef2c099-bca1-e511-80de-3863bb349a78)?$select=name,accountnumber,_primarycontactid_value,createdon,accountcategorycode,revenue&$filter=contains(name,'(sample)’)&$orderby=name&$expand=primarycontactid($select=fullname,telephone1)”
    If you were to request this for the entire accounts collection, you receive the following error message
  4. List all Phone Calls of an account
    This will display only the subject of the related phone calls.
    var qry = “accounts(4ef2c099-bca1-e511-80de-3863bb349a78)?$expand=Account_Phonecalls($select=subject)”
Understand the Query Results
Unlike the ODATA v2 queries, the results here are returned in JSON format
Now if see the results here, the primary contact id only provides the Guid, not really helpful, and for currency data types, it again returns only the number, the currency is provided as transaction guid, so again formatted value missing.
If we want the results to return the formatted values, we need to pass the following in the header tag of the request
odata.include-annotations=”OData.Community.Display.V1.FormattedValue”
I haven’t figured it out how to pass these in the browser url, but here is the code I use to pass the header values.
In the above code you can replace the “*” with “OData.Community.Display.V1.FormattedValue”, the other preferences supported are
Microsoft.Dynamics.CRM.lookuplogicalname
Microsoft.Dynamics.CRM.associatednavigationproperty
Generally for lookups, we are used to receiving 3 set of data,
The lookup entity name, the guid and the record name. By default we only received the Guid of a lookup field, if we need the record name and the entity name, we need to include the preferences listed above.
If you want all preferences to be applied pass “*”
With all preferences the applied the result would appear as
Querying data in CRM 2016 using Web API
Lookup field details are available as shown above
_primarycontactid_value: “1ef3c099-bca1-e511-80de-3863bb349a78″
_primarycontactid_value@Microsoft.Dynamics.CRM.associatednavigationproperty: “primarycontactid”
_primarycontactid_value@Microsoft.Dynamics.CRM.lookuplogicalname: “contact”
_primarycontactid_value@OData.Community.Display.V1.FormattedValue: “Rene Valdes (sample)”
And we now also get the revenue formatted with the currency symbol and the date.
Paging
To handle paging you need to specify the page size, which is now called odata.maxpagesize=n
N stands for the count of records to be returned.
You also receive the paging cookie, which will allow you to request the next set of records.
 Web API
Use the nextlink url to the Web API to request the next set of data. It returns a fully qualified url with the query parameters set that can be used just as is.
Result Count
When you include the $count=true in your query, you get the total count of the records returned by the query in the query result.
If you query the following,
var qry5 = “https://xxx.crm5.dynamics.com/api/data/v8.0/accounts?$count=true&$top=2″
You get
Querying data in Dynamics CRM 2016 using Web API
The total count is 19 even though the results requested were only top 2
Note, if there are more than 5000 records that the query returns, the count here would still return 5000 only.
Conclusion
The Web API query still has a few limitations and like the earlier ODATA v2 there are limitations on what kind of data can be queried. You can find the complete list here
In this post I have covered queries, in the later blogs hope to cover the other operations supported by WEB API.
Make your Dynamics CRM life easy with Inogic Dynamics CRM Solutions. Read more about our add-ons here.

Sunday, 1 January 2017

Building micro services using Service Fabric - Basics


How to :Definition of  Microservices:

Today’s Internet scale services are built using microservices. Example microservices are protocol gateways, user profiles, shopping carts, inventory processing, queues, caches, etc. Microservices can further be defined by:

⦁ Is (logic + state) independently versioned, scaled, and deployed
⦁ Has a unique name that can be resolved
⦁ Interacts with other microservices over well-defined interfaces like REST
⦁ Remains logically consistent in the presence of failures
⦁ Hosted in a container (code + config)
⦁ Can be written in any language or framework

How to:Build Complete Technology Stack using Microservices:

Implement Self-Hosting with ASP.NET 5 Web API
Running ASP.NET 5 on top of Azure Service Fabric is the best fit for building microservices because Service Fabric lets you deploy any number of services into each node/VM, which allows for high microservices density per cluster. ASP.NET 5 also provides exciting features such as the following:
Flexible hosting: You can now host your ASP.NET 5 application on IIS or in your own process. Hosting in your own process is fundamental in Azure Service Fabric.
Web API, MVC and Web Pages: These are all merged together, simplifying the number of concepts.
Full side-by-side support: ASP.NET 5 applications can now be installed on a machine without affecting any other applications on the machine that might be using a different .NET Framework version. This is a huge feature for IT management.
Cross-platform support: ASP.NET 5 runs and is supported on Windows, Mac OS X and Linux.
Cloud-ready: Features such as diagnostics, session state, cache and configuration are designed to work locally and in the cloud (like Azure) with no changes.

Using “MVC-Type” Web Apps and Service Fabric Microservices
ASP.NET MVC is a very popular framework for traditional Web sites, but you cannot use the “old” MVC framework (MVC 5 or older) with Service Fabric. This is due to the fact that in Service Fabric you need to self-host the HTTP listener in your process and that OWIN/Katana is not supported in ASP.NET 4.x MVC (It’s supported only in ASP.NET 4.x Web API.) Therefore, the options you have to implement an “MVC-type” Web application on Service Fabric services are the following:

Use MVC 6 in ASP.NET 5 to self-host the HTTP listener within your Service Fabric microservices process. It supports MVC because in ASP.NET 5, Web API and MVC are consolidated and are in fact the same framework with the same controllers with no dependency to IIS. This will be the preferred choice as soon as ASP.NET 5 is released to manufacture.
Use ASP.NET 4.x Web API with OWIN/Katana to self-host the HTTP listener within your Service Fabric microservices process and simulate MVC controllers with Web API controllers and use HTML/JavaScript output rather than regular Web API content (JSON/XML). The documentation page at bit.ly/1UMdKIf demonstrates how to implement this technique.


What are the building Blocks of Microservices with Azure service Fabric:

Stateful Microservices in Azure Service Fabric

Support for stateful services is an exciting and important component of Azure Service Fabric. It’s also complex and wide-ranging enough that exploring stateful services goes beyond the scope of this article, but we’ll briefly explain what it is. Look for a follow-on article focused on this area of Service Fabric in a future issue.

A stateful microservice in Service Fabric collocates compute and data, with the state placed within the microservice itself (both in-memory and persisted on local disk). The reliability of state is achieved through local persistence and replication of data to other nodes/VMs. Basically, each data partition has several replica services associated with it. Each replica can be deployed in a different node/VM to provide high availability should the primary replica go down. This is similar to how Azure SQL Database works with database replicas, because it’s based on Azure Service Fabric.

In complex and scalable applications, stateful services simplifies the architecture and reduces the number of components compared to a traditional, three-tier architecture that needs to use external cache and queues. When using stateful services, the benefits of a traditional external cache is now intrinsic in the stateful service. Additionally, external queues aren’t needed because we can imple­ment internal queues within the Service Fabric microservices.

When using stateful services, it automatically creates hot backup secondaries that can pick up the operations from the same point where a primary left off following a hardware failure. Many times services have to scale to continue to meet the demands of a growing user base, requiring the addition of hardware to the running environment. Service Fabric uses features such as partitioning so that services can be built in a way that they automatically spread over onto new hardware without requiring user intervention.

Stateful Azure Reliable Services provide a host of capabilities, including data partition support, replica support and leader election, replica service naming, and service address discovery from the gateway service. It also provides management of concurrency and granularity of state changes using transactions, the ability to maintain consistent state replication, and the use of reliable, distributed key/value collections (Reliable Dictionary and Reliable Queue). The good news is that Service Fabric handles the complexity and details of these topics for you, so you can focus on writing applications.

Reliable Actors Services in Azure Service Fabric

Azure Service Fabric Reliable Actors is an actor programming model for Service Fabric. It provides an asynchronous, single-threaded actor model. An actor represents a unit of state and computation. In some ways it’s similar to the open source software project “Orleans” created by Microsoft Research. The important point is that Service Fabric Reliable Actors API is based on the underlying infrastructure provided by Service Fabric.

Implementing actor-instances for Internet of Things (IoT) devices is a good example of actor services usage. A Vehicle-Actor type in the form of a C# class would encapsulate the IoT vehicle domain logic plus its live states like GPS coordinates and other data. Then, we would have potentially millions of actor objects or instances of that mentioned class, distributed across many nodes in the cluster.

Of course, actors are not limited to live IoT objects­—they could be used for any subject, but “live IoT objects” is a great didactic scenario.

Actors are distributed throughout the cluster to achieve high scalability and availability and are treated as in-memory objects in every cluster’s VM. They are also persisted on local disk and replicated through the cluster.

The actors are isolated single-threaded objects that encapsulate both state and behavior. Every actor is an instance of an actor type, similar to the .NET code shown here:

// Actor definition (State+Behaviour) to run in the back end.
// Object instances of this Actor class will be running transparently
// in the service back end.
public class VehicleActor : Actor<Vehicle>, IVehicleActor
{
  public void UpdateGpsPosition(GpsCoordinates coord)
  {
    // Update coordinates and trigger any data processing
    // through the State property on the base class Actor<TState>.
    this.State.Position= coord;
  }
}
Next, the following code shows example client code to use the actor via a proxy object:

// Client .NET code
ActorId actorId = ActorId.NewId();
string applicationName = "fabric:/IoTVehiclesActorApp";
IVehicleActor vehicleActorProxy =
  ActorProxy.Create<IVehicleActor>(actorId, applicationName);
vehicleActorProxy.UpdateGpsPosition(new GpsCoordinates(40.748440, -73.984559));
All the communication infrastructure is taken care of under the hood by the Service Fabric Reliable Actors framework.

You could have millions of VehicleActor objects running on your cluster across many different nodes/VMs, and Service Fabric would be taking care of the required plumbing, including partitions and replicas where your millions of actors are spread and balanced.

The Actors client API provides communication between an actor instance and an actor client. To communicate with an actor, a client creates an actor proxy object that implements the actor interface. The client interacts with the actor by invoking methods on the proxy object.

For the scenarios where actors fit, it greatly simplifies the microservices implementation, especially when compared to stateful reliable services where you have more control but need to implement a lot of plumbing related to partitioning data, partition addressing, replicas and the like. If you don’t need fine-grain control, then you can avoid the extra work by using Reliable Actors.

Tuesday, 6 December 2016

Golden Service Fabric introduction

Since the Keyhole .NET island is expanding rapidly, I was tasked with taking the Java web API and rewriting in .NET. In this blog, I will discuss the process of developing that Web API with .NET and Service Fabric, and show you some tips for avoiding the pitfalls.

Solving Problems

Let’s take it back a step. Here at Keyhole, we are beginning to observe and recommend our clients shift from building monolithic application into building microservices.
Microservice applications are composed of small, independently versioned, and scalable customer-focused services that communicate with each other over standard protocols with well-defined interfaces. – https://azure.microsoft.com
A Microservices approach goes a long way in solving problems that modern enterprises often face, particularly with scalability. It also aids in making development teams more agile in order to deliver functionality easier and quicker to the business, as well as allows for greater technology diversity. That said, there are still some hard problems to solve.
Some of the other hurdles that Microservices help to overcome include upgrading, failover, health checks/monitoring, discovery, and state management. Using Microservices versus a monolithic approach solves more problems than it causes for the majority of situations. Furthermore, the Service Fabric approach is helpful to remove the remaining hurdles.

Our Project Parameters

Alright, so I was tasked with taking the existing Java web API and rewriting in .NET with Service Fabric.
In this project, there are two microservices: a projects and an employees, both containing a web API project and service for persisting.
The web API should follow the same request and responses as the current one, and should have the same routes. The UI should be able to use the web API without having to modify said UI project. Perfect, easy.
The data should be persisted to a local cache. All of the services should be able to handle scaling and failovers with no or minimal downtime. Not bad, little harder.
Here is the big one: the application should be capable of working in different environments… including Linux. What?

Enter Service Fabric

It turns out all of that can be accomplished by using Service Fabric. Let’s put our hands on it and start learning.
Note: I will be only showing how to build the Employee microservice, the Projects’ microservice is very similar to the Employee one.
My first step was to create an Service Fabric Application (er… well it was installing Visual Studio 15 and Service Fabric).
This is important: open Visual Studio as Administrator. Service Fabric need to have admin rights to run. Don’t worry, it will tell you if you don’t.
ServiceFabric1
To meet the requirements, I needed to create three projects: two Service Fabric Applications, a Stateless Web API service, and a Stateful Service for the data. I also needed a contract class library project so the two applications knew how to talk to each other.
I started with the Stateless Web API, not that the order matters.
ServiceFabric2
Now there should be a solution that has two projects: the Service Fabric application and the web API. There is no code in the application project but it is a reference to a set of service projects. The application project is also where you’ll find the publish profiles scripts, and application manifest.
Before I started wiring up the code, I wanted to get all of the project added. So next I added the Stateful Service for persisting the employee data.
First, select the Service Fabric Application that you want to add the new service from. Select Add- -> New Service Fabric Service.
ServiceFabric3
Select the “Stateful Service” option and enter the name.
ServiceFabric4
A stateful reliable service will allow for the use of the reliable collection framework to a persist that the employees locally, meeting one of the requirements. Service Fabric manages the state and, as a developer, I have to do little-to-nothing to manage it. If a node fails, Service Fabric will preserve the state and reinstate it once it switches to a new primary node.
Next up, is the contract project. This is just a regular old class library project add at the solution.
ServiceFabric5

Contract

Starting with contract project I created a POCO for employees.
It’s important to note that in working with Reliable Collections, it’s recommended that object are serializable, immutable, and the class should be sealed. It’s also recommended to avoid using collection properties, as it could affect performance. If you do use collection properties, they should use immutable collections library.
using System;
using System.Runtime.Serialization;
namespace Khs.Employee.Contract
{
    [DataContract]
    public sealed class Employee
    {
        [DataMember]
        public long Id { get; set; }
        [DataMember]
        public String FirstName { get; set; }
        [DataMember]
        public String LastName { get; set; }
        [DataMember]
        public String Email { get; set; }

    }
}
Next I created the Interface for persisting the employee information. The method defined should all be asynchronous and return Task. That interface should implement Microsoft.ServiceFabric.Services.Remoting.IService. Since the persisting service doesn’t need to rely on a specific communication protocol, we can use the Reliable Service framework remoting mechanism. (For more info, see here.) Keep in mind that you’ll have to “nuget”-in the needed library: Install-Package Microsoft.ServiceFabric.Services
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.ServiceFabric.Services.Remoting;

namespace Khs.Employee.Contract
{
    public interface IEmployeeRepository : IService
    {
        Task<Employee> Get(long id);
        Task<IEnumerable<Employee>> Search();
        Task<Employee> Save(Employee employee);
        Task Remove(long id);
    }
}

Service

To be honest, my first attempt at adding a new service instead of using default service failed miserably. I was under a time restraint so I cheated a bit by using the default Service.cs since it was already working. I knew that the issue was probably configuration. I’ve gone back now that I have more time/knowledge and worked it out. It was configuration and it wasn’t hard in hindsight.
Sounds like a normal day, right?
First I added new EmployeeService.cs, a internal sealed class that extends StatefulService base class. The StatefulService give access to the IReliableStateManager and the ReliableCollection. StatefulService base class requires a constructor for StatefulServiceContext.
Next I added the IEmployeeRepository interface and implemented its members. Finally to allow add the override for IEnumerable CreateServiceReplicaListeners(), need the service to create the remote listener.
using System;
using System.Collections.Generic;
using System.Fabric;
using System.Threading.Tasks;
using Khs.Employee.Contract;
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.ServiceFabric.Services.Remoting.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;

namespace Khs.Employee.Service
{
    internal sealed class EmployeeService : StatefulService, IEmployeeRepository
    {
        public const string CacheName = "employeeRepo";
        public EmployeeService(StatefulServiceContext serviceContext) : base(serviceContext)
        {
        }

        public Task<Contract.Employee> Get(long id)
        {
            throw new NotImplementedException();
        }

        public Task<IEnumerable<Contract.Employee>> Search()
        {
            throw new NotImplementedException();
        }

        public Task Remove(long id)
        {
            throw new NotImplementedException();
        }

        public Task<Contract.Employee> Save(Contract.Employee employee)
        {
            throw new NotImplementedException();
        }

        protected override IEnumerable<ServiceReplicaListener> CreateServiceReplicaListeners()
        {
            return new[] {
                new ServiceReplicaListener(context =>
                    this.CreateServiceRemotingListener(context))
            };
        }
    }
}
Now we need to register the service so Service Fabric knows to create a cluster, the configuration I was missing. I was doing two of the three things it takes:
1. Register the Service. Check Open Program.cs and in Main() and add the following code:
ServiceRuntime.RegisterServiceAsync("EmployeeServiceType",context =>new EmployeeService(context))
.GetAwaiter().GetResult();

ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(EmployeeService).Name);
2. Add the type to the Service Manifest. Check. Open the ServiceManifest.xml under the Khs.Employee.Service project PackageRoot folder and in the ServiceType node add
<StatefulServiceType ServiceTypeName="EmployeeServiceType" HasPersistedState="true" />
3. Add the replication configuration. Opps. In the Service Fabric Application Project, open the ApplicationManifest.xml in the ApplicationPackageRoot folder and to the DefaultServices add:
<Service Name="EmployeeService">
<StatefulService ServiceTypeName="EmployeeServiceType" TargetReplicaSetSize="[Service_TargetReplicaSetSize]" MinReplicaSetSize="[Service_MinReplicaSetSize]">
<UniformInt64Partition PartitionCount="[Service_PartitionCount]" LowKey="-9223372036854775808" HighKey="9223372036854775807" />
        </StatefulService>
     </Service>
If you run the project and open the Service Fabric Manager (right-click the service fabric icon ServiceFabric6in the system tray and select ‘manage local cluster’) you should see both the ServiceType (fabric:/Khs.Employee/Service) that is the default service when creating a new project and EmployeeServiceType (fabric:/Khs.Employee/EmployeeService) up and running.
ServiceFabric7

Reliable Collections

Now that I have the Employee Service configured and it appears to be up and running, I needed to add the persistence for the employee data. For this I used the built in Reliable Collection because I’m lazy and they do all of the things for me. Reliable Collection will replicate state changes, providing high availability. They will persist the data to disk to handle outages. They are asynchronous and transactional.
There are currently two types of Reliable Collections Reliable Dictionary, key/value pairs and Reliable Queues, a strict first in, first out queue. For this demo I used the Reliable Dictionary with the employee id being the key and the Employee object as the value.

Get By Id

This is pretty unremarkable. Create a transaction, get the dictionary, try to get the value. If an employee is found, return that; else return null.
public async Task<Contract.Employee> Get(long id)
        {
            using (var tx = StateManager.CreateTransaction())
            {
        var employees = await StateManager.GetOrAddAsync<IReliableDictionary<long, Contract.Employee>>(CacheName);
                var employee = await employees.TryGetValueAsync(tx, id);
                return employee.HasValue ? employee.Value : null;
            }
        }

Search

This is a demo so the the method returns all the employees. This one was a little harder, I was expecting the Reliable Dictionary to be IEnumerable. It is not.
There is extension method that will create an enumerable that will allow you to iterate through the collection and in this case add them into a list to return.
public async Task<IEnumerable<Contract.Employee>> Search()
        {
            using (var tx = StateManager.CreateTransaction())
            {
         var projects = await StateManager.GetOrAddAsync<IReliableDictionary<long, Contract.Employee>>(CacheName);

                 var employees = await projects.CreateEnumerableAsync(tx);
                 var result = new List<Contract.Employee>();
                 using (var asyncEnumerator = employees.GetAsyncEnumerator())
                 {
                     while (await asyncEnumerator.MoveNextAsync(CancellationToken.None))
                     {
                          result.Add(asyncEnumerator.Current.Value);
                     }
                }
                return result;

            }
        }

Save

The save method takes a employee POCO, creates a transaction, and gets the collection. It creates a new ID if it is a new employee, calls, and then Adds or Updates the employee to the collection using the ID as the key. It finally commits the transaction.
public async Task<Contract.Employee> Save(Contract.Employee employee)
{
    using (var tx = StateManager.CreateTransaction())
    {
        var employees = await StateManager.GetOrAddAsync<IReliableDictionary<long, Contract.Employee>>(CacheName);
        if (employee.Id <= 0) { employee.Id = await employees.GetCountAsync(tx) + 1; } await employees.AddOrUpdateAsync(tx, employee.Id, employee, (key, value) => employee);
        await tx.CommitAsync();
    }

    return employee;
}

Remove

Again, this is pretty straightforward. Create a transaction, get the collection, remove the key/value pair, and finally commit the transaction.
public async Task Remove(long id)
        {
            using (var tx = StateManager.CreateTransaction())
            {
                var projects = await StateManager.GetOrAddAsync<IReliableDictionary<long, Contract.Employee>>(CacheName);
                await projects.TryRemoveAsync(tx, id);
                await tx.CommitAsync();
            }
        }
That’s it for the employee service.

Web API

To meet the requirements with web API, I need to have the following routes:
  • GET api/employees: Get all the employees
  • GET api/employees/{id}: Get an employee by id
  • POST api/employees: Insert a new employee
  • PUT api/employees/{id}: Update a specific employee
  • DELETE api/employees/{id}: Removes an employee
It’s pretty straight-forward code. Create an Employees controller and create the above routes.
using System;
using System.Threading.Tasks;
using System.Web.Http;
using Khs.Employee.Contract;
using Microsoft.ServiceFabric.Services.Client;
using Microsoft.ServiceFabric.Services.Remoting.Client;

namespace Khs.Employee.Api.Controllers
{
    
    public class EmployeesController : ApiController
    {
        private readonly IEmployeeRepository _repo;

        public EmployeesController()
        {
            var uri = new Uri("fabric:/Khs.Employee/EmployeeService");
     _repo = ServiceProxy.Create<IEmployeeRepository>(uri, new ServicePartitionKey(0));
        }

        [HttpGet]
        [Route("")]
        public async Task<IHttpActionResult> Get()
        {
            try
            {
                var results = await _repo.Search();
                return Ok(results);
            }
            catch (Exception e)
            {
                return InternalServerError(e);
            }

        }

        [HttpGet]
        [Route("{id}")]
        public async Task<IHttpActionResult> GetById(long id)
        {
            try
            {
                var results = await _repo.Get(id);
                return Ok(results);
            }
            catch (Exception e)
            {
                return InternalServerError(e);
            }

        }

        [HttpPost]
        [Route("")]
        public async Task<IHttpActionResult> Post([FromBody] Contract.Employee employee)
        {
            try
            {
                var result = await _repo.Save(employee);
                return Ok(result);
            }
            catch (Exception e)
            {
                return InternalServerError(e);
            }

        }

        [HttpPut]
        [Route("{id}")]
        public async Task<IHttpActionResult> Put(long id, [FromBody] Contract.Employee employee)
        {
            try
            {
                employee.Id = id;
                var result = await _repo.Save(employee);
                return Ok(result);
            }
            catch (Exception e)
            {
                return InternalServerError(e);
            }
        }

        [HttpDelete]
        [Route("{id}")]
        public async Task<IHttpActionResult> Delete(long id)
        {
            try
            {
                await _repo.Remove(id);
                return Ok();
            }
            catch (Exception e)
            {
                return InternalServerError(e);
            }
        }
    }
}
The only notable is thing is how to wire up the communication between the API and the Employee Service. Calling the methods from the Employee Service is done through local proxy by using the Microsoft.ServiceFabric.Services.Remoting.Client.ServiceProxy class. ServiceProxy has a Create method that will create an object from the interface the service implements.
The URI is the endpoint for that service. If you have trouble with figuring out what the URL should be, you can open the Local Cluster Manager and find the service. It will have the URI as the name.
ServiceFabric8
Now you should be able to create, get, update, and remove employees through the API using your favorite REST Client.

Final Thoughts

I’m a long way off from being Service Fabric expert; I feel like I’ve just barely discovered the usefulness of Service Fabric. But I found it easy to use as the learning curve is minimal. It does more than I expected when I started looking into it. I thought I was getting an answer to Docker. I did, but it’s much more than that – it’s a framework that is perfect for building modern applications.
I do know that I want to go back and refactor all of the code I’ve written to use it. Everything looks like a nail and I have a big golden Service Fabric hammer.

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...