Showing posts with label Silverlight. Show all posts
Showing posts with label Silverlight. Show all posts

Tuesday, 1 May 2012

Silverlight Create, Update, Delete , Retrieve, MultipleRetrieve using Organization OData Service in CRM 2011


In my previous article, i explained all Create , Update ,Delete , Retrieve using Organization service and now in this article, I am going to explain how to Create, Update, Delete, Retrieve using Organization OData service .
To use Organization OData service , Add ODataOrganization.svc Service Reference in your Visual studio Solution

In First Step I am declaring and Initializing SynchronizationContext Object, To Inatalizing Object i am using some functions


SynchronizationContext _syncContext = SynchronizationContext.Current;

//Get the ServerUrl (ServerUrl is formatted differently OnPremise than OnLine)
String _serverUrl = GetServerUrl();

if (!String.IsNullOrEmpty(_serverUrl))
{

    //Setup Context
    AEDevContext _context = new AEDevContext(
         new Uri(String.Format("{0}/xrmservices/2011/organizationdata.svc/",
                 _serverUrl), UriKind.Absolute));

    //This is important because if the entity has new
    //attributes added the code will fail.
    _context.IgnoreMissingProperties = true;
}

//Function for object Initalization
public static String GetServerUrl()
{
    String serverUrl = String.Empty;
    //Try to get the ServerUrl from the Xrm.Page object
    serverUrl = GetServerUrlFromContext();
    return serverUrl;
}

private static String GetServerUrlFromContext()
{
    // If the Silverlight is in a form, this will get the server url
    ScriptObject xrm = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");
    ScriptObject page = (ScriptObject)xrm.GetProperty("Page");
    ScriptObject pageContext = (ScriptObject)page.GetProperty("context");
    //Uncomment before using as webResource
    //String serverUrl = (String)pageContext.Invoke("getServerUrl");
    //comment before using as webResource
    String serverUrl  ="http://crm2011:5555/ITSoft";

    //The trailing forward slash character from CRM Online needs to be removed.
    if (serverUrl.EndsWith("/"))
    {
        serverUrl = serverUrl.Substring(0, serverUrl.Length - 1);
     }

    return serverUrl;
}



Code to Create Account


private void CreateAccount()
{
   Account _account = new Account();
   _account.Name = "Account created using Silverligh ODataService";
   _context.AddToAccountSet(_account);
   _context.BeginSaveChanges(CreateAccount, _account);
}
private void CreateAccount(IAsyncResult result)
{
   _context.EndSaveChanges(result);
   Account _account = result.AsyncState as Account;
}




Code to Update Account

private void UpdateAccount(Guid _accountid)
{
   Account _account = new Account();
   _account.Name = "Update account using Silverligh ODataService";
   _account.AccountId = _accountid;
   _context.AttachTo("AccountSet", _account);
   _context.UpdateObject(_account);
   _context.BeginSaveChanges(UpdateAccount, _account);
}
private void UpdateAccount(IAsyncResult result)
{
   _context.EndSaveChanges(result);
   Account _account = result.AsyncState as Account;
}


Code to Delete Account

private void DeleteAccount(Account _account)
{
   _context.DeleteObject(_account);
   _context.BeginSaveChanges(DeleteAccount, _account);
}
private void DeleteAccount(IAsyncResult result)
{
   Account deletedAccount = result.AsyncState as Account;
   _context.EndSaveChanges(result);    
}


Code to Retrieve Account

private void RetrieveAccount(Guid _accountid)
{
    DataServiceQuery<Account> query = (DataServiceQuery<Account>)_context
         .AccountSet.Where<Account>(a => a.AccountId == _accountid);

    query.BeginExecute(RetrieveAccount, query);
}
private void RetrieveAccount(IAsyncResult result)
{
   DataServiceQuery<Account> results =
         result.AsyncState as DataServiceQuery<Account>;

   Account _account = new DataServiceCollection<Account>(results
         .EndExecute(result)).First<Account>();
}


Code to Retrieve Multiple Account

private void RetrieveMultipleAccount()
{
    DataServiceQuery<Account> accounts = (DataServiceQuery<Account>)this._context
        .AccountSet.Take<Account>(10);
    accounts.BeginExecute(RetrieveMultipleAccount, accounts);
         
}
private void RetrieveMultipleAccount(IAsyncResult result)
{
   //Retrieve the query that was
   DataServiceQuery<Account> results = result.AsyncState as DataServiceQuery<Account>;
   ObservableCollection<Account> _accounts =
            new DataServiceCollection<Account>(results.EndExecute(result));
}

Silverlight Create, Update, Delete , Retrieve, MultipleRetrieve using Organization Service in CRM 2011


In this article, I am trying to explain how to Create, Update, Delete, Retrieve using Organization service.
To use Organization service , Add Organization.svc Service Reference in your Visual studio Solution

In First Step I am declaring and Initializing IOrganizationService Object, To Inatalizing Object i am using some functions


IOrganizationService service= GetSoapService();

//Function for object Initalization
public static IOrganizationService GetSoapService()
{
    Uri serviceUrl = CombineUrl(GetServerBaseUrl(), "/XRMServices/2011/Organization.svc/web");

    BasicHttpBinding binding = new BasicHttpBinding(Uri.UriSchemeHttps == serviceUrl.Scheme
        ? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.TransportCredentialOnly);
    binding.MaxReceivedMessageSize = int.MaxValue;
    binding.MaxBufferSize = int.MaxValue;
    binding.SendTimeout = TimeSpan.FromMinutes(2);

    return new SilverCrmSoap.CrmSdk.OrganizationServiceClient(binding, new EndpointAddress(serviceUrl));
}


public static Uri GetServerBaseUrl()
{
    //comment before using as webResource
    string serverUrl = "http://crm2011:5555/ITSoft";

    //Uncomment before using as webResource
    //string serverUrl = (string)GetContext().Invoke("getServerUrl");

    if (serverUrl.EndsWith("/"))
    serverUrl = serverUrl.Substring(0, serverUrl.Length - 1);

    return new Uri(serverUrl);
}


public static Uri CombineUrl(Uri baseValue, string value)
{
   if (null == baseValue)
   {
       throw new ArgumentNullException("baseValue");
   }
   else if (string.IsNullOrEmpty(value))
   {
      return baseValue;
   }

    //Ensure that a double '/' is not being added
    string newValue = baseValue.AbsoluteUri;
    if (!newValue.EndsWith("/", StringComparison.Ordinal))
    {
       //Check if there is a character at the beginning of value
       if (!value.StartsWith("/", StringComparison.Ordinal))
       {
          newValue += "/";
        }
     }
     else if (value.StartsWith("/", StringComparison.Ordinal))
     {
        value = value.Substring(1);
     }

      //Create the combined URL
      return new Uri(newValue + value);
}




Code to Create Account


void CreateAccount()
{
   Entity entity = new Entity();
   entity.LogicalName = "account";
   entity.Id = new Guid(); //if we will not pass, API will create
   entity["name"] = "Create Account using ORganization Service";
   service.BeginCreate(entity, new AsyncCallback(CreateAccount), service);
}
void CreateAccount(IAsyncResult result)
{
    Guid accoutid =  ((IOrganizationService)result.AsyncState).EndCreate(result);
}




Code to Update Account

void UpdateAccount(Guid AccountID)
{
     Entity entity = new Entity();
     entity.LogicalName = "account";
     entity.Id = AccountID;
     entity["name"] = "Update Account using ORganization Service";
     service.BeginUpdate(entity, new AsyncCallback(UpdateAccount), service);
}
void UpdateAccount(IAsyncResult result)
{
     ((IOrganizationService)result.AsyncState).EndUpdate(result);
}


Code to Delete Account

public void DeleteAccount(Guid AccountID)
{
     service.BeginDelete("account", AccountID, new AsyncCallback(DeleteAccount), service);
}

private void DeleteAccount(IAsyncResult result)
{
     ((IOrganizationService)service).EndDelete(result);
}


Code to Retrieve Account

void RetrieveAccount(Guid AccountID)
{
     ColumnSet _cols = new ColumnSet()
     {
         Columns = new ObservableCollection<string>(new string[] { "parentcustomerid", "accountid" })
         //AllColumns = true
      };
      service.BeginRetrieve("account", AccountID, new AsyncCallback(RetrieveAccount), service);
}
private void RetrieveAccount(IAsyncResult result)
{
      Entity _account =  ((IOrganizationService)service).EndRetrieve(result);
}


Code to Retrieve Multiple Account


void RetrieveMultipleAccount(Guid AccountID)
{
     QueryExpression query = new QueryExpression()
     {
          EntityName = "account",
          ColumnSet = new ColumnSet()
          {
              AllColumns = true
          },


          Criteria = new FilterExpression()
          {
              Conditions = new ObservableCollection<ConditionExpression>(
              new ConditionExpression[]
                  {
                      new ConditionExpression(){
                      AttributeName="parentcustomerid",
                      Operator = ConditionOperator.Equal,
                       Values = new ObservableCollection<object>{AccountID}
                          }
                   })
            },
            };
       OrganizationRequest _OrgRequest = new OrganizationRequest() { RequestName = "RetrieveMultiple" };
       _OrgRequest["Query"] = query;
        service.BeginExecute(_OrgRequest, new AsyncCallback(RetrieveMultipleAccount), service);
}

void RetrieveMultipleAccount(IAsyncResult result)
{
    OrganizationResponse response = ((IOrganizationService)service).EndExecute(result);
    EntityCollection results = (EntityCollection)response["EntityCollection"];
}