Read, create, update and detele objects in Microsoft CRM 2011 on premise via WCF service.

How to read, create, update and detele objects in Microsoft CRM 2011 on premise via WCF service.

by admin Posted on 11. August 2011

Please note that this code works for ON PREMISE installation of Microsoft CRM 2011.

In this short article I will show you how to access items in CRM 2011 via new built in WCF webservice. You should use WCF when accessing CRM from code and REST when accessing from client browser of Silverlight application.

Of course you can use old style CRM 4.0 like aproach with QueryExpression class and then RetreiveMultiple on IOrganizationService instance, but there is also easier approach.

You will need to download and extract CRM 2011 SDK. Current version is 5.0.3 and you can find it on this link : http://www.microsoft.com/downloads/en/details.aspx?FamilyID=420f0f05-c226-4194-b7e1-f23ceaa83b69

Here are the steps you need to follow :

  1. Create console application (with full .NET fw 4.0, not client profile) (you can ofcourse create WPF, WinForms or ASP.NET app, but for our example we will use console app)
  2. Locate crmsvcutil.exe in sdk\bin folder along with microsoft.crm.sdk.proxy.dll and microsoft.xrm.sdk.dll.
  3. Both assemblies add as reference to the console project and add also .NET FWs System.ServiceModel and System.Runtime.Serialization.
  4. Use crmsvcutil.exe to use early bound aproach, that will generate classes for all entities within CRM 2011 and also your custom ones. (this is essential something like adding webservice reference to webservice in CRM 4.0 times). I used commandline arguments like this

:crmsvcutil /url:http://server/organization-name/XRMServices/2011/Organization.svc /o:filename.cs /n:namespace /serviceContextName:context-name. /url – url of services, /o – output file, /n – namespace of generated classes, /serviceContextName is name of service,

but when you ommit this switch, no context will be generated at all. Context is used for accessing the entities via WCF.

Example :

CrmSvcUtil.exe /url:”http://kumar/Viveks/XRMServices/2011/Organization.svc” /out:”Entities.cs” /username:”administrator” /password:”pass@word1″ /serviceContextName:”Xrm”

Add generated .cs file to the project (copy to folder, button Show all files, include in project).

  1. Every generated entity will get it’s dedicated IQueryable collection, so for Account you should query AccountSet, for Annotation you should query AnnotationSet and so on. IQueryable means you can query the store with LINQ expressions.

For access you need only this code :

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.Xrm.Sdk.Client;

using Microsoft.Xrm.Sdk;

using System.ServiceModel.Description;

using service-namespace;

namespace CrmConsoleApplication2 {

class Program {

private static IOrganizationService _service;

private static OrganizationServiceProxy _serviceProxy;

static void Main(string[] args) {

IServiceConfiguration<IOrganizationService> orgConfigInfo =

ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(new Uri(“http://server/company-name/XRMServices/2011/Organization.svc&#8221;));

var creds = new ClientCredentials();

using (_serviceProxy = new OrganizationServiceProxy(orgConfigInfo, creds)) {

// This statement is required to enable early-bound type support.

_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

_service = (IOrganizationService)_serviceProxy;

List<Account> acc;

using (context srv = new context(_service)) {

acc = srv.AccountSet.Where(a => a.AccountId != null).ToList();

Account a1 = acc[0]; a1.Name = a1.Name + ” mod mod”; Account a2 = acc[1]; a2.Name = a2.Name + ” mod mod”; srv.UpdateObject(a1);
srv.UpdateObject(a2); srv.SaveChanges();
}
} } } }

And this is what you get @ runtime :

                       

 

You should also wrap OrganizationServiceProxy and also contex with using, because they both use IDisposable interface. Calling .ToList() after where on AccountSet will trigger downloading of all entities.

Please be aware, that downloading many objects will create big response from server

To create and delete record, you can use snippet like this :

                    Account newaaa = new Account();

newaaa.Name = “test acc”;

srv.AddObject(newaaa);

srv.SaveChanges();

Account newAcc = srv.AccountSet.Where(a => a.Name == “test acc”).FirstOrDefault();

srv.DeleteObject(newAcc);

srv.SaveChanges();

This will create new account, when invoking SaveChanges after AddObject, object newaaa will be filled with guid of freshly created Account. To delete object you have to “download” new object from service, you can’t use newaaa object, because context isn’t tracking the changes, so it can’t delete the object also

Custom Aspx Page for MS CRM 2011

Custom Aspx Page for MS CRM 2011 To Create Record in MS CRM

Step 1:

Take an Aspx Page with the Name Lead.aspx

Step 2:

Take a new class with name “OrgService.cs” and write the following code

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.ServiceModel.Description;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Client;

using Microsoft.Xrm.Sdk.Metadata;

using Microsoft.Xrm.Sdk.Messages;

using System.Net;

using System.Web.Services.Protocols;

// <summary>

/// Summary description for OrganizationService

/// </summary>

public class OrgService

{

string serverUri = string.Empty;

public OrgService()

{

}

publicstaticIOrganizationService getOrgService()

{

try

{

//Authenticate using credentials of the logged in user;

ClientCredentials Credentials = newClientCredentials();

Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials

//This URL needs to be updated to match the servername and Organization for the environment.

Uri OrganizationUri = new Uri(http://<SERVERURL>/<ORGNAME>/XRMServices/2011/Organization.svc);

OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(serverUrl, null, cliCredentials, null);

IOrganizationService service = (IOrganizationService)serviceProxy;

serviceProxy.EnableProxyTypes();

return service;

}

catch (SoapException ex)

{

throw ex;

}

}

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.ServiceModel;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Client;

using Microsoft.Xrm.Sdk.Query;

using Microsoft.Xrm.Sdk.Discovery;

public partialclassLead : System.Web.UI.Page

{

IOrganizationService service = OrgService.getOrgService();

protectedvoid Page_Load(object sender, EventArgs e)

{

}

publicvoid CreateLead()

{

Entity lead = newEntity(“lead”);

lead[“firstname”] = txtFName.Text.ToString();

lead[“lastname”] = txtLName.Text.ToString();

lead[“companyname”] = txtCName.Text.ToString();

Guid leadId = service.Create(lead);

}

protectedvoid Button1_Click(object sender, EventArgs e)

{

CreateLead();

}

}

Now Check in CRM Lead , Your Lead has Created

 

MS CRm 2011 Retrieve entity Meta Data Using SOAP Service in SilverLight

MS CRm 2011 Retrieve entity Meta Data Using SOAP Service in SilverLight

Follow Below link to Add Classes to your Project “SilverlightUtility.cs” and “SilverlightExtensionMethods.cs”

http://msdn.microsoft.com/en-us/library/gg594452.aspx

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using MsCrmSoapService.CrmSdk;

using System.Text;

namespace MsCrmSoapService

{

public partial class MainPage : UserControl

{

public MainPage()

{

InitializeComponent();

}

int MaxRecordsToReturn = 5;

private void AccountList_ClickCallback(IAsyncResult result)

{

try

{

OrganizationResponse response = ((IOrganizationService)result.AsyncState).EndExecute(result);

EntityCollection results = (EntityCollection)response[“EntityCollection”];

StringBuilder sb = new StringBuilder();

if (results.Entities.Count == 0)

{

sb.AppendLine(“There are no Account records in the system.”); }

foreach (Entity entity in results.Entities)

{

// sb.AppendLine(“Account Name = ” + entity.GetAttributeValue<string>(“name”));

}

if (results.MoreRecords)

{

sb.AppendLine(“Only the first ” + MaxRecordsToReturn + ” records were returned.”);

}

// this.ReportMessage(sb.ToString());

}

catch (Exception ex)

{

// this.ReportError(ex);

}

}

protected void getdata()

{

try

{

QueryExpression query = new QueryExpression()

{

EntityName = “account”,

ColumnSet = new ColumnSet()

{

Columns = new System.Collections.ObjectModel.ObservableCollection<string>(new string[] { “name” })

},

};

query.PageInfo = new PagingInfo { Count = MaxRecordsToReturn, PageNumber = 1, PagingCookie = null };

OrganizationRequest request = new OrganizationRequest() { RequestName = “RetrieveMultiple” };

request[“Query”] = query;

IOrganizationService service = SilverlightUtility.GetSoapService();

service.BeginExecute(request, new AsyncCallback(AccountList_ClickCallback), service);

}

catch (Exception ex)

{

// this.ReportError(ex);

}

        }

Retrieve OptionSet Lables using MsCrm 2011 SOAP Service in SilverLight

Retrieve OptionSet Lables using MsCrm 2011 SOAP Service in SilverLight

Follow the Below link to Add Class files to your Project “SilverlightExtensionMethods.cs ” and “SilverlightUtility.cs”

http://msdn.microsoft.com/en-us/library/gg594452.aspx

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using MsCrmSoapService.CrmSdk;

using System.Text;

namespace MsCrmSoapService

{

public partial class MainPage : UserControl

{

public MainPage()

{

InitializeComponent();

}

string lblStageValues;

private void OptionSetLabels(string entityName, string attributeName)

{

OrganizationRequest request = new OrganizationRequest();

request.RequestName = “RetrieveAttribute”;

request[“EntityLogicalName”] = “account”;

request[“LogicalName”] = “new_stage”;

request[“MetadataId”] = Guid.Empty;

request[“RetrieveAsIfPublished”] = true;

IOrganizationService service = SilverlightUtility.GetSoapService();

service.BeginExecute(request, new AsyncCallback(Callback), service);

}

private void Callback(IAsyncResult result)

{

this.Dispatcher.BeginInvoke(delegate()

{

try

{

StringBuilder sb = new StringBuilder();

OrganizationResponse response = ((IOrganizationService)result.AsyncState).EndExecute(result);

OptionSetMetadata optionSetMetadata = ((EnumAttributeMetadata)(response.Results[0].Value)).OptionSet;

foreach (OptionMetadata option in optionSetMetadata.Options)

{

lblStageValues = (sb.AppendLine(option.Label.UserLocalizedLabel.Label)).ToString();

}

}

catch (Exception ex)

{

}

});

}

Why use SilverCrmSoap For MS CRM 2011?

Why use SilverCrmSoapFor MS CRM 2011?

If you are using the SOAP End Point, then the library will help simplify your project by removing the complexities of connecting to the SOAP End Point in Silverlight while providing additional tools to assist with your Silverlight project. In the end, it really boils down to where do you use SOAP instead of REST? You use SOAP when:

  • You need to use late binding to create a dynamic Silverlight application that works with any (or multiple) entities.
  • You need to execute a message.
  • You need to assign records.
  • You need to retrieve metadata.

There are benefits to using the REST endpoint too, and being able to quickly leverage both end points in a project can be extremely helpful. You should use the REST End Point when:

  • You need to early bind to objects.
  • You want to leverage LINQ with the early bound objects.
  • You want compile time type support and IntelliSense.

You can find more information on the SOAP and REST End Points in the MSDN Article: Use Web Service Data in Web Resources (REST and SOAP Endpoint).

                        Using SilverCrmSoap

The SilverCrmSoap library is built to be added as a compiled DLL reference in a Silverlight projects. It facilitates making calls to CRM when used in a Silverlight Web-Resource.

Inside your Silverlight application solution in Visual Studio, add a reference to the compiled SilverCrmSoap.dll

Once referenced, there are three namespaces that assist with Silverlight development for CRM:

  • SilverCrmSoap.CrmSdk
  • SilverCrmSoap.FetchXml
  • SilverCrmSoap.Helpers

SilverCrmSoap.CrmSdk

Built following the steps in Walkthrough: Use the SOAP Endpoint for Web Resources with Silverlight, this namespace provides access to the SOAP Endpoint. The SilverCrmSoap.CrmSdk also contains some examples for extending the base Entity class. In the SilverCrmSoap project a UserOwnedEntitiy class has been added that extends the Entity class and raises the appropriate event when a field is changed. By default the SOAP Entity object only raises a property changed event if the Attributes object itself is changed. In addition to the UserOwnedEntity class which specifies the default fields for user owned entities, an Annotation class has been added that inherits from the UserOwnedEntity, adding the specific fields for notes. This type of extension becomes important when you are attempting to facilitate data-binding.

SilverCrmSoap.FetchXml

The FetchXml namespace provides a set of classes built according to the FetchXml schema to allow deserialization of FetchXml to support the modifying parameters through code, i.e. objectifying FetchXml. You will want to do this because a query expression does not return column values from another entity, and yet the reason why QueryExpressions are used so widely is because of their ability to easily be modified through code. By de-serializing the FetchXml query string, you will be able to edit it’s values using objects, then serialize it to use in your queries

SilverCrmSoap.Helpers

The SilverCrmSoap Library contains 3 helpers, the Xrmhelper, the FormHelper, and the SoapHelper.

XrmHelper

The XrmHelper provides on-demand access to the JScript objects that are commonly used such as the Xrm.Page, context, etc. It is also able to determine if the control was loaded as a web-resource on a form or if it was loaded outside a form. When using this helper, it is important to either put the web-resource on the form or put it on an html page that provides access to the GlobalContext.

FormHelper

FormHelper takes the XrmHelper and provides a couple of additional quick access methods that utilize the JScript objects XrmHelper provides:

  • GetUserPrivilege: Get the privileges for an attribute and determines if the user can read, update, or create.
  • GetEntityValue: Gets a value from the form using the Xrm.Page.data.entity.attributes JScript Object.
  • SetEntityValue: Sets a value from the form using the Xrm.Page.data.entity.attributes JScript Object.

SoapHelper

The SoapHelper was built to leverage the walkthrough for interfacing the SOAP End Point and provide a set of methods to launch the proper asynchronous call, simplifying access. One of the great things about these helpers is that you don’t need to specify the URL to use them. They leverage the context to correctly set the service URL. The SoapHelper provides a way to quickly connect to the SOAP End Point and a set of methods to jumpstart the begin statements of asynchronous SOAP calls:

  • BeginAssociate
  • BeginCreate
  • BeginUpdate
  • BeginDelete
  • BeginDisassociate
  • BeginExecute
  • BeginExecuteFetch
  • BeginExecuteRetrieveAllEntities

BeginExecuteRetrieveEntity