Entity Framework add method - completed event - methods

I have a WCF service with Entity Framework and I created a method to insert a new entry in a database (RateMovie() ), and other methods to get data (like GetMovies() )
I want to call the RateMovie() method from a Windows Phone 8 application and do other things when it's completed (update the average rating of a movie... ).
Here is my code :
client.RateMovieCompleted += new EventHandler<ServiceReference1.RateMovieCompletedEventArgs>(client_rateMovieCompleted);
client.RateMovieAsync(idMovie, idDevice, rating);
But the "RateMovieCompletedEventArgs" event does not exist...
I think this is normal, because my method RateMovie() doesn't return anything....
Is there a way to know when the entry is inserted to the database ?
Thanks

I finally add a return value to the RateMovie() method to have a completedEvent

Related

Plugin performance in Microsoft Dynamics CRM 2013/2015

Time to leave the shy mode behind and make my first post on stackoverflow.
After doing loads of research (plugins, performance, indexes, types of update, friends) and after trying several approaches I was unable to find a proper answer/solution.
So if possible I would like to get your feedback/help in a Microsoft Dynamics CRM 2013/2015 plugin performance issue (or coding technique)
Scenario:
Microsoft Dynamics CRM 2013/2015
2 Entities with Relationship 1:N
EntityA
EntityB
EntityB has the following columns:
Id | EntityAId | ColumnDemoX (decimal) | ColumnDemoY (currency)
Entity A has: 500 records
Entity B has: 150 records per each Entity A record. So 500*150 = 75000 records.
Objective:
Create a Post Entity A Plugin Update to "mimic" the following SQL command
Update EntityB
Set ColumnDemoX = (some quantity), ColumnDemoY = (some quantity) * (some value)
Where EntityAId = (some id)
One approach could be:
using (var serviceContext = new XrmServiceContext(service))
{
var query = from a in serviceContext.EntityASet
where a.EntityAId.Equals(someId)
select a;
foreach (EntityA entA in query)
{
entA.ColumnDemoX = (some quantity);
serviceContext.UpdateObject(entA);
}
serviceContext.SaveChanges();
}
Problem:
The foreach for 150 records in the post plugin update will take 20 secs or more.
While the
Update EntityB Set ColumnDemoX = (some quantity), ColumnDemoY = (some quantity) * (some value) Where EntityAId = (some id)
it will take 0.00001 secs
Any suggestion/solution?
Thank you all for reading.
H
You can use the ExecuteMultipleRequest, when you iterate the 150 entities, save the entities you need to update and after that call the request. If you do this, you only call the service once, that's very good for the perfomance.
If your process could be bigger and bigger, then you should think making it asynchronous as a plug-in or a custom activity workflow.
This is an example:
// Create an ExecuteMultipleRequest object.
requestWithResults = new ExecuteMultipleRequest()
{
// Assign settings that define execution behavior: continue on error, return responses.
Settings = new ExecuteMultipleSettings()
{
ContinueOnError = false,
ReturnResponses = true
},
// Create an empty organization request collection.
Requests = new OrganizationRequestCollection()
};
// Add a UpdateRequest for each entity to the request collection.
foreach (var entity in input.Entities)
{
UpdateRequest updateRequest = new UpdateRequest { Target = entity };
requestWithResults.Requests.Add(updateRequest);
}
// Execute all the requests in the request collection using a single web method call.
ExecuteMultipleResponse responseWithResults =
(ExecuteMultipleResponse)_serviceProxy.Execute(requestWithResults);
Few solutions comes to mind but I don't think they will please you...
Is this really a problem ? Yes it's slow and database update can be so much faster. However if you can have it as a background process (asynchronous), you'll have your numbers anyway. Is it really a "I need this numbers in the next second as soon as I click or business will go down" situation ?
It can be a reason to ditch 2013. In CRM 2015 you can use a calculated field. If you need this numbers only to show up in forms (eg. you don't use them in reporting), you could also do it in javascript.
Warning this is for the desesperate call. If you really need your update to be synchronous, immediate, you can't use calculated fields, you really know what your doing etc... Why not do it directly in the database? I know this is a very bad advice. There are a lot of reason not to do it this way (you can read a few here). It's unsupported and if you do something wrong it could go really bad. But if your real situation is as simple as your example (just a calculated field, no entity creation, no relation modification), you could do it this way. You'll have to consider many things: you won't have any audit on the fields, no security, caching issues, no modified by, etc. Actually I pretty much advise against this solution.
1 - Put it this logic to async workflow.
OR
2 - Don't use
serviceContext.UpdateObject(entA);
serviceContext.SaveChanges();.
Get all the records (150) from post stage update the fields and ExecuteMultipleRequest to update crm records in one time.
Don't send update request for each and every record

Plugin Pre Operation Create - Update field error

My plugin fire on Pre Create operation on Entity X. When trying to update a field on the Entity X using the following code I am getting error:
trEntity = (Entity)context.InputParameters["Target"];
trGuid = (Guid)trEntity.Id;
tr = (Entity)service.Retrieve("EntityX", trGuid,
new ColumnSet(new string[] { "field_a", "field_b" }));
tr["field_a"] = null;
service.Update(tr);
The error I am getting is:
Entity X with Id = 11505683-2292-b537-e311-143710e56fb7 Does Not Exist
Since you are in Pre-Create, the entity doesn't exist yet in the database.
You don't need to explicitly call Update in a Pre event. You can just update the Target entity (trEntity in your case) and the changes you make will be saved with the Create operation. The Target entity is the actual entity that is about to be created, so feel free to update fields directly on the Target in the Pre event.
trEntity = (Entity)context.InputParameters["Target"];
trEntity["field_a"] = null;
How are you creating your service?
This also happens when you try to update a record outside of the current transaction i.e. using a manually created OrganizationServiceProxy instead of using the one provided by IOrganizationServiceFactory.CreateOrganizationService.

Grails chained drop down

I'm trying to implement chained drop down boxes using the tutorial here. My classes are not as straight forward as the ones in the tutorial though.
I want to chain the drop down boxes for the create.gsp view in the Load class. Each load belongs to an account from the Account class, and each account belongs to a user from the User class, and each user has several cargo destinations from the Address class.
My goal is to have the cargo destination field up date based on which account is selected.
I am having trouble understanding the AJAX function in the tutorial (step 3), and how it relates to the Grails function (step 4).
Here is the AJAX code:
function respondToSelect(event)
{
new Ajax.Updater("memberSelect",
"/chainedSelect/family/updateSelect",
{method:'get', parameters: {selectedValue : $F("familySelect")} }
);
}
Here is the Grails method:
def updateSelect = {
def familySelected = Family.find("from Family as family where family.surname=:surname", [surname:params.selectedValue])
render (template:"selectMember", model : ['familySelected' : familySelected])
}
If someone could just explain what the third parameter of the AJAX function is doing I think I can figure the Grails part out.
{method:'get', parameters: {selectedValue : $F("account")}}
If someone could just explain what the third parameter of the AJAX
function is doing
The third argument is an object of parameters that get passed to the Updater that tell it how to make the HTTP request to the server.
Make the request an HTTP GET request:
method:'get'
Pass the following named query parameters:
{selectedValue: $F("account")}
$F is a prototype shortcut to retrieve the value of an element. In this case, it's getting the selected value of the DOM element with id account.
This ultimately results in something like the following request:
GET /chainedSelect/family/updateSelect?selectedValue=someValue
Where "someValue" is the currently-selected item in the "account" select list.

updateEntity["new_totalsum"] = new CrmMoney(calculatedvalue);

I can not update the webform. To bee updated I have to push the save button two times. I´ve tried with DynamicEntity entity = (DynamicEntity)context.PreEntityImages["PreCalculate"]; DynamicEntity updateEntity = (DynamicEntity)context.InputParameters.Properties["Target"];
... updateEntity["new_totalsum"] = new CrmMoney(calculatedvalue); The problem is it will not bee updated the first time I push the save button. I have registred the image PreCalculate as Preimage and Message: Update; Eventing Pipeline Stage of Excecution: Pre Stage; Execution Mode : Syncronous
What´s wrong? Thanks
You need to write the modified record back into the Target when you're done, so your changed values will be used when writing the record to the database. At the end of your plugin's Execute() method, do
context.InputParameters[ParameterName.Target] = updateEntity;

Error when I try to read/update the .Body of a Task via EWS Managed API - "You must load or assign this property before you can read its value."

I am using the Exchange Web Services Managed API to work with Tasks (Exchange 2007 SP1). I can create them fine. However, when I try to do updates, it works for all of the fields except for the .Body field. Whenever I try to access (read/update) that field, it gives the following error:
"You must load or assign this property before you can read its value."
The code I am using looks like this:
//impersonate the person whose tasks you want to read
Me.Impersonate(userName); //home-made function to handle impersonation
//build the search filter
Exchange.SearchFilter.SearchFilterCollection filter = New Exchange.SearchFilter.SearchFilterCollection();
filter.Add(New Exchange.SearchFilter.IsEqualTo(Exchange.TaskSchema.Categories, "Sales"));
//do the search
EWS.Task exTask = esb.FindItems(Exchange.WellKnownFolderName.Tasks, filter, New Exchange.ItemView(Integer.MaxValue));
exTask.Subject = txtSubject.Text; //this works fine
exTask.Body = txtBody.Text; //This one gives the error implying that the object isn't loaded
The strange thing is that, inspecting the property bag shows that the object contains 33 properties, but {Body} is not one of them. That property seems to be inherited from the base class .Item, or something.
So, do I need to re-load the object as type Item? Or reload it via .Bind or something? Keep in mind that I need to do this with thousands of items, so efficiency does matter to me.
Calling the Load method solved my problem :)
foreach (Item item in findResults.Items)
{
item.Load();
string subject = item.Subject;
string mailMessage = item.Body;
}
I had the same problem when using the EWS. My Code is requesting the events(Appointments) from the
Outlook calendar, at the end I couldn't reach to the body of the Event itself.
The missing point in my situation was the following "forgive me if there is any typo errors":
After gathering the Appointments, which are also derived from EWS Item Class, I did the following:
1- Create a List with the type Item:
List<Item> items = new List<Item>();
2- Added all appointments to items list:
if(oAppointmentList.Items.Count > 0) // Prevent the exception
{
foreach( Appointment app in oAppointmentList)
{
items.Add(app);
}
}
3- Used the exchanged service "I have already created and used":
oExchangeService.LoadPropertiesForItems(items, PropertySet.FirstClassProperties);
now if you try to use app.Body.Text, it will return it successfully.
Enjoy Coding and Best Luck
I forgot to mention the resource:
http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/ce1e0527-e2db-490d-817e-83f586fb1b44
He mentioned the use of Linq to save the intermediate step, it will help you avoid using the List items and save some memory!
RockmanX
You can load properties using a custom property set. Some properties are Extended properties instead of FirstClassProperties.
Little example:
_customPropertySet = new PropertySet(BasePropertySet.FirstClassProperties, AppointmentSchema.MyResponseType, AppointmentSchema.IsMeeting, AppointmentSchema.ICalUid);
_customPropertySet.RequestedBodyType = BodyType.Text;
appointment.Load(_customPropertySet);

Resources