Entity CodeFirst EF6, EntityData string id - azure

Have started to use Entity Code First with Azure Mobile Services and have met some issue:
For using TableController with Entity objects I need to derive each of them from EntityData class, that provide string Id field!
I used to use int, long and even guid instead string for id, so...
What is benefits of this?
What about insert operation and what is the best practice for this?
What about performance for string id?

#carlosfigueira has a good writeup about the change to using string id here: http://blogs.msdn.com/b/carlosfigueira/archive/2013/11/23/new-tables-in-azure-mobile-services-string-id-system-properties-and-optimistic-concurrency.aspx

EntityData is a class which Dtos should implement because it is required for offline feature, at least was I got as answer.
To create a Table controller you need to use it, but you can ignore if you want... Suppose you have a class called "CarDto" the dto will have a property "carDto.Id" that is from EntityData, but you can create the "carDto.CarId" as your key! The only thing you need to do is create a model based in that you want and match it with your database and then use AutoMapper to match the car's model with car's dto :)
See Azure Mobile Services - Samples and articles to help developers to use Azure Mobile Services, which has a sample about to match dtos to model.
Or you can apply this approach Build a service using an existing SQL database with the Mobile Services .NET backend, but I do not like because in my opinion is confuse.... you choose what fits your needs :)

Related

How to utilize the Unit of Work pattern with repositories in onion architecture that query external APIs?

There are many excellent resources about the Unit of Work pattern. My understanding is that it's main purpose is to provide a way to ensure that the effects of a piece of code will not persist if an error occurs. There are plenty of examples of this usage for databases in most languages.
There are very few resources I can find about using such patterns to query and use external APIs while maintaining some level of data integrity during an error. Generally repositories are about data persistence but a lot of API's do concern such things especially in a microservice architecture. Clean Architecture: Where to make API calls suggests that such a microservice architecture should abstract calls to other microservices using a repository, and there are many public APIs that can be thought of in a similar manner.
In my specific case, I am looking to plug in the Todoist API for Task items into my application which works with its own version of a Todo entity. I have successfully adapted my TodoRepository for the Todoist API and can see my tasks from Todoist displayed in my UI - I now face the issue that if a call fails then I could be adding, deleting or updating a Task in the Todoist API when an error occurs after the call, which is not ideal for data integrity reasons.
There seems to be some distinction between an API that can act as a repository and one that cannot. Seemingly, if the API is able to perform general CRUD on a similar entity in the modelled entity then it may be a good candidate for a repository adapter, but if it were something like retrieving the weather forecast, determining if a name is the same as some celebrity, working with the google maps API (if your application wasn't a map itself), etc, then these are handled differently.
Under the assumption that I have not yet confirmed that all API adapters/facades will be implemented in the Infrastructure layer of a project, what context does the interface that defines the API usage exist? If I want to query to see if a name is also a celebrity name, would I have an Application or Domain service interface that looks something like
public interface CelebrityService {
Celebrity LinkNameToCelebrity(string first_name, string last_name);
}
Where Celebrity is a Domain entity. This feels out of place if the Celebrity entity has been made only for this call.
Similarly for a weather API,
public interface WeatherService {
Weather GetWeatherForDay(datetime day);
}

Best Practice Advice - Loopback API

I want to make a webservice and it looks like Loopback is good starting point.
To explain my question, I will describe situation
I have 2 MySQL Tables:
Users
Companies
Every User has it's Company. It's like master User for it's company.
I wish to create Products table for each company next way:
company1_Products,
company2_Products,
company3_Products
Each company have internal Users, like:
company1_Users,
company2_Users,
company3_Users
Internal users are logging in from corresponding subdomain, like
company1.myservice.com
company2.myservice.com
For the API, I want datasource to get Products from the corresponding table. So the question is, how to change datasource dynamically?
And how to handle Users? Storing in one table is not good, because internal company users could be in different companies...
Maybe there's better way to do such models?
Disclaimer: I am co-author and one of current maintainers of LoopBack.
how to change datasource dynamically?
The following StackOverflow answer describes a solution how to attach a single model (e.g. Product) to multiple datasources: https://stackoverflow.com/a/28327323/69868 This solution would work if you were creating one MySQL database per company instead of using company's name as the prefix of Product table name.
To achieve what you described, you can use model subclassing. For each company, define a new company-specific Product model inheriting from the shared Product model and changing the table name.
// common/models/company1-product.json
{
"name": "Company1_Product",
"base": "Product",
"mysql": {
"tableName": "company1_Products"
}
// etc.
}
You can even create these models on the fly using app.registry.createModel() and app.model() APIs, and then run dataSource.autoupdate to create SQL tables for the new model(s).
And how to handle Users? Storing in one table is not good, because internal company users could be in different companies...
I suppose you can use the same approach as you do for Products and as you described in your question.
Maybe there's better way to do such models?
The problem you are facing is calling multi-tenancy. I am afraid we haven't figured out an easy to use solution yet. There are many possible ways how to implement multi-tenancy.
For example, you can create one LoopBack application for each Company (tenant) and then create a top-level LoopBack or Express application to route incoming requests to appropriate tenant-specific LB app instance. See the following repository for a proof-of-concept implementation: https://github.com/strongloop/loopback-multitenant-poc

What is the TableController class for and where are its methods used?

I've been starting out with Azure and have chosen to set up a Mobile Service using .NET in VS. I've been learning about the constituents of the Azure Todo get-started server project.
One thing I'm struggling to understand (even with extensive Googling) is what the TableController methods are for? I understand that TableController exposes the table to HTTP requests? But when I access data from my client I'm using ".LookupAsync" or ".UpdateAsync" methods on the Table returned by my MobileServiceClient instance.
Are the GetAllToDoItems(..), PathToDoItem(..), GetToDoItem(..), PostToDoItem(..), DeleteToDoItem(..) methods in the TableController being used behind the scenes somewhere when I make those calls on the MobileServiceClient Table?
Can I access those methods from my client? Are these methods standard/required method names?
Is TableController a good place to put server code for authorisation? E.g. the classic example of only returning that user's records?
Thanks for any help,
Tom.
Can I access those methods from my client? Are these methods standard/required method names?
At currently, Azure mobile app support C# and node.js as its backend language. From the Get started article, we can know that we can take advantage of Mobile App using native SDKs whether you're building native iOS, Android, and Windows apps or cross-platform Xamarin or Cordova (Phonegap) apps. We can see a lot of functions like GetAllToDoItems(..), PathToDoItem(..), GetToDoItem(..), PostToDoItem(..), DeleteToDoItem(..) in the backend project. This method is a MVC controller action name. Please note the SDK functions are the important, as we can see below, the backend project has a function called GetTodoItem.
public SingleResult<TodoItem> GetTodoItem(string id)
{
return Lookup(id);
}
However the function Lookup which under the namespace "Microsoft.Azure.Mobile.Server" is the key method in this function:
Is TableController a good place to put server code for authorisation? E.g. the classic example of only returning that user's records?
If you want to add authentication, I think this article may be give you helps. Just use Azure AD for example, if you want to protect some table controller, we only need to configure Azure AD then add [Authorize] attribute before table controller, it is not necessary to add authrize code in that table controller.

ServiceStack batabase first OrmLite.Poco.cs generated, now what?

there are extremely few docs about ServiceStack around. Let alone database first approach. So now I have OrmLite.Poco.cs with all the models mapped from SQL Server. What is the next step? Add routes to the models on OrmLite.Poco.cs or copy out each class into individual .cs file then add routes to it? Thanks.
Great you now have your Table POCO's which you can start querying with, e.g:
var results = Db.Select<Poco>();
Custom Routes only go on Request DTO's you should not re-use your OrmLite models to also define the contract for your Services.
For an example, checkout this Simple OrmLite Database sample showing how to use the Customer Table POCO in OrmLite to create a Simple Customer REST Service.

Service Stack migrating RPC to REST issues

Trying to sell a move to ServiceStack from traditional ASP.Net /SOAP web services with the management team.
I am struggling with a some RPC'ish issues. Requirement is that I support SOAP (even backhandedly) in the hope of selling my service consumers on REST.
Take for example a service called "ReplaceItem" which basically requires:
Close out item number
Replacement item number
Store Number
Bunch of other replacement item data
Should I create a ReplacementItem DTO? It seems to be if I have a number of these type of functions I am just going to have tons of DTOs instead of tons of RPC methods. Plus what is the "id" in this case and what REST method would I be using?
I get that REST/SS gives me basic CRUD functionality for domain level structures like Items/Customers/etc, but how do I handle non-CRUD methods in SS.
I am also having issues with multiple parameters making up the primary key for a certain service. Almost all Inventory tables are structured by Item Number AND Store Number. I'd rather not dump the creation of some composite string on the service client. How do I handle this?
Thanks.
ServiceStack promotes a SOA-like message-based design that is optimal and provides many natural benefits for remote services.
My initial thoughts would look something like
POST {CloseItemNumber} /item/1/close
POST {ItemNumber} /item/1?replace=true
POST {ItemNumber} /item/1
POST {ItemNumber} /item/1 i.e. same DTO/service different values.
Where ItemNumber and CloseItemNumber are separate Request DTOs and services.
Designing Service APIs
I prefer to structure my services around 'resources/nouns' and design my service APIs as actions that apply operations to them.
If the operation requires more information than storing the Resource DTO I would create a separate service with the additional metadata.
i.e. Here's how I would convert Amazons 'RPC' service to be more REST-ful:
https://ec2.amazonaws.com/?Action=AttachVolume
&VolumeId=vol-4d826724
&InstanceId=i-6058a509
&Device=/dev/sdh
&AUTHPARAMS
Into how I prefer to write it:
POST https://ec2.amazonaws.com/volumes/vol-4d826724/attach
FormData: InstanceId=i-6058a509&Device=/dev/sdh&AUTHPARAMS
Which would still use an explicit AttachVolume Request DTO.
Another example I use to showcase the different between WCF RPC and ServiceStack's coarse-grained message-based approach is in: https://gist.github.com/1386381
Difference between an RPC-chatty and message-based API:
This is a typical API that WCF encourages:
public interface IService
{
Customer GetCustomerById(int id);
Customer[] GetCustomerByIds(int[] id);
Customer GetCustomerByUserName(string userName);
Customer[] GetCustomerByUserNames(string[] userNames);
Customer GetCustomerByEmail(string email);
Customer[] GetCustomerByEmails(string[] emails);
}
This is an equivalent message-based API we encourage in ServiceStack:
public class Customers {
int[] Ids;
string[] UserNames;
string[] Emails;
}
public class CustomersResponse {
Customer[] Results;
}
Note: If you want your same services to support a both SOAP and a REST-based API, you will need to structure your services slightly differently to overcome SOAP's limitation of tunnelling all operations through HTTP POST.
Problem i still have when deciding to switch from 1 chatty RPC api to a REST api is that instead of having several functions easy to maintain, i find myself with either 2 solutions :
multiplying DTOs and services that makes internal code for the services being chatty and complex
or
putting into a single route (OnGet) all the code managing the service but this way i have to parse the different parameters to 'discover' which parameters have been requested (to simplify instead of having multiple simple functions with pre-defined parameters i now have only one function that has to determine which parameters are meaningful ... but that is VERY hard to maintain - code is more complex to me now).
In the proposed solution to solve GetCustomerById, GetCustomersByEmails etc. the point to me is that instead of having simple queries, we now have to dynamically construct the query based on the filled parameters - that can make the code tricky and hard to maintain - having to manage possible combinations of multiple parameters - some combinations not being possible too.
Feeling little bit sad about that as i REALLY don't like WCF at all.
Mixing WCF and REST seems summum of the complexity - the worst for me (complexity of defining a REST api + complexity of WCF).
Are my feelings shared or did i miss something ?

Resources