Create Retrieve Update and Delete using oData (Rest endpoint) in Silverlight (CRM 2011)
Views (269)
Hi,
Sharing a basic example that performs CRUD operation using Rest endpoint in Silverlight.
namespace odataSilverlight
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
GGContext context;
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
var orgServiceUrl = "http://r78-7-amscrm/GG/XRMServices/2011/OrganizationData.svc";
// initialize the context
context = new GGContext(new Uri(orgServiceUrl));
// using client http stack
context.HttpStack = System.Data.Services.Client.HttpStack.ClientHttp;
context.UseDefaultCredentials = false;
context.Credentials = new NetworkCredential("administrator", "Secure*8", "AMS");
// create contact record
Contact contact = new Contact();
contact.LastName = "Rana";
contact.FirstName = "Akshaj";
// add the new contact to the contact set
context.AddToContactSet(contact);
// call BeginSaveChanges method and specify the callback method and the contact object
context.BeginSaveChanges(CreateContactHandler, contact);
}
private void CreateContactHandler(IAsyncResult result)
{
// in the call back method call the EndSaveChanges method
// it returns DataServiceResponse object.
// we can get the error information from this object in case an operation fails
context.EndSaveChanges(result);
// id of the created contact record
Guid createdContactGuid = ((Contact)result.AsyncState).ContactId;
// Retrieve the created contact record
DataServiceQuery<Contact> queryContact = (DataServiceQuery<Contact>)
context.ContactSet.
AddQueryOption("$filter", "ContactId eq guid'" + createdContactGuid + "'");
queryContact.BeginExecute(RetrieveContactHandler, queryContact);
}
private void RetrieveContactHandler(IAsyncResult result)
{
DataServiceQuery<Contact> contacts = result.AsyncState as DataServiceQuery<Contact>;
Contact retrievedContact = new DataServiceCollection<Contact>(contacts.EndExecute(result)).First<Contact>();
// Update the retrieved contact record's first name
retrievedContact.FirstName = "Mickey";
context.UpdateObject(retrievedContact);
context.BeginSaveChanges(UpdateContactHandler, retrievedContact);
}
private void UpdateContactHandler(IAsyncResult result)
{
context.EndSaveChanges(result);
Contact contact = (Contact)result.AsyncState;
// Delete the updated contact record
context.DeleteObject(contact);
context.BeginSaveChanges(DeleteContactHandler, contact);
}
private void DeleteContactHandler(IAsyncResult result)
{
context.EndSaveChanges(result);
}
}
}
Hope it helps
Filed under: CRM 2011, oData, Silverlight Tagged: CRM 2011, oData, Silverlight
This was originally posted here.

Like
Report
*This post is locked for comments