How to create a new record with a particular GUID - guid

Using the Dynamics CRM I'm trying to create an instance of an entity. I would like to manually set the GUID, but if I had the attribute that is the primary key to the DynamicEntity, I get following error.
Service could not process request
I am building a DynamicEntity, and setting the [entityname]id attribute causes the request to fail. It's moving data between two CRM instances, so if anyone knows of a better way to copy records between CRMs, that'd work too. Otherwise, I'd like the GUID to match across instances... as that's the point of a GUID.

Happily, it IS possible to do this across two CRM instances! A co-worker knew the solution, so credit really belongs to him.
My mistake was creating a Property with type UniqueIdentifierProperty. The primary key attribute on an entity needs to be filled in with a KeyProperty. These two properties are nearly identical -- the Property types are, except that one holds a Key, the other a UniqueIdentifier. The Key/UniqueIdentifier both hold GUIDs. (Another day in the mind of Microsoft!)
Precisely, what I'm doing is creating a DynamicEntity, filling in the entity name, and filling in the majority of the attributes. The PK attribute (which you can determine from the metadata) can be filled in with a KeyProperty. I was filling it in with a UniqueIdentifierProperty, which CRM rejects and responds with a nondescript and unhelpful error message.

I apologize if I am over-simplifying the solution, but why not add a custom field in both instances that would be a mirror of the other instances guid?

Related

Complex Rule in Drupal involving multiple entities

I need to create a fairly complex rule in Drupal - I am willing to use either code or the interface to do so.
I am more familiar with the interface, however, as opposed to the Rules API.
Anyway, the rule will be as follows:
It will happen based on a form submission from entityforms (which is one entity). It will take the checkbox value of a field (not just the true or false, but rather the value submitted when a value is true or false). It will convert this number to an integer.
At this point things get interesting - I want to create a new entity of registrations (a different entity), which as far as I can tell, means I'll have to bring a registration into scope. I also need to bring node (and not just node: type and other data selectors, but specifically node) into scope, because the next step requires it.
So at this point, I should have three entities loaded into scope:
entityforms
registration
node
I believe the best way to bring registration into scope would be entity is of type? The documentation page says that content of type should be appropriate - but that seems like it might be related to the specific use case of the example - not in my more complex example where registration isn't the first entity dealt with, but rather a second.
https://drupal.org/node/1463042
So anyway, if all three of these entities is called in correctly, the ultimate result should be the following:
Value from boolean field (not the straight 1 or 0, but whatever the value to be submitted is switched to) from the entityform is converted to an integer, and inserted where entity host ID is required. In the section where host entity type is the value should be node.
I am also open to alternative suggestions if this seems overly complex or poorly architected.
The Host Entity Type cannot be of Entityform? Why be a Node since a Registration can be attached to any entity? Then you will get the id of the Entityform as also as any other fields from that entity type instead of Node. Next steps are the same.

How to handle duplicates in disconnected object graph?

I'm having a problem updating a disconnected POCO model in an ASP.NET application.
Lets say we have the following model:
Users
Districts
Orders
A user can be responsible for 0 or more districts, an order belongs to a district and a user can be the owner of an order.
When the user logs in the user and the related districts are loaded. Later the user loads an order, and sets himself as the owner of the order. The user(and related districts) and order(and related district) are loaded in two different calls with two different dbcontexts. When I save the order after the user has assigned himself to it. I get an exception that saying that acceptchanges cannot continue because the object's key values conflict with another object.
Which is not strange, since the same district can appear both in the list of districts the user is responsible and on the order.
I've searched high and low for a solution to this problem, but the answers I have found seems to be either:
Don't load the related entities of one of the objects in my case that would be the districts of the user.
Don't assign the user to the order by using the objects, just set the foreign key id on the order object.
Use nHibernate since it apparently handles it.
I tried 1 and that works, but I feel this is wrong because I then either have to load the user without it's districts before relating it to the order, or do a shallow clone. This is fine for this simple case here, but the problem is that in my case district might appear several more times in the graph. Also it seems pointless since I have the objects so why not let me connected them and update the graph. The reason I need the entire graph for the order, is that I need to display all the information to the user. So since I got all the objects why should I need to either reload or shallow clone it to get this to work?
I tried using STE but I ran in to the same problem, since I cannot attach an object to a graph loaded by another context. So I am back at square 1.
I would assume that this is a common problem in anything but tutorial code. Yet, I cannot seem to find any good solution to this. Which makes me think that either I do not under any circumstance understand using POCOs/EF or I suck at using google to find an answer to this problem.
I've bought both of the "Programming Entity Framework" books from O'Reilly by Julia Lerman but cannot seem to find anything to solve my problem in those books either.
Is there anyone out there who can shed some light on how to handle graphs where some objects might be repeated and not necessarily loaded from the same context.
The reason why EF does not allow to have two entities with the same key being attached to a context is that EF cannot know which one is "valid". For example: You could have two District objects in your object graph, both with a key Id = 1, but the two have different Name property values. Which one represents the data that have to be saved to the database?
Now, you could say that it doesn't matter if both objects haven't changed, you just want to attach them to a context in state Unchanged, maybe to establish a relationship to another entity. It is true in this special case that duplicates might not be a problem. But I think, it is simply too complex to deal with all situations and different states the objects could have to decide if duplicate objects are causing ambiguities or not.
Anyway, EF implements a strict identity mapping between object reference identity and key property values and just doesn't allow to have more than one entity with a given key attached to a context.
I don't think there is a general solution for this kind of problem. I can only add a few more ideas in addition to the solutions in your question:
Attach the User to the context you are loading the order in:
context.Users.Attach(user); // attaches user AND user.Districts
var order = context.Orders.Include("Districts")
.Single(o => o.Id == someOrderId);
// because the user's Districts are attached, no District with the same key
// will be loaded again, EF will use the already attached Districts to
// populate the order.Districts collection, thus avoiding duplicate Districts
order.Owner = user;
context.SaveChanges();
// it should work without exception
Attach only the entities to the context you need in order to perform a special update:
using (var context = new MyContext())
{
var order = new Order { Id = order.Id };
context.Orders.Attach(order);
var user = new User { Id = user.Id };
context.Users.Attach(user);
order.Owner = user;
context.SaveChanges();
}
This would be enough to update the Owner relationship. You would not need the whole object graph for this procedure, you only need the correct primary key values of the entities the relationship has to be created for. It doesn't work that easy of course if you have more changes to save or don't know what exactly could have been changed.
Don't attach the object graph to the context at all. Instead load new entities from the database that represent the object graph currently stored in the database. Then update the loaded graph with your detached object graph and save the changes applied to the loaded (=attached) graph. An example of this procedure is shown here. It is safe and a very general pattern (but not generic) but it can be very complex for complex object graphs.
Traverse the object graph and replace the duplicate objects by a unique one, for example just the first one with type and key you have found. You could build a dictionary of unique objects that you lookup to replace the duplicates. An example is here.

Symfony2: loading user roles from database

I'm running into a problem with the Symfony2 Security system, particularly when trying to load Roles from a database. Before going further, I am aware of FOSUserBundle, but at the moment, in an effort to better understand the Symfony2 framework, I want to try and make my bundle work using Symfony2 components only. TL;DR -> please don't tell me to just use the FOSUserBundle. :-)
I have 3 entities configured in my bundle, Accounts, AccountsRoles, and AccountsRepository.
src\RedK\Core\IndexBundle\Entity\Accounts.php
http://pastebin.com/0VgXvtJp
src\RedK\Core\IndexBundle\Entity\AccountsRoles.php
http://pastebin.com/GiKNnYg3
src\RedK\Core\IndexBundle\Entity\AccountsRepository.php
http://pastebin.com/SVuMVdpN
MySQL demo_template.accounts Table
http://pastebin.com/YzmjD9e4
MySQL demo_template.accounts_roles Table
http://pastebin.com/Ybwr4f7y
All aspects of the bundle were working correctly (registration, confirmation, password reset, and login) before I attempted to add the loading of user roles from a database. When I simply set the role to array('ROLE_USER') via the getRoles() { return array('ROLE_USER') }, authentication worked and the user successfully logged into the site.
However, upon attempting to integrate roles from the database, I receive the following error, which I understand is an instance of AuthenticationException:
Notice: Undefined index: id in /home/humplebert/Websites/www/template/vendor/doctrine/lib/Doctrine/ORM/Query/SqlWalker.php line 804
Stack Trace
http://pastebin.com/Sr5RvZaY
The exception is only generated when I modify the query in AccountsRepository and remove
the "->select()" and "->leftJoin()" components. In looking at the Stack Trace, around line 16 on the pastebin.com link, it appears I have all sorts of "crazy" happening with regards to the many-to-many mapping in the BasicEntityPersister.
I've searched high and low in my Entity classes for any reference to plain "id" and can find none. I've noticed that if I change the names of my "ID" columns in my entities to just "id" (i.e. replace "AccountsID" with "id" in src\RedK\Core\IndexBundle\Entity\Accounts) the error goes away (and is replaced with another error, more on that in a moment).
Question 1)
Is there something blatently wrong with my Entities to be generating the "Undefined index: id" error I am receiving? If not, does Symfony2/Doctrine2 require that Auto-Increment columns in be labeled "id"?
As I have continued to tinker, I decided to try renaming my table ID columns to "id". Therefore, src\RedK\Core\IndexBundle\Accounts replaces AccountsID with just "id". And likewise, src\RedK\Core\IndexBundle\AccountsRoles replaces RolesID with just "id". Upon doing so, the "Undefined index: id" error goes away. However, I am presented with a new error: "table or view demo_template.accounts_accountsroles does not exist". Well of course it doesn't exist, I don't have a table defined as accounts_accountsroles. I have two tables, accounts and accounts_roles.
Question 2)
In order to use the Symfony2/Doctrine2 tools for importing user roles from a database, what rules are there regarding the naming of the tables? Based on the error I received, it seems that some form of concatenation is taking place. Or have I just simply screwed up my annotations somewhere along the line?
Any help would be greatly appreciated.
Regarding Question 1) the short answer is no! For the long answer see section 5.3 Mapping Defaults in the Doctrine Association Mapping documentation:
It states that if you use this short annotation:
/** #ManyToMany(targetEntity="Group") */
private $groups;
"In that case, the name of the join table defaults to a combination of the simple, unqualified class names of the participating classes, separated by an underscore character. The names of the join columns default to the simple, unqualified class name of the targeted class followed by “_id”. The referencedColumnName always defaults to “id”, just as in one-to-one or many-to-one mappings."
You can override the defaults by providing more detailed many to many annotations (see link above) and therefore avoid the id error.
Regarding Question 2) the concatenation is correct. Many to many relationships require a third 'junction' table. The Doctrine paragraph above explains how the name of this table is generated.
I don't know why the 'table ... does not exist' error is occurring for the junction table as the annotations look ok to me. It appears as though your database schema is somehow out of sync with your annotations.
I implemented a solution, above FOSUserBundle and described it here
After implementing Role access throug Doctrine you still need to make a RoleHierarchy service aware of it.

MVC3 routes - replace id with object name

I'm looking for a fast & elegant way of converting my object IDs with descriptive names, so that my autogenerated routes look like:
/products/oak-table-25x25-3-1
instead of
/products/5bd8c59c-fc37-40c3-bf79-dd30e79b55a5
In this sample:
uid = "5bd8c59c-fc37-40c3-bf79-dd30e79b55a5"
name = "Oak table (25x25) 3/1"
I don't even know how that feature could be named, so that I might google for it.
The problem that I see so far is the uniqueness of that "url-object-name", for example if I have two oak tables 25x35 in the db, and their names differ too little to be uniquely url-named but enough to fool the unique constraint in the db.
I'm thinking of writing that function for name-transform in SQL as an UDF, then adding a calculated field that returns it, then unique-constraining that field.
Is there some more mainstream way of achieving that?
One method is that employed by stackoverflow.com which in your case would be:
/products/5bd8c59c-fc37-40c3-bf79-dd30e79b55a5/oak-table-25x25-3-1
This ensures uniqueness, however the length of the UUID may be a deterrent. You may consider adding a sequential int or bigint identity value to the products table in addition to the uniqueidentifier field. This however would require an additional index on that column for lookup, though a similar index would be required for a Url having only a descritive string. Yet another method would be to use a hash value, seeded by date for instance, which you can compose with the descriptive name. It is simpler to rely on a sequential ID value generated by a database, but if you envision use NoSQL storage mechanisms in the future you may consider using an externally generated hash value to append.
Identity should have 2 properties: it should be unique and unchangable. If you can guarantee, that /products/oak-table-25x25-3-1 will never change to /products/oak-table-25x25-3-1-1 (remember, user can have bookmarks, that shouldn't return 404 statuscode)- you can use name as url parameter and get record by this parameter.
If you can't guarantee uniqueness or want to select record more faster - use next:
/products/123/oak-table-25x25-3-1 - get record by id (123)
/products/123/blablabla - should redirect to first, because blabla no exists or have anoher id
/products/123 - should redirect to first
And try to use more short identities - remember, that at web 2.0 url is a part of UI, and UI should be friendly.
MVC routing (actions) will handle spaces and slashes in a name. It will encode them as %20, and then decode them correctly.
Thus your URL would be /products/oak%20table%2025x25-3%2F1
I have done something very similar in an eCommerce platform I am working on.
The idea is that the URL without the unique ID is better for SEO but we didn't want the unique ID to be the product name that can change often.
The solution was to implement .NET MVC "URL slug only" functionality. The product manager creates "slugs" for every product that are unique and are assigned to products. These link to the product but the product ID and name can be changed whenever.
This allows:
domain.com/oak-table-25x25-3-1
to point to:
/products/5bd8c59c-fc37-40c3-bf79-dd30e79b55a5
(The same functionality can be used on categories too so domain.com/tables can point to domain.com/category/5b38c79c-f837-42c3-bh79-dd405479b15b5)
I have documented how I did this at:
http://makit.net/post/3380143142/dotnet-slug-only-urls

LINQ to Entities, several one-to-one references to the same tables and naming

I've started porting a .NET SQL Server application to LINQ to Entities. I have (among others...) one table called Users, and one called Time. Time is reported on a specific user (UserId), but it is also recorded which user made the report (InsertedByUserId) and possibly who has updated the Time since insert (UpdatedByUserId). This gives me three references to the table Users.
When I generate a .EDMX from this I get three references to the table Users: User, User1 and User2. Without manual edit I have no way of knowing which one refers to the UserId, InsertedByUserId or UpdatedByUserId field.
How do others solve this? Maybe it's not necessary to register ALL references, and stick with InsertedByUserId and UpdatedByUserId as ints?
(The manual edit wouldn't be a problem if the database were never updated, but as we make changes to the database every now and then we occasionally have to regenerate the .EMDX, thus removing all manual changes.)
Thanks in advance!
Jos,
Generally when I make my foreign keys, I name them accordingly. From the Entity designer you can differentiate between the different Navigation Properties (ie User, User1, User2) by looking at the FK association (as long as you named your foreign keys distinctly). For Instance I have a ModifiedById and CreatedById field in each table. Both fields reference my SystemUser table, My foreign keys are named like this: FK_[TableName]_SystemUser_CreatedBy and FK_[TableName]_SystemUser_ModifiedBy.
You should notice that in the Navigation properties you can see the Foreign key. You can also modify the name of the Navigation Property (which is in the Conceptual Side "CSDL portion" of the EDMX), and this change will stay when you update your EDMX from the database.

Resources